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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1230  ! damieng     4: # $Id: loncommon.pm,v 1.1229 2015/10/05 01:52:10 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.657     raeburn    74: use DateTime::TimeZone;
1.687     raeburn    75: use DateTime::Locale::Catalog;
1.1220    raeburn    76: use Encode();
1.1091    foxr       77: use Text::Aspell;
1.1094    raeburn    78: use Authen::Captcha;
                     79: use Captcha::reCAPTCHA;
1.1174    raeburn    80: use Crypt::DES;
                     81: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   82: use MIME::Lite;
                     83: use MIME::Types;
1.117     www        84: 
1.517     raeburn    85: # ---------------------------------------------- Designs
                     86: use vars qw(%defaultdesign);
                     87: 
1.22      www        88: my $readit;
                     89: 
1.517     raeburn    90: 
1.157     matthew    91: ##
                     92: ## Global Variables
                     93: ##
1.46      matthew    94: 
1.643     foxr       95: 
                     96: # ----------------------------------------------- SSI with retries:
                     97: #
                     98: 
                     99: =pod
                    100: 
1.648     raeburn   101: =head1 Server Side include with retries:
1.643     foxr      102: 
                    103: =over 4
                    104: 
1.648     raeburn   105: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      106: 
                    107: Performs an ssi with some number of retries.  Retries continue either
                    108: until the result is ok or until the retry count supplied by the
                    109: caller is exhausted.  
                    110: 
                    111: Inputs:
1.648     raeburn   112: 
                    113: =over 4
                    114: 
1.643     foxr      115: resource   - Identifies the resource to insert.
1.648     raeburn   116: 
1.643     foxr      117: retries    - Count of the number of retries allowed.
1.648     raeburn   118: 
1.643     foxr      119: form       - Hash that identifies the rendering options.
                    120: 
1.648     raeburn   121: =back
                    122: 
                    123: Returns:
                    124: 
                    125: =over 4
                    126: 
1.643     foxr      127: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   128: 
1.643     foxr      129: response   - The response from the last attempt (which may or may not have been successful.
                    130: 
1.648     raeburn   131: =back
                    132: 
                    133: =back
                    134: 
1.643     foxr      135: =cut
                    136: 
                    137: sub ssi_with_retries {
                    138:     my ($resource, $retries, %form) = @_;
                    139: 
                    140: 
                    141:     my $ok = 0;			# True if we got a good response.
                    142:     my $content;
                    143:     my $response;
                    144: 
                    145:     # Try to get the ssi done. within the retries count:
                    146: 
                    147:     do {
                    148: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    149: 	$ok      = $response->is_success;
1.650     www       150:         if (!$ok) {
                    151:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    152:         }
1.643     foxr      153: 	$retries--;
                    154:     } while (!$ok && ($retries > 0));
                    155: 
                    156:     if (!$ok) {
                    157: 	$content = '';		# On error return an empty content.
                    158:     }
                    159:     return ($content, $response);
                    160: 
                    161: }
                    162: 
                    163: 
                    164: 
1.20      www       165: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  166: my %language;
1.124     www       167: my %supported_language;
1.1088    foxr      168: my %supported_codes;
1.1048    foxr      169: my %latex_language;		# For choosing hyphenation in <transl..>
                    170: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  171: my %cprtag;
1.192     taceyjo1  172: my %scprtag;
1.351     www       173: my %fe; my %fd; my %fm;
1.41      ng        174: my %category_extensions;
1.12      harris41  175: 
1.46      matthew   176: # ---------------------------------------------- Thesaurus variables
1.144     matthew   177: #
                    178: # %Keywords:
                    179: #      A hash used by &keyword to determine if a word is considered a keyword.
                    180: # $thesaurus_db_file 
                    181: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   182: 
                    183: my %Keywords;
                    184: my $thesaurus_db_file;
                    185: 
1.144     matthew   186: #
                    187: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    188: # thesaurus.tab, and filecategories.tab.
                    189: #
1.18      www       190: BEGIN {
1.46      matthew   191:     # Variable initialization
                    192:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    193:     #
1.22      www       194:     unless ($readit) {
1.12      harris41  195: # ------------------------------------------------------------------- languages
                    196:     {
1.158     raeburn   197:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    198:                                    '/language.tab';
                    199:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  200:             while (my $line = <$fh>) {
                    201:                 next if ($line=~/^\#/);
                    202:                 chomp($line);
1.1088    foxr      203:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   204:                 $language{$key}=$val.' - '.$enc;
                    205:                 if ($sup) {
                    206:                     $supported_language{$key}=$sup;
1.1088    foxr      207: 		    $supported_codes{$key}   = $code;
1.158     raeburn   208:                 }
1.1048    foxr      209: 		if ($latex) {
                    210: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      211: 		    $latex_language{$code} = $latex;
1.1048    foxr      212: 		}
1.158     raeburn   213:             }
                    214:             close($fh);
                    215:         }
1.12      harris41  216:     }
                    217: # ------------------------------------------------------------------ copyrights
                    218:     {
1.158     raeburn   219:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    220:                                   '/copyright.tab';
                    221:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  222:             while (my $line = <$fh>) {
                    223:                 next if ($line=~/^\#/);
                    224:                 chomp($line);
                    225:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   226:                 $cprtag{$key}=$val;
                    227:             }
                    228:             close($fh);
                    229:         }
1.12      harris41  230:     }
1.351     www       231: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  232:     {
                    233:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    234:                                   '/source_copyright.tab';
                    235:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  236:             while (my $line = <$fh>) {
                    237:                 next if ($line =~ /^\#/);
                    238:                 chomp($line);
                    239:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  240:                 $scprtag{$key}=$val;
                    241:             }
                    242:             close($fh);
                    243:         }
                    244:     }
1.63      www       245: 
1.517     raeburn   246: # -------------------------------------------------------------- default domain designs
1.63      www       247:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   248:     my $designfile = $designdir.'/default.tab';
                    249:     if ( open (my $fh,"<$designfile") ) {
                    250:         while (my $line = <$fh>) {
                    251:             next if ($line =~ /^\#/);
                    252:             chomp($line);
                    253:             my ($key,$val)=(split(/\=/,$line));
                    254:             if ($val) { $defaultdesign{$key}=$val; }
                    255:         }
                    256:         close($fh);
1.63      www       257:     }
                    258: 
1.15      harris41  259: # ------------------------------------------------------------- file categories
                    260:     {
1.158     raeburn   261:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    262:                                   '/filecategories.tab';
                    263:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  264: 	    while (my $line = <$fh>) {
                    265: 		next if ($line =~ /^\#/);
                    266: 		chomp($line);
                    267:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   268:                 push @{$category_extensions{lc($category)}},$extension;
                    269:             }
                    270:             close($fh);
                    271:         }
                    272: 
1.15      harris41  273:     }
1.12      harris41  274: # ------------------------------------------------------------------ file types
                    275:     {
1.158     raeburn   276:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    277:                '/filetypes.tab';
                    278:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  279:             while (my $line = <$fh>) {
                    280: 		next if ($line =~ /^\#/);
                    281: 		chomp($line);
                    282:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   283:                 if ($descr ne '') {
                    284:                     $fe{$ending}=lc($emb);
                    285:                     $fd{$ending}=$descr;
1.351     www       286:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   287:                 }
                    288:             }
                    289:             close($fh);
                    290:         }
1.12      harris41  291:     }
1.22      www       292:     &Apache::lonnet::logthis(
1.705     tempelho  293:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       294:     $readit=1;
1.46      matthew   295:     }  # end of unless($readit) 
1.32      matthew   296:     
                    297: }
1.112     bowersj2  298: 
1.42      matthew   299: ###############################################################
                    300: ##           HTML and Javascript Helper Functions            ##
                    301: ###############################################################
                    302: 
                    303: =pod 
                    304: 
1.112     bowersj2  305: =head1 HTML and Javascript Functions
1.42      matthew   306: 
1.112     bowersj2  307: =over 4
                    308: 
1.648     raeburn   309: =item * &browser_and_searcher_javascript()
1.112     bowersj2  310: 
                    311: X<browsing, javascript>X<searching, javascript>Returns a string
                    312: containing javascript with two functions, C<openbrowser> and
                    313: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    314: tags.
1.42      matthew   315: 
1.648     raeburn   316: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   317: 
                    318: inputs: formname, elementname, only, omit
                    319: 
                    320: formname and elementname indicate the name of the html form and name of
                    321: the element that the results of the browsing selection are to be placed in. 
                    322: 
                    323: Specifying 'only' will restrict the browser to displaying only files
1.185     www       324: with the given extension.  Can be a comma separated list.
1.42      matthew   325: 
                    326: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       327: with the given extension.  Can be a comma separated list.
1.42      matthew   328: 
1.648     raeburn   329: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   330: 
                    331: Inputs: formname, elementname
                    332: 
                    333: formname and elementname specify the name of the html form and the name
                    334: of the element the selection from the search results will be placed in.
1.542     raeburn   335: 
1.42      matthew   336: =cut
                    337: 
                    338: sub browser_and_searcher_javascript {
1.199     albertel  339:     my ($mode)=@_;
                    340:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  341:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   342:     return <<END;
1.219     albertel  343: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   344:     var editbrowser = null;
1.135     albertel  345:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       346:         var url = '$resurl/?';
1.42      matthew   347:         if (editbrowser == null) {
                    348:             url += 'launch=1&';
                    349:         }
                    350:         url += 'catalogmode=interactive&';
1.199     albertel  351:         url += 'mode=$mode&';
1.611     albertel  352:         url += 'inhibitmenu=yes&';
1.42      matthew   353:         url += 'form=' + formname + '&';
                    354:         if (only != null) {
                    355:             url += 'only=' + only + '&';
1.217     albertel  356:         } else {
                    357:             url += 'only=&';
                    358: 	}
1.42      matthew   359:         if (omit != null) {
                    360:             url += 'omit=' + omit + '&';
1.217     albertel  361:         } else {
                    362:             url += 'omit=&';
                    363: 	}
1.135     albertel  364:         if (titleelement != null) {
                    365:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  366:         } else {
                    367: 	    url += 'titleelement=&';
                    368: 	}
1.42      matthew   369:         url += 'element=' + elementname + '';
                    370:         var title = 'Browser';
1.435     albertel  371:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   372:         options += ',width=700,height=600';
                    373:         editbrowser = open(url,title,options,'1');
                    374:         editbrowser.focus();
                    375:     }
                    376:     var editsearcher;
1.135     albertel  377:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   378:         var url = '/adm/searchcat?';
                    379:         if (editsearcher == null) {
                    380:             url += 'launch=1&';
                    381:         }
                    382:         url += 'catalogmode=interactive&';
1.199     albertel  383:         url += 'mode=$mode&';
1.42      matthew   384:         url += 'form=' + formname + '&';
1.135     albertel  385:         if (titleelement != null) {
                    386:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  387:         } else {
                    388: 	    url += 'titleelement=&';
                    389: 	}
1.42      matthew   390:         url += 'element=' + elementname + '';
                    391:         var title = 'Search';
1.435     albertel  392:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   393:         options += ',width=700,height=600';
                    394:         editsearcher = open(url,title,options,'1');
                    395:         editsearcher.focus();
                    396:     }
1.219     albertel  397: // END LON-CAPA Internal -->
1.42      matthew   398: END
1.170     www       399: }
                    400: 
                    401: sub lastresurl {
1.258     albertel  402:     if ($env{'environment.lastresurl'}) {
                    403: 	return $env{'environment.lastresurl'}
1.170     www       404:     } else {
                    405: 	return '/res';
                    406:     }
                    407: }
                    408: 
                    409: sub storeresurl {
                    410:     my $resurl=&Apache::lonnet::clutter(shift);
                    411:     unless ($resurl=~/^\/res/) { return 0; }
                    412:     $resurl=~s/\/$//;
                    413:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   414:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       415:     return 1;
1.42      matthew   416: }
                    417: 
1.74      www       418: sub studentbrowser_javascript {
1.111     www       419:    unless (
1.258     albertel  420:             (($env{'request.course.id'}) && 
1.302     albertel  421:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    422: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    423: 					  '/'.$env{'request.course.sec'})
                    424: 	      ))
1.258     albertel  425:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       426:           ) { return ''; }  
1.74      www       427:    return (<<'ENDSTDBRW');
1.776     bisitz    428: <script type="text/javascript" language="Javascript">
1.824     bisitz    429: // <![CDATA[
1.74      www       430:     var stdeditbrowser;
1.999     www       431:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       432:         var url = '/adm/pickstudent?';
                    433:         var filter;
1.558     albertel  434: 	if (!ignorefilter) {
                    435: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    436: 	}
1.74      www       437:         if (filter != null) {
                    438:            if (filter != '') {
                    439:                url += 'filter='+filter+'&';
                    440: 	   }
                    441:         }
                    442:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       443:                                     '&udomelement='+udom+
                    444:                                     '&clicker='+clicker;
1.111     www       445: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   446:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       447:         var title = 'Student_Browser';
1.74      www       448:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    449:         options += ',width=700,height=600';
                    450:         stdeditbrowser = open(url,title,options,'1');
                    451:         stdeditbrowser.focus();
                    452:     }
1.824     bisitz    453: // ]]>
1.74      www       454: </script>
                    455: ENDSTDBRW
                    456: }
1.42      matthew   457: 
1.1003    www       458: sub resourcebrowser_javascript {
                    459:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       460:    return (<<'ENDRESBRW');
1.1003    www       461: <script type="text/javascript" language="Javascript">
                    462: // <![CDATA[
                    463:     var reseditbrowser;
1.1004    www       464:     function openresbrowser(formname,reslink) {
1.1005    www       465:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       466:         var title = 'Resource_Browser';
                    467:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       468:         options += ',width=700,height=500';
1.1004    www       469:         reseditbrowser = open(url,title,options,'1');
                    470:         reseditbrowser.focus();
1.1003    www       471:     }
                    472: // ]]>
                    473: </script>
1.1004    www       474: ENDRESBRW
1.1003    www       475: }
                    476: 
1.74      www       477: sub selectstudent_link {
1.999     www       478:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    479:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    480:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    481:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  482:    if ($env{'request.course.id'}) {  
1.302     albertel  483:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    484: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    485: 					'/'.$env{'request.course.sec'})) {
1.111     www       486: 	   return '';
                    487:        }
1.999     www       488:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   489:        if ($courseadvonly)  {
                    490:            $callargs .= ",'',1,1";
                    491:        }
                    492:        return '<span class="LC_nobreak">'.
                    493:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    494:               &mt('Select User').'</a></span>';
1.74      www       495:    }
1.258     albertel  496:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       497:        $callargs .= ",'',1"; 
1.793     raeburn   498:        return '<span class="LC_nobreak">'.
                    499:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    500:               &mt('Select User').'</a></span>';
1.111     www       501:    }
                    502:    return '';
1.91      www       503: }
                    504: 
1.1004    www       505: sub selectresource_link {
                    506:    my ($form,$reslink,$arg)=@_;
                    507:    
                    508:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    509:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    510:    unless ($env{'request.course.id'}) { return $arg; }
                    511:    return '<span class="LC_nobreak">'.
                    512:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    513:               $arg.'</a></span>';
                    514: }
                    515: 
                    516: 
                    517: 
1.653     raeburn   518: sub authorbrowser_javascript {
                    519:     return <<"ENDAUTHORBRW";
1.776     bisitz    520: <script type="text/javascript" language="JavaScript">
1.824     bisitz    521: // <![CDATA[
1.653     raeburn   522: var stdeditbrowser;
                    523: 
                    524: function openauthorbrowser(formname,udom) {
                    525:     var url = '/adm/pickauthor?';
                    526:     url += 'form='+formname+'&roledom='+udom;
                    527:     var title = 'Author_Browser';
                    528:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    529:     options += ',width=700,height=600';
                    530:     stdeditbrowser = open(url,title,options,'1');
                    531:     stdeditbrowser.focus();
                    532: }
                    533: 
1.824     bisitz    534: // ]]>
1.653     raeburn   535: </script>
                    536: ENDAUTHORBRW
                    537: }
                    538: 
1.91      www       539: sub coursebrowser_javascript {
1.1116    raeburn   540:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   541:         $credits_element,$instcode) = @_;
1.932     raeburn   542:     my $wintitle = 'Course_Browser';
1.931     raeburn   543:     if ($crstype eq 'Community') {
1.932     raeburn   544:         $wintitle = 'Community_Browser';
1.909     raeburn   545:     }
1.876     raeburn   546:     my $id_functions = &javascript_index_functions();
                    547:     my $output = '
1.776     bisitz    548: <script type="text/javascript" language="JavaScript">
1.824     bisitz    549: // <![CDATA[
1.468     raeburn   550:     var stdeditbrowser;'."\n";
1.876     raeburn   551: 
                    552:     $output .= <<"ENDSTDBRW";
1.909     raeburn   553:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       554:         var url = '/adm/pickcourse?';
1.895     raeburn   555:         var formid = getFormIdByName(formname);
1.876     raeburn   556:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  557:         if (domainfilter != null) {
                    558:            if (domainfilter != '') {
                    559:                url += 'domainfilter='+domainfilter+'&';
                    560: 	   }
                    561:         }
1.91      www       562:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  563: 	                            '&cdomelement='+udom+
                    564:                                     '&cnameelement='+desc;
1.468     raeburn   565:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   566:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   567:                 url += '&roleelement='+extra_element;
                    568:                 if (domainfilter == null || domainfilter == '') {
                    569:                     url += '&domainfilter='+extra_element;
                    570:                 }
1.234     raeburn   571:             }
1.468     raeburn   572:             else {
                    573:                 if (formname == 'portform') {
                    574:                     url += '&setroles='+extra_element;
1.800     raeburn   575:                 } else {
                    576:                     if (formname == 'rules') {
                    577:                         url += '&fixeddom='+extra_element; 
                    578:                     }
1.468     raeburn   579:                 }
                    580:             }     
1.230     raeburn   581:         }
1.909     raeburn   582:         if (type != null && type != '') {
                    583:             url += '&type='+type;
                    584:         }
                    585:         if (type_elem != null && type_elem != '') {
                    586:             url += '&typeelement='+type_elem;
                    587:         }
1.872     raeburn   588:         if (formname == 'ccrs') {
                    589:             var ownername = document.forms[formid].ccuname.value;
                    590:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1221    raeburn   591:             url += '&cloner='+ownername+':'+ownerdom+'&crscode='+document.forms[formid].crscode.value;
                    592:         }
                    593:         if (formname == 'requestcrs') {
                    594:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   595:         }
1.293     raeburn   596:         if (multflag !=null && multflag != '') {
                    597:             url += '&multiple='+multflag;
                    598:         }
1.909     raeburn   599:         var title = '$wintitle';
1.91      www       600:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    601:         options += ',width=700,height=600';
                    602:         stdeditbrowser = open(url,title,options,'1');
                    603:         stdeditbrowser.focus();
                    604:     }
1.876     raeburn   605: $id_functions
                    606: ENDSTDBRW
1.1116    raeburn   607:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    608:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    609:                                       $credits_element);
1.876     raeburn   610:     }
                    611:     $output .= '
                    612: // ]]>
                    613: </script>';
                    614:     return $output;
                    615: }
                    616: 
                    617: sub javascript_index_functions {
                    618:     return <<"ENDJS";
                    619: 
                    620: function getFormIdByName(formname) {
                    621:     for (var i=0;i<document.forms.length;i++) {
                    622:         if (document.forms[i].name == formname) {
                    623:             return i;
                    624:         }
                    625:     }
                    626:     return -1;
                    627: }
                    628: 
                    629: function getIndexByName(formid,item) {
                    630:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    631:         if (document.forms[formid].elements[i].name == item) {
                    632:             return i;
                    633:         }
                    634:     }
                    635:     return -1;
                    636: }
1.468     raeburn   637: 
1.876     raeburn   638: function getDomainFromSelectbox(formname,udom) {
                    639:     var userdom;
                    640:     var formid = getFormIdByName(formname);
                    641:     if (formid > -1) {
                    642:         var domid = getIndexByName(formid,udom);
                    643:         if (domid > -1) {
                    644:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    645:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    646:             }
                    647:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    648:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   649:             }
                    650:         }
                    651:     }
1.876     raeburn   652:     return userdom;
                    653: }
                    654: 
                    655: ENDJS
1.468     raeburn   656: 
1.876     raeburn   657: }
                    658: 
1.1017    raeburn   659: sub javascript_array_indexof {
1.1018    raeburn   660:     return <<ENDJS;
1.1017    raeburn   661: <script type="text/javascript" language="JavaScript">
                    662: // <![CDATA[
                    663: 
                    664: if (!Array.prototype.indexOf) {
                    665:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    666:         "use strict";
                    667:         if (this === void 0 || this === null) {
                    668:             throw new TypeError();
                    669:         }
                    670:         var t = Object(this);
                    671:         var len = t.length >>> 0;
                    672:         if (len === 0) {
                    673:             return -1;
                    674:         }
                    675:         var n = 0;
                    676:         if (arguments.length > 0) {
                    677:             n = Number(arguments[1]);
1.1088    foxr      678:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   679:                 n = 0;
                    680:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    681:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    682:             }
                    683:         }
                    684:         if (n >= len) {
                    685:             return -1;
                    686:         }
                    687:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    688:         for (; k < len; k++) {
                    689:             if (k in t && t[k] === searchElement) {
                    690:                 return k;
                    691:             }
                    692:         }
                    693:         return -1;
                    694:     }
                    695: }
                    696: 
                    697: // ]]>
                    698: </script>
                    699: 
                    700: ENDJS
                    701: 
                    702: }
                    703: 
1.876     raeburn   704: sub userbrowser_javascript {
                    705:     my $id_functions = &javascript_index_functions();
                    706:     return <<"ENDUSERBRW";
                    707: 
1.888     raeburn   708: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   709:     var url = '/adm/pickuser?';
                    710:     var userdom = getDomainFromSelectbox(formname,udom);
                    711:     if (userdom != null) {
                    712:        if (userdom != '') {
                    713:            url += 'srchdom='+userdom+'&';
                    714:        }
                    715:     }
                    716:     url += 'form=' + formname + '&unameelement='+uname+
                    717:                                 '&udomelement='+udom+
                    718:                                 '&ulastelement='+ulast+
                    719:                                 '&ufirstelement='+ufirst+
                    720:                                 '&uemailelement='+uemail+
1.881     raeburn   721:                                 '&hideudomelement='+hideudom+
                    722:                                 '&coursedom='+crsdom;
1.888     raeburn   723:     if ((caller != null) && (caller != undefined)) {
                    724:         url += '&caller='+caller;
                    725:     }
1.876     raeburn   726:     var title = 'User_Browser';
                    727:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    728:     options += ',width=700,height=600';
                    729:     var stdeditbrowser = open(url,title,options,'1');
                    730:     stdeditbrowser.focus();
                    731: }
                    732: 
1.888     raeburn   733: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   734:     var formid = getFormIdByName(formname);
                    735:     if (formid > -1) {
1.888     raeburn   736:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   737:         var domid = getIndexByName(formid,udom);
                    738:         var hidedomid = getIndexByName(formid,origdom);
                    739:         if (hidedomid > -1) {
                    740:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   741:             var unameval = document.forms[formid].elements[unameid].value;
                    742:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    743:                 if (domid > -1) {
                    744:                     var slct = document.forms[formid].elements[domid];
                    745:                     if (slct.type == 'select-one') {
                    746:                         var i;
                    747:                         for (i=0;i<slct.length;i++) {
                    748:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    749:                         }
                    750:                     }
                    751:                     if (slct.type == 'hidden') {
                    752:                         slct.value = fixeddom;
1.876     raeburn   753:                     }
                    754:                 }
1.468     raeburn   755:             }
                    756:         }
                    757:     }
1.876     raeburn   758:     return;
                    759: }
                    760: 
                    761: $id_functions
                    762: ENDUSERBRW
1.468     raeburn   763: }
                    764: 
                    765: sub setsec_javascript {
1.1116    raeburn   766:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   767:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    768:         $communityrolestr);
                    769:     if ($role_element ne '') {
                    770:         my @allroles = ('st','ta','ep','in','ad');
                    771:         foreach my $crstype ('Course','Community') {
                    772:             if ($crstype eq 'Community') {
                    773:                 foreach my $role (@allroles) {
                    774:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    775:                 }
                    776:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    777:             } else {
                    778:                 foreach my $role (@allroles) {
                    779:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    780:                 }
                    781:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    782:             }
                    783:         }
                    784:         $rolestr = '"'.join('","',@allroles).'"';
                    785:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    786:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    787:     }
1.468     raeburn   788:     my $setsections = qq|
                    789: function setSect(sectionlist) {
1.629     raeburn   790:     var sectionsArray = new Array();
                    791:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    792:         sectionsArray = sectionlist.split(",");
                    793:     }
1.468     raeburn   794:     var numSections = sectionsArray.length;
                    795:     document.$formname.$sec_element.length = 0;
                    796:     if (numSections == 0) {
                    797:         document.$formname.$sec_element.multiple=false;
                    798:         document.$formname.$sec_element.size=1;
                    799:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    800:     } else {
                    801:         if (numSections == 1) {
                    802:             document.$formname.$sec_element.multiple=false;
                    803:             document.$formname.$sec_element.size=1;
                    804:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    805:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    806:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    807:         } else {
                    808:             for (var i=0; i<numSections; i++) {
                    809:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    810:             }
                    811:             document.$formname.$sec_element.multiple=true
                    812:             if (numSections < 3) {
                    813:                 document.$formname.$sec_element.size=numSections;
                    814:             } else {
                    815:                 document.$formname.$sec_element.size=3;
                    816:             }
                    817:             document.$formname.$sec_element.options[0].selected = false
                    818:         }
                    819:     }
1.91      www       820: }
1.905     raeburn   821: 
                    822: function setRole(crstype) {
1.468     raeburn   823: |;
1.905     raeburn   824:     if ($role_element eq '') {
                    825:         $setsections .= '    return;
                    826: }
                    827: ';
                    828:     } else {
                    829:         $setsections .= qq|
                    830:     var elementLength = document.$formname.$role_element.length;
                    831:     var allroles = Array($rolestr);
                    832:     var courserolenames = Array($courserolestr);
                    833:     var communityrolenames = Array($communityrolestr);
                    834:     if (elementLength != undefined) {
                    835:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    836:             if (crstype == 'Course') {
                    837:                 return;
                    838:             } else {
                    839:                 allroles[5] = 'co';
                    840:                 for (var i=0; i<6; i++) {
                    841:                     document.$formname.$role_element.options[i].value = allroles[i];
                    842:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    843:                 }
                    844:             }
                    845:         } else {
                    846:             if (crstype == 'Community') {
                    847:                 return;
                    848:             } else {
                    849:                 allroles[5] = 'cc';
                    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 = courserolenames[i];
                    853:                 }
                    854:             }
                    855:         }
                    856:     }
                    857:     return;
                    858: }
                    859: |;
                    860:     }
1.1116    raeburn   861:     if ($credits_element) {
                    862:         $setsections .= qq|
                    863: function setCredits(defaultcredits) {
                    864:     document.$formname.$credits_element.value = defaultcredits;
                    865:     return;
                    866: }
                    867: |;
                    868:     }
1.468     raeburn   869:     return $setsections;
                    870: }
                    871: 
1.91      www       872: sub selectcourse_link {
1.909     raeburn   873:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    874:        $typeelement) = @_;
                    875:    my $type = $selecttype;
1.871     raeburn   876:    my $linktext = &mt('Select Course');
                    877:    if ($selecttype eq 'Community') {
1.909     raeburn   878:        $linktext = &mt('Select Community');
1.906     raeburn   879:    } elsif ($selecttype eq 'Course/Community') {
                    880:        $linktext = &mt('Select Course/Community');
1.909     raeburn   881:        $type = '';
1.1019    raeburn   882:    } elsif ($selecttype eq 'Select') {
                    883:        $linktext = &mt('Select');
                    884:        $type = '';
1.871     raeburn   885:    }
1.787     bisitz    886:    return '<span class="LC_nobreak">'
                    887:          ."<a href='"
                    888:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    889:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   890:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   891:          ."'>".$linktext.'</a>'
1.787     bisitz    892:          .'</span>';
1.74      www       893: }
1.42      matthew   894: 
1.653     raeburn   895: sub selectauthor_link {
                    896:    my ($form,$udom)=@_;
                    897:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    898:           &mt('Select Author').'</a>';
                    899: }
                    900: 
1.876     raeburn   901: sub selectuser_link {
1.881     raeburn   902:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   903:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   904:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   905:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   906:            ');">'.$linktext.'</a>';
1.876     raeburn   907: }
                    908: 
1.273     raeburn   909: sub check_uncheck_jscript {
                    910:     my $jscript = <<"ENDSCRT";
                    911: function checkAll(field) {
                    912:     if (field.length > 0) {
                    913:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   914:             if (!field[i].disabled) { 
                    915:                 field[i].checked = true;
                    916:             }
1.273     raeburn   917:         }
                    918:     } else {
1.1093    raeburn   919:         if (!field.disabled) { 
                    920:             field.checked = true;
                    921:         }
1.273     raeburn   922:     }
                    923: }
                    924:  
                    925: function uncheckAll(field) {
                    926:     if (field.length > 0) {
                    927:         for (i = 0; i < field.length; i++) {
                    928:             field[i].checked = false ;
1.543     albertel  929:         }
                    930:     } else {
1.273     raeburn   931:         field.checked = false ;
                    932:     }
                    933: }
                    934: ENDSCRT
                    935:     return $jscript;
                    936: }
                    937: 
1.656     www       938: sub select_timezone {
1.659     raeburn   939:    my ($name,$selected,$onchange,$includeempty)=@_;
                    940:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    941:    if ($includeempty) {
                    942:        $output .= '<option value=""';
                    943:        if (($selected eq '') || ($selected eq 'local')) {
                    944:            $output .= ' selected="selected" ';
                    945:        }
                    946:        $output .= '> </option>';
                    947:    }
1.657     raeburn   948:    my @timezones = DateTime::TimeZone->all_names;
                    949:    foreach my $tzone (@timezones) {
                    950:        $output.= '<option value="'.$tzone.'"';
                    951:        if ($tzone eq $selected) {
                    952:            $output.=' selected="selected"';
                    953:        }
                    954:        $output.=">$tzone</option>\n";
1.656     www       955:    }
                    956:    $output.="</select>";
                    957:    return $output;
                    958: }
1.273     raeburn   959: 
1.687     raeburn   960: sub select_datelocale {
                    961:     my ($name,$selected,$onchange,$includeempty)=@_;
                    962:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    963:     if ($includeempty) {
                    964:         $output .= '<option value=""';
                    965:         if ($selected eq '') {
                    966:             $output .= ' selected="selected" ';
                    967:         }
                    968:         $output .= '> </option>';
                    969:     }
                    970:     my (@possibles,%locale_names);
                    971:     my @locales = DateTime::Locale::Catalog::Locales;
                    972:     foreach my $locale (@locales) {
                    973:         if (ref($locale) eq 'HASH') {
                    974:             my $id = $locale->{'id'};
                    975:             if ($id ne '') {
                    976:                 my $en_terr = $locale->{'en_territory'};
                    977:                 my $native_terr = $locale->{'native_territory'};
1.695     raeburn   978:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   979:                 if (grep(/^en$/,@languages) || !@languages) {
                    980:                     if ($en_terr ne '') {
                    981:                         $locale_names{$id} = '('.$en_terr.')';
                    982:                     } elsif ($native_terr ne '') {
                    983:                         $locale_names{$id} = $native_terr;
                    984:                     }
                    985:                 } else {
                    986:                     if ($native_terr ne '') {
                    987:                         $locale_names{$id} = $native_terr.' ';
                    988:                     } elsif ($en_terr ne '') {
                    989:                         $locale_names{$id} = '('.$en_terr.')';
                    990:                     }
                    991:                 }
1.1220    raeburn   992:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.687     raeburn   993:                 push (@possibles,$id);
                    994:             }
                    995:         }
                    996:     }
                    997:     foreach my $item (sort(@possibles)) {
                    998:         $output.= '<option value="'.$item.'"';
                    999:         if ($item eq $selected) {
                   1000:             $output.=' selected="selected"';
                   1001:         }
                   1002:         $output.=">$item";
                   1003:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1004:             $output.='  '.$locale_names{$item};
1.687     raeburn  1005:         }
                   1006:         $output.="</option>\n";
                   1007:     }
                   1008:     $output.="</select>";
                   1009:     return $output;
                   1010: }
                   1011: 
1.792     raeburn  1012: sub select_language {
                   1013:     my ($name,$selected,$includeempty) = @_;
                   1014:     my %langchoices;
                   1015:     if ($includeempty) {
1.1117    raeburn  1016:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1017:     }
                   1018:     foreach my $id (&languageids()) {
                   1019:         my $code = &supportedlanguagecode($id);
                   1020:         if ($code) {
                   1021:             $langchoices{$code} = &plainlanguagedescription($id);
                   1022:         }
                   1023:     }
1.1117    raeburn  1024:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.970     raeburn  1025:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1026: }
                   1027: 
1.42      matthew  1028: =pod
1.36      matthew  1029: 
1.1088    foxr     1030: 
                   1031: =item * &list_languages()
                   1032: 
                   1033: Returns an array reference that is suitable for use in language prompters.
                   1034: Each array element is itself a two element array.  The first element
                   1035: is the language code.  The second element a descsriptiuon of the 
                   1036: language itself.  This is suitable for use in e.g.
                   1037: &Apache::edit::select_arg (once dereferenced that is).
                   1038: 
                   1039: =cut 
                   1040: 
                   1041: sub list_languages {
                   1042:     my @lang_choices;
                   1043: 
                   1044:     foreach my $id (&languageids()) {
                   1045: 	my $code = &supportedlanguagecode($id);
                   1046: 	if ($code) {
                   1047: 	    my $selector    = $supported_codes{$id};
                   1048: 	    my $description = &plainlanguagedescription($id);
                   1049: 	    push (@lang_choices, [$selector, $description]);
                   1050: 	}
                   1051:     }
                   1052:     return \@lang_choices;
                   1053: }
                   1054: 
                   1055: =pod
                   1056: 
1.648     raeburn  1057: =item * &linked_select_forms(...)
1.36      matthew  1058: 
                   1059: linked_select_forms returns a string containing a <script></script> block
                   1060: and html for two <select> menus.  The select menus will be linked in that
                   1061: changing the value of the first menu will result in new values being placed
                   1062: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1063: order unless a defined order is provided.
1.36      matthew  1064: 
                   1065: linked_select_forms takes the following ordered inputs:
                   1066: 
                   1067: =over 4
                   1068: 
1.112     bowersj2 1069: =item * $formname, the name of the <form> tag
1.36      matthew  1070: 
1.112     bowersj2 1071: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1072: 
1.112     bowersj2 1073: =item * $firstdefault, the default value for the first menu
1.36      matthew  1074: 
1.112     bowersj2 1075: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1076: 
1.112     bowersj2 1077: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1078: 
1.112     bowersj2 1079: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1080: 
1.609     raeburn  1081: =item * $menuorder, the order of values in the first menu
                   1082: 
1.1115    raeburn  1083: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1084:         event for the first <select> tag
                   1085: 
                   1086: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1087:         event for the second <select> tag
                   1088: 
1.41      ng       1089: =back 
                   1090: 
1.36      matthew  1091: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1092: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1093: values for the first select menu.  The text that coincides with the 
1.41      ng       1094: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1095: and text for the second menu are given in the hash pointed to by 
                   1096: $menu{$choice1}->{'select2'}.  
                   1097: 
1.112     bowersj2 1098:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1099:                        default => "B3",
                   1100:                        select2 => { 
                   1101:                            B1 => "Choice B1",
                   1102:                            B2 => "Choice B2",
                   1103:                            B3 => "Choice B3",
                   1104:                            B4 => "Choice B4"
1.609     raeburn  1105:                            },
                   1106:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1107:                    },
                   1108:                A2 => { text =>"Choice A2" ,
                   1109:                        default => "C2",
                   1110:                        select2 => { 
                   1111:                            C1 => "Choice C1",
                   1112:                            C2 => "Choice C2",
                   1113:                            C3 => "Choice C3"
1.609     raeburn  1114:                            },
                   1115:                        order => ['C2','C1','C3'],
1.112     bowersj2 1116:                    },
                   1117:                A3 => { text =>"Choice A3" ,
                   1118:                        default => "D6",
                   1119:                        select2 => { 
                   1120:                            D1 => "Choice D1",
                   1121:                            D2 => "Choice D2",
                   1122:                            D3 => "Choice D3",
                   1123:                            D4 => "Choice D4",
                   1124:                            D5 => "Choice D5",
                   1125:                            D6 => "Choice D6",
                   1126:                            D7 => "Choice D7"
1.609     raeburn  1127:                            },
                   1128:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1129:                    }
                   1130:                );
1.36      matthew  1131: 
                   1132: =cut
                   1133: 
                   1134: sub linked_select_forms {
                   1135:     my ($formname,
                   1136:         $middletext,
                   1137:         $firstdefault,
                   1138:         $firstselectname,
                   1139:         $secondselectname, 
1.609     raeburn  1140:         $hashref,
                   1141:         $menuorder,
1.1115    raeburn  1142:         $onchangefirst,
                   1143:         $onchangesecond
1.36      matthew  1144:         ) = @_;
                   1145:     my $second = "document.$formname.$secondselectname";
                   1146:     my $first = "document.$formname.$firstselectname";
                   1147:     # output the javascript to do the changing
                   1148:     my $result = '';
1.776     bisitz   1149:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1150:     $result.="// <![CDATA[\n";
1.36      matthew  1151:     $result.="var select2data = new Object();\n";
                   1152:     $" = '","';
                   1153:     my $debug = '';
                   1154:     foreach my $s1 (sort(keys(%$hashref))) {
                   1155:         $result.="select2data.d_$s1 = new Object();\n";        
                   1156:         $result.="select2data.d_$s1.def = new String('".
                   1157:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1158:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1159:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1160:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1161:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1162:         }
1.36      matthew  1163:         $result.="\"@s2values\");\n";
                   1164:         $result.="select2data.d_$s1.texts = new Array(";        
                   1165:         my @s2texts;
                   1166:         foreach my $value (@s2values) {
                   1167:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1168:         }
                   1169:         $result.="\"@s2texts\");\n";
                   1170:     }
                   1171:     $"=' ';
                   1172:     $result.= <<"END";
                   1173: 
                   1174: function select1_changed() {
                   1175:     // Determine new choice
                   1176:     var newvalue = "d_" + $first.value;
                   1177:     // update select2
                   1178:     var values     = select2data[newvalue].values;
                   1179:     var texts      = select2data[newvalue].texts;
                   1180:     var select2def = select2data[newvalue].def;
                   1181:     var i;
                   1182:     // out with the old
                   1183:     for (i = 0; i < $second.options.length; i++) {
                   1184:         $second.options[i] = null;
                   1185:     }
                   1186:     // in with the nuclear
                   1187:     for (i=0;i<values.length; i++) {
                   1188:         $second.options[i] = new Option(values[i]);
1.143     matthew  1189:         $second.options[i].value = values[i];
1.36      matthew  1190:         $second.options[i].text = texts[i];
                   1191:         if (values[i] == select2def) {
                   1192:             $second.options[i].selected = true;
                   1193:         }
                   1194:     }
                   1195: }
1.824     bisitz   1196: // ]]>
1.36      matthew  1197: </script>
                   1198: END
                   1199:     # output the initial values for the selection lists
1.1115    raeburn  1200:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1201:     my @order = sort(keys(%{$hashref}));
                   1202:     if (ref($menuorder) eq 'ARRAY') {
                   1203:         @order = @{$menuorder};
                   1204:     }
                   1205:     foreach my $value (@order) {
1.36      matthew  1206:         $result.="    <option value=\"$value\" ";
1.253     albertel 1207:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1208:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1209:     }
                   1210:     $result .= "</select>\n";
                   1211:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1212:     $result .= $middletext;
1.1115    raeburn  1213:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1214:     if ($onchangesecond) {
                   1215:         $result .= ' onchange="'.$onchangesecond.'"';
                   1216:     }
                   1217:     $result .= ">\n";
1.36      matthew  1218:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1219:     
                   1220:     my @secondorder = sort(keys(%select2));
                   1221:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1222:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1223:     }
                   1224:     foreach my $value (@secondorder) {
1.36      matthew  1225:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1226:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1227:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1228:     }
                   1229:     $result .= "</select>\n";
                   1230:     #    return $debug;
                   1231:     return $result;
                   1232: }   #  end of sub linked_select_forms {
                   1233: 
1.45      matthew  1234: =pod
1.44      bowersj2 1235: 
1.973     raeburn  1236: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1237: 
1.112     bowersj2 1238: Returns a string corresponding to an HTML link to the given help
                   1239: $topic, where $topic corresponds to the name of a .tex file in
                   1240: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1241: spaces. 
                   1242: 
                   1243: $text will optionally be linked to the same topic, allowing you to
                   1244: link text in addition to the graphic. If you do not want to link
                   1245: text, but wish to specify one of the later parameters, pass an
                   1246: empty string. 
                   1247: 
                   1248: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1249: the link will not open a new window. If false, the link will open
                   1250: a new window using Javascript. (Default is false.) 
                   1251: 
                   1252: $width and $height are optional numerical parameters that will
                   1253: override the width and height of the popped up window, which may
1.973     raeburn  1254: be useful for certain help topics with big pictures included.
                   1255: 
                   1256: $imgid is the id of the img tag used for the help icon. This may be
                   1257: used in a javascript call to switch the image src.  See 
                   1258: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1259: 
                   1260: =cut
                   1261: 
                   1262: sub help_open_topic {
1.973     raeburn  1263:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1264:     $text = "" if (not defined $text);
1.44      bowersj2 1265:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1266:     $width = 500 if (not defined $width);
1.44      bowersj2 1267:     $height = 400 if (not defined $height);
                   1268:     my $filename = $topic;
                   1269:     $filename =~ s/ /_/g;
                   1270: 
1.48      bowersj2 1271:     my $template = "";
                   1272:     my $link;
1.572     banghart 1273:     
1.159     www      1274:     $topic=~s/\W/\_/g;
1.44      bowersj2 1275: 
1.572     banghart 1276:     if (!$stayOnPage) {
1.1033    www      1277: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1278:     } elsif ($stayOnPage eq 'popup') {
                   1279:         $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 1280:     } else {
1.48      bowersj2 1281: 	$link = "/adm/help/${filename}.hlp";
                   1282:     }
                   1283: 
                   1284:     # Add the text
1.755     neumanie 1285:     if ($text ne "") {	
1.763     bisitz   1286: 	$template.='<span class="LC_help_open_topic">'
                   1287:                   .'<a target="_top" href="'.$link.'">'
                   1288:                   .$text.'</a>';
1.48      bowersj2 1289:     }
                   1290: 
1.763     bisitz   1291:     # (Always) Add the graphic
1.179     matthew  1292:     my $title = &mt('Online Help');
1.667     raeburn  1293:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1294:     if ($imgid ne '') {
                   1295:         $imgid = ' id="'.$imgid.'"';
                   1296:     }
1.763     bisitz   1297:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1298:               .'<img src="'.$helpicon.'" border="0"'
                   1299:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1300:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1301:               .' /></a>';
                   1302:     if ($text ne "") {	
                   1303:         $template.='</span>';
                   1304:     }
1.44      bowersj2 1305:     return $template;
                   1306: 
1.106     bowersj2 1307: }
                   1308: 
                   1309: # This is a quicky function for Latex cheatsheet editing, since it 
                   1310: # appears in at least four places
                   1311: sub helpLatexCheatsheet {
1.1037    www      1312:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1313:     my $out;
1.106     bowersj2 1314:     my $addOther = '';
1.732     raeburn  1315:     if ($topic) {
1.1037    www      1316: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1317:     }
                   1318:     $out = '<span>' # Start cheatsheet
                   1319: 	  .$addOther
                   1320:           .'<span>'
1.1037    www      1321: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1322: 	  .'</span> <span>'
1.1037    www      1323: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1324: 	  .'</span>';
1.732     raeburn  1325:     unless ($not_author) {
1.1186    kruse    1326:         $out .= '<span>'
                   1327:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1328:                .'</span> <span>'
                   1329:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1330: 	       .'</span>';
1.732     raeburn  1331:     }
1.763     bisitz   1332:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1333:     return $out;
1.172     www      1334: }
                   1335: 
1.430     albertel 1336: sub general_help {
                   1337:     my $helptopic='Student_Intro';
                   1338:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1339: 	$helptopic='Authoring_Intro';
1.907     raeburn  1340:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1341: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1342:     } elsif ($env{'request.role'}=~/^dc/) {
                   1343:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1344:     }
                   1345:     return $helptopic;
                   1346: }
                   1347: 
                   1348: sub update_help_link {
                   1349:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1350:     my $origurl = $ENV{'REQUEST_URI'};
                   1351:     $origurl=~s|^/~|/priv/|;
                   1352:     my $timestamp = time;
                   1353:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1354:         $$datum = &escape($$datum);
                   1355:     }
                   1356: 
                   1357:     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";
                   1358:     my $output .= <<"ENDOUTPUT";
                   1359: <script type="text/javascript">
1.824     bisitz   1360: // <![CDATA[
1.430     albertel 1361: banner_link = '$banner_link';
1.824     bisitz   1362: // ]]>
1.430     albertel 1363: </script>
                   1364: ENDOUTPUT
                   1365:     return $output;
                   1366: }
                   1367: 
                   1368: # now just updates the help link and generates a blue icon
1.193     raeburn  1369: sub help_open_menu {
1.430     albertel 1370:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1371: 	= @_;    
1.949     droeschl 1372:     $stayOnPage = 1;
1.430     albertel 1373:     my $output;
                   1374:     if ($component_help) {
                   1375: 	if (!$text) {
                   1376: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1377: 				       $width,$height);
                   1378: 	} else {
                   1379: 	    my $help_text;
                   1380: 	    $help_text=&unescape($topic);
                   1381: 	    $output='<table><tr><td>'.
                   1382: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1383: 				 $width,$height).'</td></tr></table>';
                   1384: 	}
                   1385:     }
                   1386:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1387:     return $output.$banner_link;
                   1388: }
                   1389: 
                   1390: sub top_nav_help {
                   1391:     my ($text) = @_;
1.436     albertel 1392:     $text = &mt($text);
1.949     droeschl 1393:     my $stay_on_page = 1;
                   1394: 
1.1168    raeburn  1395:     my ($link,$banner_link);
                   1396:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1397:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1398: 	                         : "javascript:helpMenu('open')";
                   1399:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1400:     }
1.201     raeburn  1401:     my $title = &mt('Get help');
1.1168    raeburn  1402:     if ($link) {
                   1403:         return <<"END";
1.436     albertel 1404: $banner_link
1.1159    raeburn  1405: <a href="$link" title="$title">$text</a>
1.436     albertel 1406: END
1.1168    raeburn  1407:     } else {
                   1408:         return '&nbsp;'.$text.'&nbsp;';
                   1409:     }
1.436     albertel 1410: }
                   1411: 
                   1412: sub help_menu_js {
1.1154    raeburn  1413:     my ($httphost) = @_;
1.949     droeschl 1414:     my $stayOnPage = 1;
1.436     albertel 1415:     my $width = 620;
                   1416:     my $height = 600;
1.430     albertel 1417:     my $helptopic=&general_help();
1.1154    raeburn  1418:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1419:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1420:     my $start_page =
                   1421:         &Apache::loncommon::start_page('Help Menu', undef,
                   1422: 				       {'frameset'    => 1,
                   1423: 					'js_ready'    => 1,
1.1154    raeburn  1424:                                         'use_absolute' => $httphost,
1.331     albertel 1425: 					'add_entries' => {
1.1168    raeburn  1426: 					    'border' => '0', 
1.579     raeburn  1427: 					    'rows'   => "110,*",},});
1.331     albertel 1428:     my $end_page =
                   1429:         &Apache::loncommon::end_page({'frameset' => 1,
                   1430: 				      'js_ready' => 1,});
                   1431: 
1.436     albertel 1432:     my $template .= <<"ENDTEMPLATE";
                   1433: <script type="text/javascript">
1.877     bisitz   1434: // <![CDATA[
1.253     albertel 1435: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1436: var banner_link = '';
1.243     raeburn  1437: function helpMenu(target) {
                   1438:     var caller = this;
                   1439:     if (target == 'open') {
                   1440:         var newWindow = null;
                   1441:         try {
1.262     albertel 1442:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1443:         }
                   1444:         catch(error) {
                   1445:             writeHelp(caller);
                   1446:             return;
                   1447:         }
                   1448:         if (newWindow) {
                   1449:             caller = newWindow;
                   1450:         }
1.193     raeburn  1451:     }
1.243     raeburn  1452:     writeHelp(caller);
                   1453:     return;
                   1454: }
                   1455: function writeHelp(caller) {
1.1168    raeburn  1456:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1457:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1458:     caller.document.close();
                   1459:     caller.focus();
1.193     raeburn  1460: }
1.877     bisitz   1461: // END LON-CAPA Internal -->
1.253     albertel 1462: // ]]>
1.436     albertel 1463: </script>
1.193     raeburn  1464: ENDTEMPLATE
                   1465:     return $template;
                   1466: }
                   1467: 
1.172     www      1468: sub help_open_bug {
                   1469:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1470:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1471:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1472:     $text = "" if (not defined $text);
                   1473: 	$stayOnPage=1;
1.184     albertel 1474:     $width = 600 if (not defined $width);
                   1475:     $height = 600 if (not defined $height);
1.172     www      1476: 
                   1477:     $topic=~s/\W+/\+/g;
                   1478:     my $link='';
                   1479:     my $template='';
1.379     albertel 1480:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1481: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1482:     if (!$stayOnPage)
                   1483:     {
                   1484: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1485:     }
                   1486:     else
                   1487:     {
                   1488: 	$link = $url;
                   1489:     }
                   1490:     # Add the text
                   1491:     if ($text ne "")
                   1492:     {
                   1493: 	$template .= 
                   1494:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1495:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1496:     }
                   1497: 
                   1498:     # Add the graphic
1.179     matthew  1499:     my $title = &mt('Report a Bug');
1.215     albertel 1500:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1501:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1502:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1503: ENDTEMPLATE
                   1504:     if ($text ne '') { $template.='</td></tr></table>' };
                   1505:     return $template;
                   1506: 
                   1507: }
                   1508: 
                   1509: sub help_open_faq {
                   1510:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1511:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1512:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1513:     $text = "" if (not defined $text);
                   1514: 	$stayOnPage=1;
                   1515:     $width = 350 if (not defined $width);
                   1516:     $height = 400 if (not defined $height);
                   1517: 
                   1518:     $topic=~s/\W+/\+/g;
                   1519:     my $link='';
                   1520:     my $template='';
                   1521:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1522:     if (!$stayOnPage)
                   1523:     {
                   1524: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1525:     }
                   1526:     else
                   1527:     {
                   1528: 	$link = $url;
                   1529:     }
                   1530: 
                   1531:     # Add the text
                   1532:     if ($text ne "")
                   1533:     {
                   1534: 	$template .= 
1.173     www      1535:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1536:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1537:     }
                   1538: 
                   1539:     # Add the graphic
1.179     matthew  1540:     my $title = &mt('View the FAQ');
1.215     albertel 1541:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1542:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1543:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1544: ENDTEMPLATE
                   1545:     if ($text ne '') { $template.='</td></tr></table>' };
                   1546:     return $template;
                   1547: 
1.44      bowersj2 1548: }
1.37      matthew  1549: 
1.180     matthew  1550: ###############################################################
                   1551: ###############################################################
                   1552: 
1.45      matthew  1553: =pod
                   1554: 
1.648     raeburn  1555: =item * &change_content_javascript():
1.256     matthew  1556: 
                   1557: This and the next function allow you to create small sections of an
                   1558: otherwise static HTML page that you can update on the fly with
                   1559: Javascript, even in Netscape 4.
                   1560: 
                   1561: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1562: must be written to the HTML page once. It will prove the Javascript
                   1563: function "change(name, content)". Calling the change function with the
                   1564: name of the section 
                   1565: you want to update, matching the name passed to C<changable_area>, and
                   1566: the new content you want to put in there, will put the content into
                   1567: that area.
                   1568: 
                   1569: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1570: to contain room for the original contents. You need to "make space"
                   1571: for whatever changes you wish to make, and be B<sure> to check your
                   1572: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1573: it's adequate for updating a one-line status display, but little more.
                   1574: This script will set the space to 100% width, so you only need to
                   1575: worry about height in Netscape 4.
                   1576: 
                   1577: Modern browsers are much less limiting, and if you can commit to the
                   1578: user not using Netscape 4, this feature may be used freely with
                   1579: pretty much any HTML.
                   1580: 
                   1581: =cut
                   1582: 
                   1583: sub change_content_javascript {
                   1584:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1585:     if ($env{'browser.type'} eq 'netscape' &&
                   1586: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1587: 	return (<<NETSCAPE4);
                   1588: 	function change(name, content) {
                   1589: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1590: 	    doc.open();
                   1591: 	    doc.write(content);
                   1592: 	    doc.close();
                   1593: 	}
                   1594: NETSCAPE4
                   1595:     } else {
                   1596: 	# Otherwise, we need to use semi-standards-compliant code
                   1597: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1598: 	# is really scary, and every useful browser supports it
                   1599: 	return (<<DOMBASED);
                   1600: 	function change(name, content) {
                   1601: 	    element = document.getElementById(name);
                   1602: 	    element.innerHTML = content;
                   1603: 	}
                   1604: DOMBASED
                   1605:     }
                   1606: }
                   1607: 
                   1608: =pod
                   1609: 
1.648     raeburn  1610: =item * &changable_area($name,$origContent):
1.256     matthew  1611: 
                   1612: This provides a "changable area" that can be modified on the fly via
                   1613: the Javascript code provided in C<change_content_javascript>. $name is
                   1614: the name you will use to reference the area later; do not repeat the
                   1615: same name on a given HTML page more then once. $origContent is what
                   1616: the area will originally contain, which can be left blank.
                   1617: 
                   1618: =cut
                   1619: 
                   1620: sub changable_area {
                   1621:     my ($name, $origContent) = @_;
                   1622: 
1.258     albertel 1623:     if ($env{'browser.type'} eq 'netscape' &&
                   1624: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1625: 	# If this is netscape 4, we need to use the Layer tag
                   1626: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1627:     } else {
                   1628: 	return "<span id='$name'>$origContent</span>";
                   1629:     }
                   1630: }
                   1631: 
                   1632: =pod
                   1633: 
1.648     raeburn  1634: =item * &viewport_geometry_js 
1.590     raeburn  1635: 
                   1636: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1637: 
                   1638: =cut
                   1639: 
                   1640: 
                   1641: sub viewport_geometry_js { 
                   1642:     return <<"GEOMETRY";
                   1643: var Geometry = {};
                   1644: function init_geometry() {
                   1645:     if (Geometry.init) { return };
                   1646:     Geometry.init=1;
                   1647:     if (window.innerHeight) {
                   1648:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1649:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1650:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1651:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1652:     }
                   1653:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1654:         Geometry.getViewportHeight =
                   1655:             function() { return document.documentElement.clientHeight; };
                   1656:         Geometry.getViewportWidth =
                   1657:             function() { return document.documentElement.clientWidth; };
                   1658: 
                   1659:         Geometry.getHorizontalScroll =
                   1660:             function() { return document.documentElement.scrollLeft; };
                   1661:         Geometry.getVerticalScroll =
                   1662:             function() { return document.documentElement.scrollTop; };
                   1663:     }
                   1664:     else if (document.body.clientHeight) {
                   1665:         Geometry.getViewportHeight =
                   1666:             function() { return document.body.clientHeight; };
                   1667:         Geometry.getViewportWidth =
                   1668:             function() { return document.body.clientWidth; };
                   1669:         Geometry.getHorizontalScroll =
                   1670:             function() { return document.body.scrollLeft; };
                   1671:         Geometry.getVerticalScroll =
                   1672:             function() { return document.body.scrollTop; };
                   1673:     }
                   1674: }
                   1675: 
                   1676: GEOMETRY
                   1677: }
                   1678: 
                   1679: =pod
                   1680: 
1.648     raeburn  1681: =item * &viewport_size_js()
1.590     raeburn  1682: 
                   1683: 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. 
                   1684: 
                   1685: =cut
                   1686: 
                   1687: sub viewport_size_js {
                   1688:     my $geometry = &viewport_geometry_js();
                   1689:     return <<"DIMS";
                   1690: 
                   1691: $geometry
                   1692: 
                   1693: function getViewportDims(width,height) {
                   1694:     init_geometry();
                   1695:     width.value = Geometry.getViewportWidth();
                   1696:     height.value = Geometry.getViewportHeight();
                   1697:     return;
                   1698: }
                   1699: 
                   1700: DIMS
                   1701: }
                   1702: 
                   1703: =pod
                   1704: 
1.648     raeburn  1705: =item * &resize_textarea_js()
1.565     albertel 1706: 
                   1707: emits the needed javascript to resize a textarea to be as big as possible
                   1708: 
                   1709: creates a function resize_textrea that takes two IDs first should be
                   1710: the id of the element to resize, second should be the id of a div that
                   1711: surrounds everything that comes after the textarea, this routine needs
                   1712: to be attached to the <body> for the onload and onresize events.
                   1713: 
1.648     raeburn  1714: =back
1.565     albertel 1715: 
                   1716: =cut
                   1717: 
                   1718: sub resize_textarea_js {
1.590     raeburn  1719:     my $geometry = &viewport_geometry_js();
1.565     albertel 1720:     return <<"RESIZE";
                   1721:     <script type="text/javascript">
1.824     bisitz   1722: // <![CDATA[
1.590     raeburn  1723: $geometry
1.565     albertel 1724: 
1.588     albertel 1725: function getX(element) {
                   1726:     var x = 0;
                   1727:     while (element) {
                   1728: 	x += element.offsetLeft;
                   1729: 	element = element.offsetParent;
                   1730:     }
                   1731:     return x;
                   1732: }
                   1733: function getY(element) {
                   1734:     var y = 0;
                   1735:     while (element) {
                   1736: 	y += element.offsetTop;
                   1737: 	element = element.offsetParent;
                   1738:     }
                   1739:     return y;
                   1740: }
                   1741: 
                   1742: 
1.565     albertel 1743: function resize_textarea(textarea_id,bottom_id) {
                   1744:     init_geometry();
                   1745:     var textarea        = document.getElementById(textarea_id);
                   1746:     //alert(textarea);
                   1747: 
1.588     albertel 1748:     var textarea_top    = getY(textarea);
1.565     albertel 1749:     var textarea_height = textarea.offsetHeight;
                   1750:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1751:     var bottom_top      = getY(bottom);
1.565     albertel 1752:     var bottom_height   = bottom.offsetHeight;
                   1753:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1754:     var fudge           = 23;
1.565     albertel 1755:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1756:     if (new_height < 300) {
                   1757: 	new_height = 300;
                   1758:     }
                   1759:     textarea.style.height=new_height+'px';
                   1760: }
1.824     bisitz   1761: // ]]>
1.565     albertel 1762: </script>
                   1763: RESIZE
                   1764: 
                   1765: }
                   1766: 
1.1205    golterma 1767: sub colorfuleditor_js {
                   1768:     return <<"COLORFULEDIT"
                   1769: <script type="text/javascript">
                   1770: // <![CDATA[>
                   1771:     function fold_box(curDepth, lastresource){
                   1772: 
                   1773:     // we need a list because there can be several blocks you need to fold in one tag
                   1774:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1775:     // but there is only one folding button per tag
                   1776:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1777: 
                   1778:         if(block.item(0).style.display == 'none'){
                   1779: 
                   1780:             foldbutton.value = '@{[&mt("Hide")]}';
                   1781:             for (i = 0; i < block.length; i++){
                   1782:                 block.item(i).style.display = '';
                   1783:             }
                   1784:         }else{
                   1785: 
                   1786:             foldbutton.value = '@{[&mt("Show")]}';
                   1787:             for (i = 0; i < block.length; i++){
                   1788:                 // block.item(i).style.visibility = 'collapse';
                   1789:                 block.item(i).style.display = 'none';
                   1790:             }
                   1791:         };
                   1792:         saveState(lastresource);
                   1793:     }
                   1794: 
                   1795:     function saveState (lastresource) {
                   1796: 
                   1797:         var tag_list = getTagList();
                   1798:         if(tag_list != null){
                   1799:             var timestamp = new Date().getTime();
                   1800:             var key = lastresource;
                   1801: 
                   1802:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1803:             // starting with timestamp
                   1804:             var value = timestamp+';';
                   1805: 
                   1806:             // building the list of key-value pairs
                   1807:             for(var i = 0; i < tag_list.length; i++){
                   1808:                 value += tag_list[i]+',';
                   1809:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1810:             }
                   1811: 
                   1812:             // only iterate whole storage if nothing to override
                   1813:             if(localStorage.getItem(key) == null){        
                   1814: 
                   1815:                 // prevent storage from growing large
                   1816:                 if(localStorage.length > 50){
                   1817:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1818:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1819:                     var oldest_key;
                   1820:                     
                   1821:                     for(var i = 1; i < localStorage.length; i++){
                   1822:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1823:                             oldest_key = localStorage.key(i);
                   1824:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1825:                         }
                   1826:                     }
                   1827:                     localStorage.removeItem(oldest_key);
                   1828:                 }
                   1829:             }
                   1830:             localStorage.setItem(key,value);
                   1831:         }
                   1832:     }
                   1833: 
                   1834:     // restore folding status of blocks (on page load)
                   1835:     function restoreState (lastresource) {
                   1836:         if(localStorage.getItem(lastresource) != null){
                   1837:             var key = lastresource;
                   1838:             var value = localStorage.getItem(key);
                   1839:             var regex_delTimestamp = /^\d+;/;
                   1840: 
                   1841:             value.replace(regex_delTimestamp, '');
                   1842: 
                   1843:             var valueArr = value.split(';');
                   1844:             var pairs;
                   1845:             var elements;
                   1846:             for (var i = 0; i < valueArr.length; i++){
                   1847:                 pairs = valueArr[i].split(',');
                   1848:                 elements = document.getElementsByName(pairs[0]);
                   1849: 
                   1850:                 for (var j = 0; j < elements.length; j++){  
                   1851:                     elements[j].style.display = pairs[1];
                   1852:                     if (pairs[1] == "none"){
                   1853:                         var regex_id = /([_\\d]+)\$/;
                   1854:                         regex_id.exec(pairs[0]);
                   1855:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1856:                     }
                   1857:                 }
                   1858:             }
                   1859:         }
                   1860:     }
                   1861: 
                   1862:     function getTagList () {
                   1863:         
                   1864:         var stringToSearch = document.lonhomework.innerHTML;
                   1865: 
                   1866:         var ret = new Array();
                   1867:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1868:         var tag_list = stringToSearch.match(regex_findBlock);
                   1869: 
                   1870:         if(tag_list != null){
                   1871:             for(var i = 0; i < tag_list.length; i++){            
                   1872:                 ret.push(tag_list[i].replace(/"/, ''));
                   1873:             }
                   1874:         }
                   1875:         return ret;
                   1876:     }
                   1877: 
                   1878:     function saveScrollPosition (resource) {
                   1879:         var tag_list = getTagList();
                   1880: 
                   1881:         // we dont always want to jump to the first block
                   1882:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1883:         if(\$(window).scrollTop() > 170){
                   1884:             if(tag_list != null){
                   1885:                 var result;
                   1886:                 for(var i = 0; i < tag_list.length; i++){
                   1887:                     if(isElementInViewport(tag_list[i])){
                   1888:                         result += tag_list[i]+';';
                   1889:                     }
                   1890:                 }
                   1891:                 sessionStorage.setItem('anchor_'+resource, result);
                   1892:             }
                   1893:         } else {
                   1894:             // we dont need to save zero, just delete the item to leave everything tidy
                   1895:             sessionStorage.removeItem('anchor_'+resource);
                   1896:         }
                   1897:     }
                   1898: 
                   1899:     function restoreScrollPosition(resource){
                   1900: 
                   1901:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1902:         if(elem != null){
                   1903:             var tag_list = elem.split(';');
                   1904:             var elem_list;
                   1905: 
                   1906:             for(var i = 0; i < tag_list.length; i++){
                   1907:                 elem_list = document.getElementsByName(tag_list[i]);
                   1908:                 
                   1909:                 if(elem_list.length > 0){
                   1910:                     elem = elem_list[0];
                   1911:                     break;
                   1912:                 }
                   1913:             }
                   1914:             elem.scrollIntoView();
                   1915:         }
                   1916:     }
                   1917: 
                   1918:     function isElementInViewport(el) {
                   1919: 
                   1920:         // change to last element instead of first
                   1921:         var elem = document.getElementsByName(el);
                   1922:         var rect = elem[0].getBoundingClientRect();
                   1923: 
                   1924:         return (
                   1925:             rect.top >= 0 &&
                   1926:             rect.left >= 0 &&
                   1927:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1928:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1929:         );
                   1930:     }
                   1931:     
                   1932:     function autosize(depth){
                   1933:         var cmInst = window['cm'+depth];
                   1934:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1935: 
                   1936:         // is fixed size, switching to dynamic
                   1937:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1938:             cmInst.setSize("","auto");
                   1939:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1940:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1941: 
                   1942:         // is dynamic size, switching to fixed
                   1943:         } else {
                   1944:             cmInst.setSize("","300px");
                   1945:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1946:             sessionStorage.removeItem("autosized_"+depth);
                   1947:         }
                   1948:     }
                   1949: 
                   1950: 
                   1951: 
                   1952: // ]]>
                   1953: </script>
                   1954: COLORFULEDIT
                   1955: }
                   1956: 
                   1957: sub xmleditor_js {
                   1958:     return <<XMLEDIT
                   1959: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1960: <script type="text/javascript">
                   1961: // <![CDATA[>
                   1962: 
                   1963:     function saveScrollPosition (resource) {
                   1964: 
                   1965:         var scrollPos = \$(window).scrollTop();
                   1966:         sessionStorage.setItem(resource,scrollPos);
                   1967:     }
                   1968: 
                   1969:     function restoreScrollPosition(resource){
                   1970: 
                   1971:         var scrollPos = sessionStorage.getItem(resource);
                   1972:         \$(window).scrollTop(scrollPos);
                   1973:     }
                   1974: 
                   1975:     // unless internet explorer
                   1976:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1977: 
                   1978:         \$(document).ready(function() {
                   1979:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1980:         });
                   1981:     }
                   1982: 
                   1983:     // inserts text at cursor position into codemirror (xml editor only)
                   1984:     function insertText(text){
                   1985:         cm.focus();
                   1986:         var curPos = cm.getCursor();
                   1987:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1988:     }
                   1989: // ]]>
                   1990: </script>
                   1991: XMLEDIT
                   1992: }
                   1993: 
                   1994: sub insert_folding_button {
                   1995:     my $curDepth = $Apache::lonxml::curdepth;
                   1996:     my $lastresource = $env{'request.ambiguous'};
                   1997: 
                   1998:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   1999:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2000: }
                   2001: 
1.565     albertel 2002: =pod
                   2003: 
1.256     matthew  2004: =head1 Excel and CSV file utility routines
                   2005: 
                   2006: =cut
                   2007: 
                   2008: ###############################################################
                   2009: ###############################################################
                   2010: 
                   2011: =pod
                   2012: 
1.1162    raeburn  2013: =over 4
                   2014: 
1.648     raeburn  2015: =item * &csv_translate($text) 
1.37      matthew  2016: 
1.185     www      2017: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2018: format.
                   2019: 
                   2020: =cut
                   2021: 
1.180     matthew  2022: ###############################################################
                   2023: ###############################################################
1.37      matthew  2024: sub csv_translate {
                   2025:     my $text = shift;
                   2026:     $text =~ s/\"/\"\"/g;
1.209     albertel 2027:     $text =~ s/\n/ /g;
1.37      matthew  2028:     return $text;
                   2029: }
1.180     matthew  2030: 
                   2031: ###############################################################
                   2032: ###############################################################
                   2033: 
                   2034: =pod
                   2035: 
1.648     raeburn  2036: =item * &define_excel_formats()
1.180     matthew  2037: 
                   2038: Define some commonly used Excel cell formats.
                   2039: 
                   2040: Currently supported formats:
                   2041: 
                   2042: =over 4
                   2043: 
                   2044: =item header
                   2045: 
                   2046: =item bold
                   2047: 
                   2048: =item h1
                   2049: 
                   2050: =item h2
                   2051: 
                   2052: =item h3
                   2053: 
1.256     matthew  2054: =item h4
                   2055: 
                   2056: =item i
                   2057: 
1.180     matthew  2058: =item date
                   2059: 
                   2060: =back
                   2061: 
                   2062: Inputs: $workbook
                   2063: 
                   2064: Returns: $format, a hash reference.
                   2065: 
1.1057    foxr     2066: 
1.180     matthew  2067: =cut
                   2068: 
                   2069: ###############################################################
                   2070: ###############################################################
                   2071: sub define_excel_formats {
                   2072:     my ($workbook) = @_;
                   2073:     my $format;
                   2074:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2075:                                                 bottom    => 1,
                   2076:                                                 align     => 'center');
                   2077:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2078:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2079:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2080:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2081:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2082:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2083:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2084:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2085:     return $format;
                   2086: }
                   2087: 
                   2088: ###############################################################
                   2089: ###############################################################
1.113     bowersj2 2090: 
                   2091: =pod
                   2092: 
1.648     raeburn  2093: =item * &create_workbook()
1.255     matthew  2094: 
                   2095: Create an Excel worksheet.  If it fails, output message on the
                   2096: request object and return undefs.
                   2097: 
                   2098: Inputs: Apache request object
                   2099: 
                   2100: Returns (undef) on failure, 
                   2101:     Excel worksheet object, scalar with filename, and formats 
                   2102:     from &Apache::loncommon::define_excel_formats on success
                   2103: 
                   2104: =cut
                   2105: 
                   2106: ###############################################################
                   2107: ###############################################################
                   2108: sub create_workbook {
                   2109:     my ($r) = @_;
                   2110:         #
                   2111:     # Create the excel spreadsheet
                   2112:     my $filename = '/prtspool/'.
1.258     albertel 2113:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2114:         time.'_'.rand(1000000000).'.xls';
                   2115:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2116:     if (! defined($workbook)) {
                   2117:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2118:         $r->print(
                   2119:             '<p class="LC_error">'
                   2120:            .&mt('Problems occurred in creating the new Excel file.')
                   2121:            .' '.&mt('This error has been logged.')
                   2122:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2123:            .'</p>'
                   2124:         );
1.255     matthew  2125:         return (undef);
                   2126:     }
                   2127:     #
1.1014    foxr     2128:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2129:     #
                   2130:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2131:     return ($workbook,$filename,$format);
                   2132: }
                   2133: 
                   2134: ###############################################################
                   2135: ###############################################################
                   2136: 
                   2137: =pod
                   2138: 
1.648     raeburn  2139: =item * &create_text_file()
1.113     bowersj2 2140: 
1.542     raeburn  2141: Create a file to write to and eventually make available to the user.
1.256     matthew  2142: If file creation fails, outputs an error message on the request object and 
                   2143: return undefs.
1.113     bowersj2 2144: 
1.256     matthew  2145: Inputs: Apache request object, and file suffix
1.113     bowersj2 2146: 
1.256     matthew  2147: Returns (undef) on failure, 
                   2148:     Filehandle and filename on success.
1.113     bowersj2 2149: 
                   2150: =cut
                   2151: 
1.256     matthew  2152: ###############################################################
                   2153: ###############################################################
                   2154: sub create_text_file {
                   2155:     my ($r,$suffix) = @_;
                   2156:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2157:     my $fh;
                   2158:     my $filename = '/prtspool/'.
1.258     albertel 2159:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2160:         time.'_'.rand(1000000000).'.'.$suffix;
                   2161:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2162:     if (! defined($fh)) {
                   2163:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2164:         $r->print(
                   2165:             '<p class="LC_error">'
                   2166:            .&mt('Problems occurred in creating the output file.')
                   2167:            .' '.&mt('This error has been logged.')
                   2168:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2169:            .'</p>'
                   2170:         );
1.113     bowersj2 2171:     }
1.256     matthew  2172:     return ($fh,$filename)
1.113     bowersj2 2173: }
                   2174: 
                   2175: 
1.256     matthew  2176: =pod 
1.113     bowersj2 2177: 
                   2178: =back
                   2179: 
                   2180: =cut
1.37      matthew  2181: 
                   2182: ###############################################################
1.33      matthew  2183: ##        Home server <option> list generating code          ##
                   2184: ###############################################################
1.35      matthew  2185: 
1.169     www      2186: # ------------------------------------------
                   2187: 
                   2188: sub domain_select {
                   2189:     my ($name,$value,$multiple)=@_;
                   2190:     my %domains=map { 
1.514     albertel 2191: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2192:     } &Apache::lonnet::all_domains();
1.169     www      2193:     if ($multiple) {
                   2194: 	$domains{''}=&mt('Any domain');
1.550     albertel 2195: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2196: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2197:     } else {
1.550     albertel 2198: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2199: 	return &select_form($name,$value,\%domains);
1.169     www      2200:     }
                   2201: }
                   2202: 
1.282     albertel 2203: #-------------------------------------------
                   2204: 
                   2205: =pod
                   2206: 
1.519     raeburn  2207: =head1 Routines for form select boxes
                   2208: 
                   2209: =over 4
                   2210: 
1.648     raeburn  2211: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2212: 
                   2213: Returns a string containing a <select> element int multiple mode
                   2214: 
                   2215: 
                   2216: Args:
                   2217:   $name - name of the <select> element
1.506     raeburn  2218:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2219:   $size - number of rows long the select element is
1.283     albertel 2220:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2221:           (shown text should already have been &mt())
1.506     raeburn  2222:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2223: 
1.282     albertel 2224: =cut
                   2225: 
                   2226: #-------------------------------------------
1.169     www      2227: sub multiple_select_form {
1.284     albertel 2228:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2229:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2230:     my $output='';
1.191     matthew  2231:     if (! defined($size)) {
                   2232:         $size = 4;
1.283     albertel 2233:         if (scalar(keys(%$hash))<4) {
                   2234:             $size = scalar(keys(%$hash));
1.191     matthew  2235:         }
                   2236:     }
1.734     bisitz   2237:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2238:     my @order;
1.506     raeburn  2239:     if (ref($order) eq 'ARRAY')  {
                   2240:         @order = @{$order};
                   2241:     } else {
                   2242:         @order = sort(keys(%$hash));
1.501     banghart 2243:     }
                   2244:     if (exists($$hash{'select_form_order'})) {
                   2245:         @order = @{$$hash{'select_form_order'}};
                   2246:     }
                   2247:         
1.284     albertel 2248:     foreach my $key (@order) {
1.356     albertel 2249:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2250:         $output.='selected="selected" ' if ($selected{$key});
                   2251:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2252:     }
                   2253:     $output.="</select>\n";
                   2254:     return $output;
                   2255: }
                   2256: 
1.88      www      2257: #-------------------------------------------
                   2258: 
                   2259: =pod
                   2260: 
1.970     raeburn  2261: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      2262: 
                   2263: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2264: allow a user to select options from a ref to a hash containing:
                   2265: option_name => displayed text. An optional $onchange can include
                   2266: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   2267: 
1.88      www      2268: See lonrights.pm for an example invocation and use.
                   2269: 
                   2270: =cut
                   2271: 
                   2272: #-------------------------------------------
                   2273: sub select_form {
1.1228    raeburn  2274:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2275:     return unless (ref($hashref) eq 'HASH');
                   2276:     if ($onchange) {
                   2277:         $onchange = ' onchange="'.$onchange.'"';
                   2278:     }
1.1228    raeburn  2279:     my $disabled;
                   2280:     if ($readonly) {
                   2281:         $disabled = ' disabled="disabled"';
                   2282:     }
                   2283:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2284:     my @keys;
1.970     raeburn  2285:     if (exists($hashref->{'select_form_order'})) {
                   2286: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2287:     } else {
1.970     raeburn  2288: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2289:     }
1.356     albertel 2290:     foreach my $key (@keys) {
                   2291:         $selectform.=
                   2292: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2293:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2294:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2295:     }
                   2296:     $selectform.="</select>";
                   2297:     return $selectform;
                   2298: }
                   2299: 
1.475     www      2300: # For display filters
                   2301: 
                   2302: sub display_filter {
1.1074    raeburn  2303:     my ($context) = @_;
1.475     www      2304:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2305:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2306:     my $phraseinput = 'hidden';
                   2307:     my $includeinput = 'hidden';
                   2308:     my ($checked,$includetypestext);
                   2309:     if ($env{'form.displayfilter'} eq 'containing') {
                   2310:         $phraseinput = 'text'; 
                   2311:         if ($context eq 'parmslog') {
                   2312:             $includeinput = 'checkbox';
                   2313:             if ($env{'form.includetypes'}) {
                   2314:                 $checked = ' checked="checked"';
                   2315:             }
                   2316:             $includetypestext = &mt('Include parameter types');
                   2317:         }
                   2318:     } else {
                   2319:         $includetypestext = '&nbsp;';
                   2320:     }
                   2321:     my ($additional,$secondid,$thirdid);
                   2322:     if ($context eq 'parmslog') {
                   2323:         $additional = 
                   2324:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2325:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2326:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2327:             '</label>';
                   2328:         $secondid = 'includetypes';
                   2329:         $thirdid = 'includetypestext';
                   2330:     }
                   2331:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2332:                                                     '$secondid','$thirdid')";
                   2333:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2334: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2335: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2336: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2337:            &mt('Filter: [_1]',
1.477     www      2338: 	   &select_form($env{'form.displayfilter'},
                   2339: 			'displayfilter',
1.970     raeburn  2340: 			{'currentfolder' => 'Current folder/page',
1.477     www      2341: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2342: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2343: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2344:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2345:                          '" />'.$additional;
                   2346: }
                   2347: 
                   2348: sub display_filter_js {
                   2349:     my $includetext = &mt('Include parameter types');
                   2350:     return <<"ENDJS";
                   2351:   
                   2352: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2353:     var firstType = 'hidden';
                   2354:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2355:         firstType = 'text';
                   2356:     }
                   2357:     firstObject = document.getElementById(firstid);
                   2358:     if (typeof(firstObject) == 'object') {
                   2359:         if (firstObject.type != firstType) {
                   2360:             changeInputType(firstObject,firstType);
                   2361:         }
                   2362:     }
                   2363:     if (context == 'parmslog') {
                   2364:         var secondType = 'hidden';
                   2365:         if (firstType == 'text') {
                   2366:             secondType = 'checkbox';
                   2367:         }
                   2368:         secondObject = document.getElementById(secondid);  
                   2369:         if (typeof(secondObject) == 'object') {
                   2370:             if (secondObject.type != secondType) {
                   2371:                 changeInputType(secondObject,secondType);
                   2372:             }
                   2373:         }
                   2374:         var textItem = document.getElementById(thirdid);
                   2375:         var currtext = textItem.innerHTML;
                   2376:         var newtext;
                   2377:         if (firstType == 'text') {
                   2378:             newtext = '$includetext';
                   2379:         } else {
                   2380:             newtext = '&nbsp;';
                   2381:         }
                   2382:         if (currtext != newtext) {
                   2383:             textItem.innerHTML = newtext;
                   2384:         }
                   2385:     }
                   2386:     return;
                   2387: }
                   2388: 
                   2389: function changeInputType(oldObject,newType) {
                   2390:     var newObject = document.createElement('input');
                   2391:     newObject.type = newType;
                   2392:     if (oldObject.size) {
                   2393:         newObject.size = oldObject.size;
                   2394:     }
                   2395:     if (oldObject.value) {
                   2396:         newObject.value = oldObject.value;
                   2397:     }
                   2398:     if (oldObject.name) {
                   2399:         newObject.name = oldObject.name;
                   2400:     }
                   2401:     if (oldObject.id) {
                   2402:         newObject.id = oldObject.id;
                   2403:     }
                   2404:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2405:     return;
                   2406: }
                   2407: 
                   2408: ENDJS
1.475     www      2409: }
                   2410: 
1.167     www      2411: sub gradeleveldescription {
                   2412:     my $gradelevel=shift;
                   2413:     my %gradelevels=(0 => 'Not specified',
                   2414: 		     1 => 'Grade 1',
                   2415: 		     2 => 'Grade 2',
                   2416: 		     3 => 'Grade 3',
                   2417: 		     4 => 'Grade 4',
                   2418: 		     5 => 'Grade 5',
                   2419: 		     6 => 'Grade 6',
                   2420: 		     7 => 'Grade 7',
                   2421: 		     8 => 'Grade 8',
                   2422: 		     9 => 'Grade 9',
                   2423: 		     10 => 'Grade 10',
                   2424: 		     11 => 'Grade 11',
                   2425: 		     12 => 'Grade 12',
                   2426: 		     13 => 'Grade 13',
                   2427: 		     14 => '100 Level',
                   2428: 		     15 => '200 Level',
                   2429: 		     16 => '300 Level',
                   2430: 		     17 => '400 Level',
                   2431: 		     18 => 'Graduate Level');
                   2432:     return &mt($gradelevels{$gradelevel});
                   2433: }
                   2434: 
1.163     www      2435: sub select_level_form {
                   2436:     my ($deflevel,$name)=@_;
                   2437:     unless ($deflevel) { $deflevel=0; }
1.167     www      2438:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2439:     for (my $i=0; $i<=18; $i++) {
                   2440:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2441:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2442:                 ">".&gradeleveldescription($i)."</option>\n";
                   2443:     }
                   2444:     $selectform.="</select>";
                   2445:     return $selectform;
1.163     www      2446: }
1.167     www      2447: 
1.35      matthew  2448: #-------------------------------------------
                   2449: 
1.45      matthew  2450: =pod
                   2451: 
1.1121    raeburn  2452: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2453: 
                   2454: Returns a string containing a <select name='$name' size='1'> form to 
                   2455: allow a user to select the domain to preform an operation in.  
                   2456: See loncreateuser.pm for an example invocation and use.
                   2457: 
1.90      www      2458: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2459: selected");
                   2460: 
1.743     raeburn  2461: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2462: 
1.910     raeburn  2463: 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.
                   2464: 
1.1121    raeburn  2465: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2466: 
                   2467: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2468: 
1.35      matthew  2469: =cut
                   2470: 
                   2471: #-------------------------------------------
1.34      matthew  2472: sub select_dom_form {
1.1121    raeburn  2473:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2474:     if ($onchange) {
1.874     raeburn  2475:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2476:     }
1.1121    raeburn  2477:     my (@domains,%exclude);
1.910     raeburn  2478:     if (ref($incdoms) eq 'ARRAY') {
                   2479:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2480:     } else {
                   2481:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2482:     }
1.90      www      2483:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2484:     if (ref($excdoms) eq 'ARRAY') {
                   2485:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2486:     }
1.743     raeburn  2487:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2488:     foreach my $dom (@domains) {
1.1121    raeburn  2489:         next if ($exclude{$dom});
1.356     albertel 2490:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2491:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2492:         if ($showdomdesc) {
                   2493:             if ($dom ne '') {
                   2494:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2495:                 if ($domdesc ne '') {
                   2496:                     $selectdomain .= ' ('.$domdesc.')';
                   2497:                 }
                   2498:             } 
                   2499:         }
                   2500:         $selectdomain .= "</option>\n";
1.34      matthew  2501:     }
                   2502:     $selectdomain.="</select>";
                   2503:     return $selectdomain;
                   2504: }
                   2505: 
1.35      matthew  2506: #-------------------------------------------
                   2507: 
1.45      matthew  2508: =pod
                   2509: 
1.648     raeburn  2510: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2511: 
1.586     raeburn  2512: input: 4 arguments (two required, two optional) - 
                   2513:     $domain - domain of new user
                   2514:     $name - name of form element
                   2515:     $default - Value of 'default' causes a default item to be first 
                   2516:                             option, and selected by default. 
                   2517:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2518:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2519: output: returns 2 items: 
1.586     raeburn  2520: (a) form element which contains either:
                   2521:    (i) <select name="$name">
                   2522:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2523:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2524:        </select>
                   2525:        form item if there are multiple library servers in $domain, or
                   2526:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2527:        if there is only one library server in $domain.
                   2528: 
                   2529: (b) number of library servers found.
                   2530: 
                   2531: See loncreateuser.pm for example of use.
1.35      matthew  2532: 
                   2533: =cut
                   2534: 
                   2535: #-------------------------------------------
1.586     raeburn  2536: sub home_server_form_item {
                   2537:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2538:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2539:     my $result;
                   2540:     my $numlib = keys(%servers);
                   2541:     if ($numlib > 1) {
                   2542:         $result .= '<select name="'.$name.'" />'."\n";
                   2543:         if ($default) {
1.804     bisitz   2544:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2545:                        '</option>'."\n";
                   2546:         }
                   2547:         foreach my $hostid (sort(keys(%servers))) {
                   2548:             $result.= '<option value="'.$hostid.'">'.
                   2549: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2550:         }
                   2551:         $result .= '</select>'."\n";
                   2552:     } elsif ($numlib == 1) {
                   2553:         my $hostid;
                   2554:         foreach my $item (keys(%servers)) {
                   2555:             $hostid = $item;
                   2556:         }
                   2557:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2558:                    $hostid.'" />';
                   2559:                    if (!$hide) {
                   2560:                        $result .= $hostid.' '.$servers{$hostid};
                   2561:                    }
                   2562:                    $result .= "\n";
                   2563:     } elsif ($default) {
                   2564:         $result .= '<input type="hidden" name="'.$name.
                   2565:                    '" value="default" />';
                   2566:                    if (!$hide) {
                   2567:                        $result .= &mt('default');
                   2568:                    }
                   2569:                    $result .= "\n";
1.33      matthew  2570:     }
1.586     raeburn  2571:     return ($result,$numlib);
1.33      matthew  2572: }
1.112     bowersj2 2573: 
                   2574: =pod
                   2575: 
1.534     albertel 2576: =back 
                   2577: 
1.112     bowersj2 2578: =cut
1.87      matthew  2579: 
                   2580: ###############################################################
1.112     bowersj2 2581: ##                  Decoding User Agent                      ##
1.87      matthew  2582: ###############################################################
                   2583: 
                   2584: =pod
                   2585: 
1.112     bowersj2 2586: =head1 Decoding the User Agent
                   2587: 
                   2588: =over 4
                   2589: 
                   2590: =item * &decode_user_agent()
1.87      matthew  2591: 
                   2592: Inputs: $r
                   2593: 
                   2594: Outputs:
                   2595: 
                   2596: =over 4
                   2597: 
1.112     bowersj2 2598: =item * $httpbrowser
1.87      matthew  2599: 
1.112     bowersj2 2600: =item * $clientbrowser
1.87      matthew  2601: 
1.112     bowersj2 2602: =item * $clientversion
1.87      matthew  2603: 
1.112     bowersj2 2604: =item * $clientmathml
1.87      matthew  2605: 
1.112     bowersj2 2606: =item * $clientunicode
1.87      matthew  2607: 
1.112     bowersj2 2608: =item * $clientos
1.87      matthew  2609: 
1.1137    raeburn  2610: =item * $clientmobile
                   2611: 
1.1141    raeburn  2612: =item * $clientinfo
                   2613: 
1.1194    raeburn  2614: =item * $clientosversion
                   2615: 
1.87      matthew  2616: =back
                   2617: 
1.157     matthew  2618: =back 
                   2619: 
1.87      matthew  2620: =cut
                   2621: 
                   2622: ###############################################################
                   2623: ###############################################################
                   2624: sub decode_user_agent {
1.247     albertel 2625:     my ($r)=@_;
1.87      matthew  2626:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2627:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2628:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2629:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2630:     my $clientbrowser='unknown';
                   2631:     my $clientversion='0';
                   2632:     my $clientmathml='';
                   2633:     my $clientunicode='0';
1.1137    raeburn  2634:     my $clientmobile=0;
1.1194    raeburn  2635:     my $clientosversion='';
1.87      matthew  2636:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2637:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2638: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2639: 	    $clientbrowser=$bname;
                   2640:             $httpbrowser=~/$vreg/i;
                   2641: 	    $clientversion=$1;
                   2642:             $clientmathml=($clientversion>=$minv);
                   2643:             $clientunicode=($clientversion>=$univ);
                   2644: 	}
                   2645:     }
                   2646:     my $clientos='unknown';
1.1141    raeburn  2647:     my $clientinfo;
1.87      matthew  2648:     if (($httpbrowser=~/linux/i) ||
                   2649:         ($httpbrowser=~/unix/i) ||
                   2650:         ($httpbrowser=~/ux/i) ||
                   2651:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2652:     if (($httpbrowser=~/vax/i) ||
                   2653:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2654:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2655:     if (($httpbrowser=~/mac/i) ||
                   2656:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2657:     if ($httpbrowser=~/win/i) {
                   2658:         $clientos='win';
                   2659:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2660:             $clientosversion = $1;
                   2661:         }
                   2662:     }
1.87      matthew  2663:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2664:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2665:         $clientmobile=lc($1);
                   2666:     }
1.1141    raeburn  2667:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2668:         $clientinfo = 'firefox-'.$1;
                   2669:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2670:         $clientinfo = 'chromeframe-'.$1;
                   2671:     }
1.87      matthew  2672:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  2673:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2674:             $clientosversion);
1.87      matthew  2675: }
                   2676: 
1.32      matthew  2677: ###############################################################
                   2678: ##    Authentication changing form generation subroutines    ##
                   2679: ###############################################################
                   2680: ##
                   2681: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2682: ## hash, and have reasonable default values.
                   2683: ##
                   2684: ##    formname = the name given in the <form> tag.
1.35      matthew  2685: #-------------------------------------------
                   2686: 
1.45      matthew  2687: =pod
                   2688: 
1.112     bowersj2 2689: =head1 Authentication Routines
                   2690: 
                   2691: =over 4
                   2692: 
1.648     raeburn  2693: =item * &authform_xxxxxx()
1.35      matthew  2694: 
                   2695: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2696: handle some of the conveniences required for authentication forms.  
                   2697: This is not an optimal method, but it works.  
                   2698: 
                   2699: =over 4
                   2700: 
1.112     bowersj2 2701: =item * authform_header
1.35      matthew  2702: 
1.112     bowersj2 2703: =item * authform_authorwarning
1.35      matthew  2704: 
1.112     bowersj2 2705: =item * authform_nochange
1.35      matthew  2706: 
1.112     bowersj2 2707: =item * authform_kerberos
1.35      matthew  2708: 
1.112     bowersj2 2709: =item * authform_internal
1.35      matthew  2710: 
1.112     bowersj2 2711: =item * authform_filesystem
1.35      matthew  2712: 
                   2713: =back
                   2714: 
1.648     raeburn  2715: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2716: 
1.35      matthew  2717: =cut
                   2718: 
                   2719: #-------------------------------------------
1.32      matthew  2720: sub authform_header{  
                   2721:     my %in = (
                   2722:         formname => 'cu',
1.80      albertel 2723:         kerb_def_dom => '',
1.32      matthew  2724:         @_,
                   2725:     );
                   2726:     $in{'formname'} = 'document.' . $in{'formname'};
                   2727:     my $result='';
1.80      albertel 2728: 
                   2729: #---------------------------------------------- Code for upper case translation
                   2730:     my $Javascript_toUpperCase;
                   2731:     unless ($in{kerb_def_dom}) {
                   2732:         $Javascript_toUpperCase =<<"END";
                   2733:         switch (choice) {
                   2734:            case 'krb': currentform.elements[choicearg].value =
                   2735:                currentform.elements[choicearg].value.toUpperCase();
                   2736:                break;
                   2737:            default:
                   2738:         }
                   2739: END
                   2740:     } else {
                   2741:         $Javascript_toUpperCase = "";
                   2742:     }
                   2743: 
1.165     raeburn  2744:     my $radioval = "'nochange'";
1.591     raeburn  2745:     if (defined($in{'curr_authtype'})) {
                   2746:         if ($in{'curr_authtype'} ne '') {
                   2747:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2748:         }
1.174     matthew  2749:     }
1.165     raeburn  2750:     my $argfield = 'null';
1.591     raeburn  2751:     if (defined($in{'mode'})) {
1.165     raeburn  2752:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2753:             if (defined($in{'curr_autharg'})) {
                   2754:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2755:                     $argfield = "'$in{'curr_autharg'}'";
                   2756:                 }
                   2757:             }
                   2758:         }
                   2759:     }
                   2760: 
1.32      matthew  2761:     $result.=<<"END";
                   2762: var current = new Object();
1.165     raeburn  2763: current.radiovalue = $radioval;
                   2764: current.argfield = $argfield;
1.32      matthew  2765: 
                   2766: function changed_radio(choice,currentform) {
                   2767:     var choicearg = choice + 'arg';
                   2768:     // If a radio button in changed, we need to change the argfield
                   2769:     if (current.radiovalue != choice) {
                   2770:         current.radiovalue = choice;
                   2771:         if (current.argfield != null) {
                   2772:             currentform.elements[current.argfield].value = '';
                   2773:         }
                   2774:         if (choice == 'nochange') {
                   2775:             current.argfield = null;
                   2776:         } else {
                   2777:             current.argfield = choicearg;
                   2778:             switch(choice) {
                   2779:                 case 'krb': 
                   2780:                     currentform.elements[current.argfield].value = 
                   2781:                         "$in{'kerb_def_dom'}";
                   2782:                 break;
                   2783:               default:
                   2784:                 break;
                   2785:             }
                   2786:         }
                   2787:     }
                   2788:     return;
                   2789: }
1.22      www      2790: 
1.32      matthew  2791: function changed_text(choice,currentform) {
                   2792:     var choicearg = choice + 'arg';
                   2793:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2794:         $Javascript_toUpperCase
1.32      matthew  2795:         // clear old field
                   2796:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2797:             currentform.elements[current.argfield].value = '';
                   2798:         }
                   2799:         current.argfield = choicearg;
                   2800:     }
                   2801:     set_auth_radio_buttons(choice,currentform);
                   2802:     return;
1.20      www      2803: }
1.32      matthew  2804: 
                   2805: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2806:     var numauthchoices = currentform.login.length;
                   2807:     if (typeof numauthchoices  == "undefined") {
                   2808:         return;
                   2809:     } 
1.32      matthew  2810:     var i=0;
1.986     raeburn  2811:     while (i < numauthchoices) {
1.32      matthew  2812:         if (currentform.login[i].value == newvalue) { break; }
                   2813:         i++;
                   2814:     }
1.986     raeburn  2815:     if (i == numauthchoices) {
1.32      matthew  2816:         return;
                   2817:     }
                   2818:     current.radiovalue = newvalue;
                   2819:     currentform.login[i].checked = true;
                   2820:     return;
                   2821: }
                   2822: END
                   2823:     return $result;
                   2824: }
                   2825: 
1.1106    raeburn  2826: sub authform_authorwarning {
1.32      matthew  2827:     my $result='';
1.144     matthew  2828:     $result='<i>'.
                   2829:         &mt('As a general rule, only authors or co-authors should be '.
                   2830:             'filesystem authenticated '.
                   2831:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2832:     return $result;
                   2833: }
                   2834: 
1.1106    raeburn  2835: sub authform_nochange {
1.32      matthew  2836:     my %in = (
                   2837:               formname => 'document.cu',
                   2838:               kerb_def_dom => 'MSU.EDU',
                   2839:               @_,
                   2840:           );
1.1106    raeburn  2841:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  2842:     my $result;
1.1104    raeburn  2843:     if (!$authnum) {
1.1105    raeburn  2844:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2845:     } else {
                   2846:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2847:                   '<input type="radio" name="login" value="nochange" '.
                   2848:                   'checked="checked" onclick="'.
1.281     albertel 2849:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2850: 	    '</label>';
1.586     raeburn  2851:     }
1.32      matthew  2852:     return $result;
                   2853: }
                   2854: 
1.591     raeburn  2855: sub authform_kerberos {
1.32      matthew  2856:     my %in = (
                   2857:               formname => 'document.cu',
                   2858:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2859:               kerb_def_auth => 'krb4',
1.32      matthew  2860:               @_,
                   2861:               );
1.586     raeburn  2862:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2863:         $autharg,$jscall);
1.1106    raeburn  2864:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2865:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2866:        $check5 = ' checked="checked"';
1.80      albertel 2867:     } else {
1.772     bisitz   2868:        $check4 = ' checked="checked"';
1.80      albertel 2869:     }
1.165     raeburn  2870:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2871:     if (defined($in{'curr_authtype'})) {
                   2872:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2873:             $krbcheck = ' checked="checked"';
1.623     raeburn  2874:             if (defined($in{'mode'})) {
                   2875:                 if ($in{'mode'} eq 'modifyuser') {
                   2876:                     $krbcheck = '';
                   2877:                 }
                   2878:             }
1.591     raeburn  2879:             if (defined($in{'curr_kerb_ver'})) {
                   2880:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2881:                     $check5 = ' checked="checked"';
1.591     raeburn  2882:                     $check4 = '';
                   2883:                 } else {
1.772     bisitz   2884:                     $check4 = ' checked="checked"';
1.591     raeburn  2885:                     $check5 = '';
                   2886:                 }
1.586     raeburn  2887:             }
1.591     raeburn  2888:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2889:                 $krbarg = $in{'curr_autharg'};
                   2890:             }
1.586     raeburn  2891:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2892:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2893:                     $result = 
                   2894:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2895:         $in{'curr_autharg'},$krbver);
                   2896:                 } else {
                   2897:                     $result =
                   2898:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2899:                 }
                   2900:                 return $result; 
                   2901:             }
                   2902:         }
                   2903:     } else {
                   2904:         if ($authnum == 1) {
1.784     bisitz   2905:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2906:         }
                   2907:     }
1.586     raeburn  2908:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2909:         return;
1.587     raeburn  2910:     } elsif ($authtype eq '') {
1.591     raeburn  2911:         if (defined($in{'mode'})) {
1.587     raeburn  2912:             if ($in{'mode'} eq 'modifycourse') {
                   2913:                 if ($authnum == 1) {
1.1104    raeburn  2914:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2915:                 }
                   2916:             }
                   2917:         }
1.586     raeburn  2918:     }
                   2919:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2920:     if ($authtype eq '') {
                   2921:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2922:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2923:                     $krbcheck.' />';
                   2924:     }
                   2925:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  2926:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2927:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  2928:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2929:          $in{'curr_authtype'} eq 'krb4')) {
                   2930:         $result .= &mt
1.144     matthew  2931:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2932:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2933:          '<label>'.$authtype,
1.281     albertel 2934:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2935:              'value="'.$krbarg.'" '.
1.144     matthew  2936:              'onchange="'.$jscall.'" />',
1.281     albertel 2937:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2938:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2939: 	 '</label>');
1.586     raeburn  2940:     } elsif ($can_assign{'krb4'}) {
                   2941:         $result .= &mt
                   2942:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2943:          '[_3] Version 4 [_4]',
                   2944:          '<label>'.$authtype,
                   2945:          '</label><input type="text" size="10" name="krbarg" '.
                   2946:              'value="'.$krbarg.'" '.
                   2947:              'onchange="'.$jscall.'" />',
                   2948:          '<label><input type="hidden" name="krbver" value="4" />',
                   2949:          '</label>');
                   2950:     } elsif ($can_assign{'krb5'}) {
                   2951:         $result .= &mt
                   2952:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2953:          '[_3] Version 5 [_4]',
                   2954:          '<label>'.$authtype,
                   2955:          '</label><input type="text" size="10" name="krbarg" '.
                   2956:              'value="'.$krbarg.'" '.
                   2957:              'onchange="'.$jscall.'" />',
                   2958:          '<label><input type="hidden" name="krbver" value="5" />',
                   2959:          '</label>');
                   2960:     }
1.32      matthew  2961:     return $result;
                   2962: }
                   2963: 
1.1106    raeburn  2964: sub authform_internal {
1.586     raeburn  2965:     my %in = (
1.32      matthew  2966:                 formname => 'document.cu',
                   2967:                 kerb_def_dom => 'MSU.EDU',
                   2968:                 @_,
                   2969:                 );
1.586     raeburn  2970:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2971:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2972:     if (defined($in{'curr_authtype'})) {
                   2973:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2974:             if ($can_assign{'int'}) {
1.772     bisitz   2975:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2976:                 if (defined($in{'mode'})) {
                   2977:                     if ($in{'mode'} eq 'modifyuser') {
                   2978:                         $intcheck = '';
                   2979:                     }
                   2980:                 }
1.591     raeburn  2981:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2982:                     $intarg = $in{'curr_autharg'};
                   2983:                 }
                   2984:             } else {
                   2985:                 $result = &mt('Currently internally authenticated.');
                   2986:                 return $result;
1.165     raeburn  2987:             }
                   2988:         }
1.586     raeburn  2989:     } else {
                   2990:         if ($authnum == 1) {
1.784     bisitz   2991:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2992:         }
                   2993:     }
                   2994:     if (!$can_assign{'int'}) {
                   2995:         return;
1.587     raeburn  2996:     } elsif ($authtype eq '') {
1.591     raeburn  2997:         if (defined($in{'mode'})) {
1.587     raeburn  2998:             if ($in{'mode'} eq 'modifycourse') {
                   2999:                 if ($authnum == 1) {
1.1104    raeburn  3000:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  3001:                 }
                   3002:             }
                   3003:         }
1.165     raeburn  3004:     }
1.586     raeburn  3005:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3006:     if ($authtype eq '') {
                   3007:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   3008:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   3009:     }
1.605     bisitz   3010:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  3011:                $intarg.'" onchange="'.$jscall.'" />';
                   3012:     $result = &mt
1.144     matthew  3013:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3014:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   3015:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
1.32      matthew  3016:     return $result;
                   3017: }
                   3018: 
1.1104    raeburn  3019: sub authform_local {
1.32      matthew  3020:     my %in = (
                   3021:               formname => 'document.cu',
                   3022:               kerb_def_dom => 'MSU.EDU',
                   3023:               @_,
                   3024:               );
1.586     raeburn  3025:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3026:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3027:     if (defined($in{'curr_authtype'})) {
                   3028:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3029:             if ($can_assign{'loc'}) {
1.772     bisitz   3030:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3031:                 if (defined($in{'mode'})) {
                   3032:                     if ($in{'mode'} eq 'modifyuser') {
                   3033:                         $loccheck = '';
                   3034:                     }
                   3035:                 }
1.591     raeburn  3036:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3037:                     $locarg = $in{'curr_autharg'};
                   3038:                 }
                   3039:             } else {
                   3040:                 $result = &mt('Currently using local (institutional) authentication.');
                   3041:                 return $result;
1.165     raeburn  3042:             }
                   3043:         }
1.586     raeburn  3044:     } else {
                   3045:         if ($authnum == 1) {
1.784     bisitz   3046:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3047:         }
                   3048:     }
                   3049:     if (!$can_assign{'loc'}) {
                   3050:         return;
1.587     raeburn  3051:     } elsif ($authtype eq '') {
1.591     raeburn  3052:         if (defined($in{'mode'})) {
1.587     raeburn  3053:             if ($in{'mode'} eq 'modifycourse') {
                   3054:                 if ($authnum == 1) {
1.1104    raeburn  3055:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  3056:                 }
                   3057:             }
                   3058:         }
1.165     raeburn  3059:     }
1.586     raeburn  3060:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3061:     if ($authtype eq '') {
                   3062:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3063:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   3064:                     $jscall.'" />';
                   3065:     }
                   3066:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   3067:                $locarg.'" onchange="'.$jscall.'" />';
                   3068:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3069:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3070:     return $result;
                   3071: }
                   3072: 
1.1106    raeburn  3073: sub authform_filesystem {
1.32      matthew  3074:     my %in = (
                   3075:               formname => 'document.cu',
                   3076:               kerb_def_dom => 'MSU.EDU',
                   3077:               @_,
                   3078:               );
1.586     raeburn  3079:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3080:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3081:     if (defined($in{'curr_authtype'})) {
                   3082:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3083:             if ($can_assign{'fsys'}) {
1.772     bisitz   3084:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3085:                 if (defined($in{'mode'})) {
                   3086:                     if ($in{'mode'} eq 'modifyuser') {
                   3087:                         $fsyscheck = '';
                   3088:                     }
                   3089:                 }
1.586     raeburn  3090:             } else {
                   3091:                 $result = &mt('Currently Filesystem Authenticated.');
                   3092:                 return $result;
                   3093:             }           
                   3094:         }
                   3095:     } else {
                   3096:         if ($authnum == 1) {
1.784     bisitz   3097:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3098:         }
                   3099:     }
                   3100:     if (!$can_assign{'fsys'}) {
                   3101:         return;
1.587     raeburn  3102:     } elsif ($authtype eq '') {
1.591     raeburn  3103:         if (defined($in{'mode'})) {
1.587     raeburn  3104:             if ($in{'mode'} eq 'modifycourse') {
                   3105:                 if ($authnum == 1) {
1.1104    raeburn  3106:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  3107:                 }
                   3108:             }
                   3109:         }
1.586     raeburn  3110:     }
                   3111:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3112:     if ($authtype eq '') {
                   3113:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3114:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   3115:                     $jscall.'" />';
                   3116:     }
                   3117:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   3118:                ' onchange="'.$jscall.'" />';
                   3119:     $result = &mt
1.144     matthew  3120:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3121:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  3122:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   3123:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  3124:                   'onchange="'.$jscall.'" />');
1.32      matthew  3125:     return $result;
                   3126: }
                   3127: 
1.586     raeburn  3128: sub get_assignable_auth {
                   3129:     my ($dom) = @_;
                   3130:     if ($dom eq '') {
                   3131:         $dom = $env{'request.role.domain'};
                   3132:     }
                   3133:     my %can_assign = (
                   3134:                           krb4 => 1,
                   3135:                           krb5 => 1,
                   3136:                           int  => 1,
                   3137:                           loc  => 1,
                   3138:                      );
                   3139:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3140:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3141:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3142:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3143:             my $context;
                   3144:             if ($env{'request.role'} =~ /^au/) {
                   3145:                 $context = 'author';
                   3146:             } elsif ($env{'request.role'} =~ /^dc/) {
                   3147:                 $context = 'domain';
                   3148:             } elsif ($env{'request.course.id'}) {
                   3149:                 $context = 'course';
                   3150:             }
                   3151:             if ($context) {
                   3152:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3153:                    %can_assign = %{$authhash->{$context}}; 
                   3154:                 }
                   3155:             }
                   3156:         }
                   3157:     }
                   3158:     my $authnum = 0;
                   3159:     foreach my $key (keys(%can_assign)) {
                   3160:         if ($can_assign{$key}) {
                   3161:             $authnum ++;
                   3162:         }
                   3163:     }
                   3164:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3165:         $authnum --;
                   3166:     }
                   3167:     return ($authnum,%can_assign);
                   3168: }
                   3169: 
1.80      albertel 3170: ###############################################################
                   3171: ##    Get Kerberos Defaults for Domain                 ##
                   3172: ###############################################################
                   3173: ##
                   3174: ## Returns default kerberos version and an associated argument
                   3175: ## as listed in file domain.tab. If not listed, provides
                   3176: ## appropriate default domain and kerberos version.
                   3177: ##
                   3178: #-------------------------------------------
                   3179: 
                   3180: =pod
                   3181: 
1.648     raeburn  3182: =item * &get_kerberos_defaults()
1.80      albertel 3183: 
                   3184: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3185: version and domain. If not found, it defaults to version 4 and the 
                   3186: domain of the server.
1.80      albertel 3187: 
1.648     raeburn  3188: =over 4
                   3189: 
1.80      albertel 3190: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3191: 
1.648     raeburn  3192: =back
                   3193: 
                   3194: =back
                   3195: 
1.80      albertel 3196: =cut
                   3197: 
                   3198: #-------------------------------------------
                   3199: sub get_kerberos_defaults {
                   3200:     my $domain=shift;
1.641     raeburn  3201:     my ($krbdef,$krbdefdom);
                   3202:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3203:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3204:         $krbdef = $domdefaults{'auth_def'};
                   3205:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3206:     } else {
1.80      albertel 3207:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3208:         my $krbdefdom=$1;
                   3209:         $krbdefdom=~tr/a-z/A-Z/;
                   3210:         $krbdef = "krb4";
                   3211:     }
                   3212:     return ($krbdef,$krbdefdom);
                   3213: }
1.112     bowersj2 3214: 
1.32      matthew  3215: 
1.46      matthew  3216: ###############################################################
                   3217: ##                Thesaurus Functions                        ##
                   3218: ###############################################################
1.20      www      3219: 
1.46      matthew  3220: =pod
1.20      www      3221: 
1.112     bowersj2 3222: =head1 Thesaurus Functions
                   3223: 
                   3224: =over 4
                   3225: 
1.648     raeburn  3226: =item * &initialize_keywords()
1.46      matthew  3227: 
                   3228: Initializes the package variable %Keywords if it is empty.  Uses the
                   3229: package variable $thesaurus_db_file.
                   3230: 
                   3231: =cut
                   3232: 
                   3233: ###################################################
                   3234: 
                   3235: sub initialize_keywords {
                   3236:     return 1 if (scalar keys(%Keywords));
                   3237:     # If we are here, %Keywords is empty, so fill it up
                   3238:     #   Make sure the file we need exists...
                   3239:     if (! -e $thesaurus_db_file) {
                   3240:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3241:                                  " failed because it does not exist");
                   3242:         return 0;
                   3243:     }
                   3244:     #   Set up the hash as a database
                   3245:     my %thesaurus_db;
                   3246:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3247:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3248:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3249:                                  $thesaurus_db_file);
                   3250:         return 0;
                   3251:     } 
                   3252:     #  Get the average number of appearances of a word.
                   3253:     my $avecount = $thesaurus_db{'average.count'};
                   3254:     #  Put keywords (those that appear > average) into %Keywords
                   3255:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3256:         my ($count,undef) = split /:/,$data;
                   3257:         $Keywords{$word}++ if ($count > $avecount);
                   3258:     }
                   3259:     untie %thesaurus_db;
                   3260:     # Remove special values from %Keywords.
1.356     albertel 3261:     foreach my $value ('total.count','average.count') {
                   3262:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3263:   }
1.46      matthew  3264:     return 1;
                   3265: }
                   3266: 
                   3267: ###################################################
                   3268: 
                   3269: =pod
                   3270: 
1.648     raeburn  3271: =item * &keyword($word)
1.46      matthew  3272: 
                   3273: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3274: than the average number of times in the thesaurus database.  Calls 
                   3275: &initialize_keywords
                   3276: 
                   3277: =cut
                   3278: 
                   3279: ###################################################
1.20      www      3280: 
                   3281: sub keyword {
1.46      matthew  3282:     return if (!&initialize_keywords());
                   3283:     my $word=lc(shift());
                   3284:     $word=~s/\W//g;
                   3285:     return exists($Keywords{$word});
1.20      www      3286: }
1.46      matthew  3287: 
                   3288: ###############################################################
                   3289: 
                   3290: =pod 
1.20      www      3291: 
1.648     raeburn  3292: =item * &get_related_words()
1.46      matthew  3293: 
1.160     matthew  3294: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3295: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3296: will be returned.  The order of the words returned is determined by the
                   3297: database which holds them.
                   3298: 
                   3299: Uses global $thesaurus_db_file.
                   3300: 
1.1057    foxr     3301: 
1.46      matthew  3302: =cut
                   3303: 
                   3304: ###############################################################
                   3305: sub get_related_words {
                   3306:     my $keyword = shift;
                   3307:     my %thesaurus_db;
                   3308:     if (! -e $thesaurus_db_file) {
                   3309:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3310:                                  "failed because the file does not exist");
                   3311:         return ();
                   3312:     }
                   3313:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3314:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3315:         return ();
                   3316:     } 
                   3317:     my @Words=();
1.429     www      3318:     my $count=0;
1.46      matthew  3319:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3320: 	# The first element is the number of times
                   3321: 	# the word appears.  We do not need it now.
1.429     www      3322: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3323: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3324: 	my $threshold=$mostfrequentcount/10;
                   3325:         foreach my $possibleword (@RelatedWords) {
                   3326:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3327:             if ($wordcount>$threshold) {
                   3328: 		push(@Words,$word);
                   3329:                 $count++;
                   3330:                 if ($count>10) { last; }
                   3331: 	    }
1.20      www      3332:         }
                   3333:     }
1.46      matthew  3334:     untie %thesaurus_db;
                   3335:     return @Words;
1.14      harris41 3336: }
1.1090    foxr     3337: ###############################################################
                   3338: #
                   3339: #  Spell checking
                   3340: #
                   3341: 
                   3342: =pod
                   3343: 
1.1142    raeburn  3344: =back
                   3345: 
1.1090    foxr     3346: =head1 Spell checking
                   3347: 
                   3348: =over 4
                   3349: 
                   3350: =item * &check_spelling($wordlist $language)
                   3351: 
                   3352: Takes a string containing words and feeds it to an external
                   3353: spellcheck program via a pipeline. Returns a string containing
                   3354: them mis-spelled words.
                   3355: 
                   3356: Parameters:
                   3357: 
                   3358: =over 4
                   3359: 
                   3360: =item - $wordlist
                   3361: 
                   3362: String that will be fed into the spellcheck program.
                   3363: 
                   3364: =item - $language
                   3365: 
                   3366: Language string that specifies the language for which the spell
                   3367: check will be performed.
                   3368: 
                   3369: =back
                   3370: 
                   3371: =back
                   3372: 
                   3373: Note: This sub assumes that aspell is installed.
                   3374: 
                   3375: 
                   3376: =cut
                   3377: 
1.46      matthew  3378: 
1.1090    foxr     3379: sub check_spelling {
                   3380:     my ($wordlist, $language) = @_;
1.1091    foxr     3381:     my @misspellings;
                   3382:     
                   3383:     # Generate the speller and set the langauge.
                   3384:     # if explicitly selected:
1.1090    foxr     3385: 
1.1091    foxr     3386:     my $speller = Text::Aspell->new;
1.1090    foxr     3387:     if ($language) {
1.1091    foxr     3388: 	$speller->set_option('lang', $language);
1.1090    foxr     3389:     }
                   3390: 
1.1091    foxr     3391:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3392: 
1.1091    foxr     3393:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3394: 
1.1091    foxr     3395:     foreach my $word (@words) {
                   3396: 	if(! $speller->check($word)) {
                   3397: 	    push(@misspellings, $word);
1.1090    foxr     3398: 	}
                   3399:     }
1.1091    foxr     3400:     return join(' ', @misspellings);
                   3401:     
1.1090    foxr     3402: }
                   3403: 
1.61      www      3404: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3405: =pod
                   3406: 
1.112     bowersj2 3407: =head1 User Name Functions
                   3408: 
                   3409: =over 4
                   3410: 
1.648     raeburn  3411: =item * &plainname($uname,$udom,$first)
1.81      albertel 3412: 
1.112     bowersj2 3413: Takes a users logon name and returns it as a string in
1.226     albertel 3414: "first middle last generation" form 
                   3415: if $first is set to 'lastname' then it returns it as
                   3416: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3417: 
                   3418: =cut
1.61      www      3419: 
1.295     www      3420: 
1.81      albertel 3421: ###############################################################
1.61      www      3422: sub plainname {
1.226     albertel 3423:     my ($uname,$udom,$first)=@_;
1.537     albertel 3424:     return if (!defined($uname) || !defined($udom));
1.295     www      3425:     my %names=&getnames($uname,$udom);
1.226     albertel 3426:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3427: 					  $names{'middlename'},
                   3428: 					  $names{'lastname'},
                   3429: 					  $names{'generation'},$first);
                   3430:     $name=~s/^\s+//;
1.62      www      3431:     $name=~s/\s+$//;
                   3432:     $name=~s/\s+/ /g;
1.353     albertel 3433:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3434:     return $name;
1.61      www      3435: }
1.66      www      3436: 
                   3437: # -------------------------------------------------------------------- Nickname
1.81      albertel 3438: =pod
                   3439: 
1.648     raeburn  3440: =item * &nickname($uname,$udom)
1.81      albertel 3441: 
                   3442: Gets a users name and returns it as a string as
                   3443: 
                   3444: "&quot;nickname&quot;"
1.66      www      3445: 
1.81      albertel 3446: if the user has a nickname or
                   3447: 
                   3448: "first middle last generation"
                   3449: 
                   3450: if the user does not
                   3451: 
                   3452: =cut
1.66      www      3453: 
                   3454: sub nickname {
                   3455:     my ($uname,$udom)=@_;
1.537     albertel 3456:     return if (!defined($uname) || !defined($udom));
1.295     www      3457:     my %names=&getnames($uname,$udom);
1.68      albertel 3458:     my $name=$names{'nickname'};
1.66      www      3459:     if ($name) {
                   3460:        $name='&quot;'.$name.'&quot;'; 
                   3461:     } else {
                   3462:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3463: 	     $names{'lastname'}.' '.$names{'generation'};
                   3464:        $name=~s/\s+$//;
                   3465:        $name=~s/\s+/ /g;
                   3466:     }
                   3467:     return $name;
                   3468: }
                   3469: 
1.295     www      3470: sub getnames {
                   3471:     my ($uname,$udom)=@_;
1.537     albertel 3472:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3473:     if ($udom eq 'public' && $uname eq 'public') {
                   3474: 	return ('lastname' => &mt('Public'));
                   3475:     }
1.295     www      3476:     my $id=$uname.':'.$udom;
                   3477:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3478:     if ($cached) {
                   3479: 	return %{$names};
                   3480:     } else {
                   3481: 	my %loadnames=&Apache::lonnet::get('environment',
                   3482:                     ['firstname','middlename','lastname','generation','nickname'],
                   3483: 					 $udom,$uname);
                   3484: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3485: 	return %loadnames;
                   3486:     }
                   3487: }
1.61      www      3488: 
1.542     raeburn  3489: # -------------------------------------------------------------------- getemails
1.648     raeburn  3490: 
1.542     raeburn  3491: =pod
                   3492: 
1.648     raeburn  3493: =item * &getemails($uname,$udom)
1.542     raeburn  3494: 
                   3495: Gets a user's email information and returns it as a hash with keys:
                   3496: notification, critnotification, permanentemail
                   3497: 
                   3498: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3499: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3500:  
1.648     raeburn  3501: 
1.542     raeburn  3502: =cut
                   3503: 
1.648     raeburn  3504: 
1.466     albertel 3505: sub getemails {
                   3506:     my ($uname,$udom)=@_;
                   3507:     if ($udom eq 'public' && $uname eq 'public') {
                   3508: 	return;
                   3509:     }
1.467     www      3510:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3511:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3512:     my $id=$uname.':'.$udom;
                   3513:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3514:     if ($cached) {
                   3515: 	return %{$names};
                   3516:     } else {
                   3517: 	my %loadnames=&Apache::lonnet::get('environment',
                   3518:                     			   ['notification','critnotification',
                   3519: 					    'permanentemail'],
                   3520: 					   $udom,$uname);
                   3521: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3522: 	return %loadnames;
                   3523:     }
                   3524: }
                   3525: 
1.551     albertel 3526: sub flush_email_cache {
                   3527:     my ($uname,$udom)=@_;
                   3528:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3529:     if (!$uname) { $uname=$env{'user.name'};   }
                   3530:     return if ($udom eq 'public' && $uname eq 'public');
                   3531:     my $id=$uname.':'.$udom;
                   3532:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3533: }
                   3534: 
1.728     raeburn  3535: # -------------------------------------------------------------------- getlangs
                   3536: 
                   3537: =pod
                   3538: 
                   3539: =item * &getlangs($uname,$udom)
                   3540: 
                   3541: Gets a user's language preference and returns it as a hash with key:
                   3542: language.
                   3543: 
                   3544: =cut
                   3545: 
                   3546: 
                   3547: sub getlangs {
                   3548:     my ($uname,$udom) = @_;
                   3549:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3550:     if (!$uname) { $uname=$env{'user.name'};   }
                   3551:     my $id=$uname.':'.$udom;
                   3552:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3553:     if ($cached) {
                   3554:         return %{$langs};
                   3555:     } else {
                   3556:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3557:                                            $udom,$uname);
                   3558:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3559:         return %loadlangs;
                   3560:     }
                   3561: }
                   3562: 
                   3563: sub flush_langs_cache {
                   3564:     my ($uname,$udom)=@_;
                   3565:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3566:     if (!$uname) { $uname=$env{'user.name'};   }
                   3567:     return if ($udom eq 'public' && $uname eq 'public');
                   3568:     my $id=$uname.':'.$udom;
                   3569:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3570: }
                   3571: 
1.61      www      3572: # ------------------------------------------------------------------ Screenname
1.81      albertel 3573: 
                   3574: =pod
                   3575: 
1.648     raeburn  3576: =item * &screenname($uname,$udom)
1.81      albertel 3577: 
                   3578: Gets a users screenname and returns it as a string
                   3579: 
                   3580: =cut
1.61      www      3581: 
                   3582: sub screenname {
                   3583:     my ($uname,$udom)=@_;
1.258     albertel 3584:     if ($uname eq $env{'user.name'} &&
                   3585: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3586:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3587:     return $names{'screenname'};
1.62      www      3588: }
                   3589: 
1.212     albertel 3590: 
1.802     bisitz   3591: # ------------------------------------------------------------- Confirm Wrapper
                   3592: =pod
                   3593: 
1.1142    raeburn  3594: =item * &confirmwrapper($message)
1.802     bisitz   3595: 
                   3596: Wrap messages about completion of operation in box
                   3597: 
                   3598: =cut
                   3599: 
                   3600: sub confirmwrapper {
                   3601:     my ($message)=@_;
                   3602:     if ($message) {
                   3603:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3604:                .$message."\n"
                   3605:                .'</div>'."\n";
                   3606:     } else {
                   3607:         return $message;
                   3608:     }
                   3609: }
                   3610: 
1.62      www      3611: # ------------------------------------------------------------- Message Wrapper
                   3612: 
                   3613: sub messagewrapper {
1.369     www      3614:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3615:     return 
1.441     albertel 3616:         '<a href="/adm/email?compose=individual&amp;'.
                   3617:         'recname='.$username.'&amp;recdom='.$domain.
                   3618: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3619:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3620: }
1.802     bisitz   3621: 
1.74      www      3622: # --------------------------------------------------------------- Notes Wrapper
                   3623: 
                   3624: sub noteswrapper {
                   3625:     my ($link,$un,$do)=@_;
                   3626:     return 
1.896     amueller 3627: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3628: }
1.802     bisitz   3629: 
1.62      www      3630: # ------------------------------------------------------------- Aboutme Wrapper
                   3631: 
                   3632: sub aboutmewrapper {
1.1070    raeburn  3633:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3634:     if (!defined($username)  && !defined($domain)) {
                   3635:         return;
                   3636:     }
1.1096    raeburn  3637:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3638: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3639: }
                   3640: 
                   3641: # ------------------------------------------------------------ Syllabus Wrapper
                   3642: 
                   3643: sub syllabuswrapper {
1.707     bisitz   3644:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3645:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3646: }
1.14      harris41 3647: 
1.802     bisitz   3648: # -----------------------------------------------------------------------------
                   3649: 
1.208     matthew  3650: sub track_student_link {
1.887     raeburn  3651:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3652:     my $link ="/adm/trackstudent?";
1.208     matthew  3653:     my $title = 'View recent activity';
                   3654:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3655:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3656:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3657:         $title .= ' of this student';
1.268     albertel 3658:     } 
1.208     matthew  3659:     if (defined($target) && $target !~ /^\s*$/) {
                   3660:         $target = qq{target="$target"};
                   3661:     } else {
                   3662:         $target = '';
                   3663:     }
1.268     albertel 3664:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3665:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3666:     $title = &mt($title);
                   3667:     $linktext = &mt($linktext);
1.448     albertel 3668:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3669: 	&help_open_topic('View_recent_activity');
1.208     matthew  3670: }
                   3671: 
1.781     raeburn  3672: sub slot_reservations_link {
                   3673:     my ($linktext,$sname,$sdom,$target) = @_;
                   3674:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3675:     my $title = 'View slot reservation history';
                   3676:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3677:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3678:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3679:         $title .= ' of this student';
                   3680:     }
                   3681:     if (defined($target) && $target !~ /^\s*$/) {
                   3682:         $target = qq{target="$target"};
                   3683:     } else {
                   3684:         $target = '';
                   3685:     }
                   3686:     $title = &mt($title);
                   3687:     $linktext = &mt($linktext);
                   3688:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3689: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3690: 
                   3691: }
                   3692: 
1.508     www      3693: # ===================================================== Display a student photo
                   3694: 
                   3695: 
1.509     albertel 3696: sub student_image_tag {
1.508     www      3697:     my ($domain,$user)=@_;
                   3698:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3699:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3700: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3701:     } else {
                   3702: 	return '';
                   3703:     }
                   3704: }
                   3705: 
1.112     bowersj2 3706: =pod
                   3707: 
                   3708: =back
                   3709: 
                   3710: =head1 Access .tab File Data
                   3711: 
                   3712: =over 4
                   3713: 
1.648     raeburn  3714: =item * &languageids() 
1.112     bowersj2 3715: 
                   3716: returns list of all language ids
                   3717: 
                   3718: =cut
                   3719: 
1.14      harris41 3720: sub languageids {
1.16      harris41 3721:     return sort(keys(%language));
1.14      harris41 3722: }
                   3723: 
1.112     bowersj2 3724: =pod
                   3725: 
1.648     raeburn  3726: =item * &languagedescription() 
1.112     bowersj2 3727: 
                   3728: returns description of a specified language id
                   3729: 
                   3730: =cut
                   3731: 
1.14      harris41 3732: sub languagedescription {
1.125     www      3733:     my $code=shift;
                   3734:     return  ($supported_language{$code}?'* ':'').
                   3735:             $language{$code}.
1.126     www      3736: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3737: }
                   3738: 
1.1048    foxr     3739: =pod
                   3740: 
                   3741: =item * &plainlanguagedescription
                   3742: 
                   3743: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3744: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3745: 
                   3746: =cut
                   3747: 
1.145     www      3748: sub plainlanguagedescription {
                   3749:     my $code=shift;
                   3750:     return $language{$code};
                   3751: }
                   3752: 
1.1048    foxr     3753: =pod
                   3754: 
                   3755: =item * &supportedlanguagecode
                   3756: 
                   3757: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3758: code.
                   3759: 
                   3760: =cut
                   3761: 
1.145     www      3762: sub supportedlanguagecode {
                   3763:     my $code=shift;
                   3764:     return $supported_language{$code};
1.97      www      3765: }
                   3766: 
1.112     bowersj2 3767: =pod
                   3768: 
1.1048    foxr     3769: =item * &latexlanguage()
                   3770: 
                   3771: Given a language key code returns the correspondnig language to use
                   3772: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3773: is no supported hyphenation for the language code.
                   3774: 
                   3775: =cut
                   3776: 
                   3777: sub latexlanguage {
                   3778:     my $code = shift;
                   3779:     return $latex_language{$code};
                   3780: }
                   3781: 
                   3782: =pod
                   3783: 
                   3784: =item * &latexhyphenation()
                   3785: 
                   3786: Same as above but what's supplied is the language as it might be stored
                   3787: in the metadata.
                   3788: 
                   3789: =cut
                   3790: 
                   3791: sub latexhyphenation {
                   3792:     my $key = shift;
                   3793:     return $latex_language_bykey{$key};
                   3794: }
                   3795: 
                   3796: =pod
                   3797: 
1.648     raeburn  3798: =item * &copyrightids() 
1.112     bowersj2 3799: 
                   3800: returns list of all copyrights
                   3801: 
                   3802: =cut
                   3803: 
                   3804: sub copyrightids {
                   3805:     return sort(keys(%cprtag));
                   3806: }
                   3807: 
                   3808: =pod
                   3809: 
1.648     raeburn  3810: =item * &copyrightdescription() 
1.112     bowersj2 3811: 
                   3812: returns description of a specified copyright id
                   3813: 
                   3814: =cut
                   3815: 
                   3816: sub copyrightdescription {
1.166     www      3817:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3818: }
1.197     matthew  3819: 
                   3820: =pod
                   3821: 
1.648     raeburn  3822: =item * &source_copyrightids() 
1.192     taceyjo1 3823: 
                   3824: returns list of all source copyrights
                   3825: 
                   3826: =cut
                   3827: 
                   3828: sub source_copyrightids {
                   3829:     return sort(keys(%scprtag));
                   3830: }
                   3831: 
                   3832: =pod
                   3833: 
1.648     raeburn  3834: =item * &source_copyrightdescription() 
1.192     taceyjo1 3835: 
                   3836: returns description of a specified source copyright id
                   3837: 
                   3838: =cut
                   3839: 
                   3840: sub source_copyrightdescription {
                   3841:     return &mt($scprtag{shift(@_)});
                   3842: }
1.112     bowersj2 3843: 
                   3844: =pod
                   3845: 
1.648     raeburn  3846: =item * &filecategories() 
1.112     bowersj2 3847: 
                   3848: returns list of all file categories
                   3849: 
                   3850: =cut
                   3851: 
                   3852: sub filecategories {
                   3853:     return sort(keys(%category_extensions));
                   3854: }
                   3855: 
                   3856: =pod
                   3857: 
1.648     raeburn  3858: =item * &filecategorytypes() 
1.112     bowersj2 3859: 
                   3860: returns list of file types belonging to a given file
                   3861: category
                   3862: 
                   3863: =cut
                   3864: 
                   3865: sub filecategorytypes {
1.356     albertel 3866:     my ($cat) = @_;
                   3867:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3868: }
                   3869: 
                   3870: =pod
                   3871: 
1.648     raeburn  3872: =item * &fileembstyle() 
1.112     bowersj2 3873: 
                   3874: returns embedding style for a specified file type
                   3875: 
                   3876: =cut
                   3877: 
                   3878: sub fileembstyle {
                   3879:     return $fe{lc(shift(@_))};
1.169     www      3880: }
                   3881: 
1.351     www      3882: sub filemimetype {
                   3883:     return $fm{lc(shift(@_))};
                   3884: }
                   3885: 
1.169     www      3886: 
                   3887: sub filecategoryselect {
                   3888:     my ($name,$value)=@_;
1.189     matthew  3889:     return &select_form($value,$name,
1.970     raeburn  3890:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3891: }
                   3892: 
                   3893: =pod
                   3894: 
1.648     raeburn  3895: =item * &filedescription() 
1.112     bowersj2 3896: 
                   3897: returns description for a specified file type
                   3898: 
                   3899: =cut
                   3900: 
                   3901: sub filedescription {
1.188     matthew  3902:     my $file_description = $fd{lc(shift())};
                   3903:     $file_description =~ s:([\[\]]):~$1:g;
                   3904:     return &mt($file_description);
1.112     bowersj2 3905: }
                   3906: 
                   3907: =pod
                   3908: 
1.648     raeburn  3909: =item * &filedescriptionex() 
1.112     bowersj2 3910: 
                   3911: returns description for a specified file type with
                   3912: extra formatting
                   3913: 
                   3914: =cut
                   3915: 
                   3916: sub filedescriptionex {
                   3917:     my $ex=shift;
1.188     matthew  3918:     my $file_description = $fd{lc($ex)};
                   3919:     $file_description =~ s:([\[\]]):~$1:g;
                   3920:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3921: }
                   3922: 
                   3923: # End of .tab access
                   3924: =pod
                   3925: 
                   3926: =back
                   3927: 
                   3928: =cut
                   3929: 
                   3930: # ------------------------------------------------------------------ File Types
                   3931: sub fileextensions {
                   3932:     return sort(keys(%fe));
                   3933: }
                   3934: 
1.97      www      3935: # ----------------------------------------------------------- Display Languages
                   3936: # returns a hash with all desired display languages
                   3937: #
                   3938: 
                   3939: sub display_languages {
                   3940:     my %languages=();
1.695     raeburn  3941:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3942: 	$languages{$lang}=1;
1.97      www      3943:     }
                   3944:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3945:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3946: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3947: 	    $languages{$lang}=1;
1.97      www      3948:         }
                   3949:     }
                   3950:     return %languages;
1.14      harris41 3951: }
                   3952: 
1.582     albertel 3953: sub languages {
                   3954:     my ($possible_langs) = @_;
1.695     raeburn  3955:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3956:     if (!ref($possible_langs)) {
                   3957: 	if( wantarray ) {
                   3958: 	    return @preferred_langs;
                   3959: 	} else {
                   3960: 	    return $preferred_langs[0];
                   3961: 	}
                   3962:     }
                   3963:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3964:     my @preferred_possibilities;
                   3965:     foreach my $preferred_lang (@preferred_langs) {
                   3966: 	if (exists($possibilities{$preferred_lang})) {
                   3967: 	    push(@preferred_possibilities, $preferred_lang);
                   3968: 	}
                   3969:     }
                   3970:     if( wantarray ) {
                   3971: 	return @preferred_possibilities;
                   3972:     }
                   3973:     return $preferred_possibilities[0];
                   3974: }
                   3975: 
1.742     raeburn  3976: sub user_lang {
                   3977:     my ($touname,$toudom,$fromcid) = @_;
                   3978:     my @userlangs;
                   3979:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3980:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3981:                     $env{'course.'.$fromcid.'.languages'}));
                   3982:     } else {
                   3983:         my %langhash = &getlangs($touname,$toudom);
                   3984:         if ($langhash{'languages'} ne '') {
                   3985:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3986:         } else {
                   3987:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3988:             if ($domdefs{'lang_def'} ne '') {
                   3989:                 @userlangs = ($domdefs{'lang_def'});
                   3990:             }
                   3991:         }
                   3992:     }
                   3993:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3994:     my $user_lh = Apache::localize->get_handle(@languages);
                   3995:     return $user_lh;
                   3996: }
                   3997: 
                   3998: 
1.112     bowersj2 3999: ###############################################################
                   4000: ##               Student Answer Attempts                     ##
                   4001: ###############################################################
                   4002: 
                   4003: =pod
                   4004: 
                   4005: =head1 Alternate Problem Views
                   4006: 
                   4007: =over 4
                   4008: 
1.648     raeburn  4009: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4010:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4011: 
                   4012: Return string with previous attempt on problem. Arguments:
                   4013: 
                   4014: =over 4
                   4015: 
                   4016: =item * $symb: Problem, including path
                   4017: 
                   4018: =item * $username: username of the desired student
                   4019: 
                   4020: =item * $domain: domain of the desired student
1.14      harris41 4021: 
1.112     bowersj2 4022: =item * $course: Course ID
1.14      harris41 4023: 
1.112     bowersj2 4024: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4025:     something
1.14      harris41 4026: 
1.112     bowersj2 4027: =item * $regexp: if string matches this regexp, the string will be
                   4028:     sent to $gradesub
1.14      harris41 4029: 
1.112     bowersj2 4030: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4031: 
1.1199    raeburn  4032: =item * $usec: section of the desired student
                   4033: 
                   4034: =item * $identifier: counter for student (multiple students one problem) or 
                   4035:     problem (one student; whole sequence).
                   4036: 
1.112     bowersj2 4037: =back
1.14      harris41 4038: 
1.112     bowersj2 4039: The output string is a table containing all desired attempts, if any.
1.16      harris41 4040: 
1.112     bowersj2 4041: =cut
1.1       albertel 4042: 
                   4043: sub get_previous_attempt {
1.1199    raeburn  4044:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4045:   my $prevattempts='';
1.43      ng       4046:   no strict 'refs';
1.1       albertel 4047:   if ($symb) {
1.3       albertel 4048:     my (%returnhash)=
                   4049:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4050:     if ($returnhash{'version'}) {
                   4051:       my %lasthash=();
                   4052:       my $version;
                   4053:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4054:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4055:             if ($key =~ /\.rawrndseed$/) {
                   4056:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4057:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4058:             } else {
                   4059:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4060:             }
1.19      harris41 4061:         }
1.1       albertel 4062:       }
1.596     albertel 4063:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4064:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4065:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4066:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4067:       foreach my $key (sort(keys(%lasthash))) {
                   4068: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4069: 	if ($#parts > 0) {
1.31      albertel 4070: 	  my $data=$parts[-1];
1.989     raeburn  4071:           next if ($data eq 'foilorder');
1.31      albertel 4072: 	  pop(@parts);
1.1010    www      4073:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4074:           if ($data eq 'type') {
                   4075:               unless ($showsurv) {
                   4076:                   my $id = join(',',@parts);
                   4077:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4078:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4079:                       $lasthidden{$ign.'.'.$id} = 1;
                   4080:                   }
1.945     raeburn  4081:               }
1.1199    raeburn  4082:               if ($identifier ne '') {
                   4083:                   my $id = join(',',@parts);
                   4084:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4085:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4086:                       $hidestatus{$ign.'.'.$id} = 1;
                   4087:                   }
                   4088:               }
                   4089:           } elsif ($data eq 'regrader') {
                   4090:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4091:                   my $id = join(',',@parts);
                   4092:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4093:               }
1.1010    www      4094:           } 
1.31      albertel 4095: 	} else {
1.41      ng       4096: 	  if ($#parts == 0) {
                   4097: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4098: 	  } else {
                   4099: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4100: 	  }
1.31      albertel 4101: 	}
1.16      harris41 4102:       }
1.596     albertel 4103:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4104:       if ($getattempt eq '') {
1.1199    raeburn  4105:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4106:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4107:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4108:                 foreach my $id (keys(%regraded)) {
                   4109:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4110:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4111:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4112:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4113:                     }
                   4114:                 }
                   4115:             }
1.1200    raeburn  4116:         }
                   4117: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4118:             my (@hidden,@unsolved);
1.945     raeburn  4119:             if (%typeparts) {
                   4120:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4121:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4122:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4123:                         push(@hidden,$id);
1.1199    raeburn  4124:                     } elsif ($identifier ne '') {
                   4125:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4126:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4127:                                 ($hidestatus{$id})) {
1.1200    raeburn  4128:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4129:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4130:                                 push(@{$solved{$id}},$version);
                   4131:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4132:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4133:                                 my $skip;
                   4134:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4135:                                     foreach my $reset (@{$resets{$id}}) {
                   4136:                                         if ($reset > $solved{$id}[-1]) {
                   4137:                                             $skip=1;
                   4138:                                             last;
                   4139:                                         }
                   4140:                                     }
                   4141:                                 }
                   4142:                                 unless ($skip) {
                   4143:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4144:                                     push(@unsolved,$partslist);
                   4145:                                 }
                   4146:                             }
                   4147:                         }
1.945     raeburn  4148:                     }
                   4149:                 }
                   4150:             }
                   4151:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4152:                            '<td>'.&mt('Transaction [_1]',$version);
                   4153:             if (@unsolved) {
                   4154:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4155:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4156:                                  &mt('Hide').'</label></span>';
                   4157:             }
                   4158:             $prevattempts .= '</td>';
1.945     raeburn  4159:             if (@hidden) {
                   4160:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4161:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4162:                     my $hide;
                   4163:                     foreach my $id (@hidden) {
                   4164:                         if ($key =~ /^\Q$id\E/) {
                   4165:                             $hide = 1;
                   4166:                             last;
                   4167:                         }
                   4168:                     }
                   4169:                     if ($hide) {
                   4170:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4171:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4172:                             my $value = &format_previous_attempt_value($key,
                   4173:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4174:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4175:                         } else {
                   4176:                             $prevattempts.='<td>&nbsp;</td>';
                   4177:                         }
                   4178:                     } else {
                   4179:                         if ($key =~ /\./) {
1.1212    raeburn  4180:                             my $value = $returnhash{$version.':'.$key};
                   4181:                             if ($key =~ /\.rndseed$/) {
                   4182:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4183:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4184:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4185:                                 }
                   4186:                             }
                   4187:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4188:                                            '&nbsp;</td>';
1.945     raeburn  4189:                         } else {
                   4190:                             $prevattempts.='<td>&nbsp;</td>';
                   4191:                         }
                   4192:                     }
                   4193:                 }
                   4194:             } else {
                   4195: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4196:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4197:                     my $value = $returnhash{$version.':'.$key};
                   4198:                     if ($key =~ /\.rndseed$/) {
                   4199:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4200:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4201:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4202:                         }
                   4203:                     }
                   4204:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4205:                                    '&nbsp;</td>';
1.945     raeburn  4206: 	        }
                   4207:             }
                   4208: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4209: 	 }
1.1       albertel 4210:       }
1.945     raeburn  4211:       my @currhidden = keys(%lasthidden);
1.596     albertel 4212:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4213:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4214:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4215:           if (%typeparts) {
                   4216:               my $hidden;
                   4217:               foreach my $id (@currhidden) {
                   4218:                   if ($key =~ /^\Q$id\E/) {
                   4219:                       $hidden = 1;
                   4220:                       last;
                   4221:                   }
                   4222:               }
                   4223:               if ($hidden) {
                   4224:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4225:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4226:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4227:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4228:                           $value = &$gradesub($value);
                   4229:                       }
1.1173    kruse    4230:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4231:                   } else {
                   4232:                       $prevattempts.='<td>&nbsp;</td>';
                   4233:                   }
                   4234:               } else {
                   4235:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4236:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4237:                       $value = &$gradesub($value);
                   4238:                   }
1.1173    kruse    4239:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4240:               }
                   4241:           } else {
                   4242: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4243: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4244:                   $value = &$gradesub($value);
                   4245:               }
1.1173    kruse    4246: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4247:           }
1.16      harris41 4248:       }
1.596     albertel 4249:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4250:     } else {
1.596     albertel 4251:       $prevattempts=
                   4252: 	  &start_data_table().&start_data_table_row().
                   4253: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4254: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4255:     }
                   4256:   } else {
1.596     albertel 4257:     $prevattempts=
                   4258: 	  &start_data_table().&start_data_table_row().
                   4259: 	  '<td>'.&mt('No data.').'</td>'.
                   4260: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4261:   }
1.10      albertel 4262: }
                   4263: 
1.581     albertel 4264: sub format_previous_attempt_value {
                   4265:     my ($key,$value) = @_;
1.1011    www      4266:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4267:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4268:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4269:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4270:     } elsif ($key =~ /answerstring$/) {
                   4271:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4272:         my @answer = %answers;
                   4273:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4274:         my @anskeys = sort(keys(%answers));
                   4275:         if (@anskeys == 1) {
                   4276:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4277:             if ($answer =~ m{\0}) {
                   4278:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4279:             }
                   4280:             my $tag_internal_answer_name = 'INTERNAL';
                   4281:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4282:                 $value = $answer; 
                   4283:             } else {
                   4284:                 $value = $anskeys[0].'='.$answer;
                   4285:             }
                   4286:         } else {
                   4287:             foreach my $ans (@anskeys) {
                   4288:                 my $answer = $answers{$ans};
1.1001    raeburn  4289:                 if ($answer =~ m{\0}) {
                   4290:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4291:                 }
                   4292:                 $value .=  $ans.'='.$answer.'<br />';;
                   4293:             } 
                   4294:         }
1.581     albertel 4295:     } else {
1.1173    kruse    4296:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4297:     }
                   4298:     return $value;
                   4299: }
                   4300: 
                   4301: 
1.107     albertel 4302: sub relative_to_absolute {
                   4303:     my ($url,$output)=@_;
                   4304:     my $parser=HTML::TokeParser->new(\$output);
                   4305:     my $token;
                   4306:     my $thisdir=$url;
                   4307:     my @rlinks=();
                   4308:     while ($token=$parser->get_token) {
                   4309: 	if ($token->[0] eq 'S') {
                   4310: 	    if ($token->[1] eq 'a') {
                   4311: 		if ($token->[2]->{'href'}) {
                   4312: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4313: 		}
                   4314: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4315: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4316: 	    } elsif ($token->[1] eq 'base') {
                   4317: 		$thisdir=$token->[2]->{'href'};
                   4318: 	    }
                   4319: 	}
                   4320:     }
                   4321:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4322:     foreach my $link (@rlinks) {
1.726     raeburn  4323: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4324: 		($link=~/^\//) ||
                   4325: 		($link=~/^javascript:/i) ||
                   4326: 		($link=~/^mailto:/i) ||
                   4327: 		($link=~/^\#/)) {
                   4328: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4329: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4330: 	}
                   4331:     }
                   4332: # -------------------------------------------------- Deal with Applet codebases
                   4333:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4334:     return $output;
                   4335: }
                   4336: 
1.112     bowersj2 4337: =pod
                   4338: 
1.648     raeburn  4339: =item * &get_student_view()
1.112     bowersj2 4340: 
                   4341: show a snapshot of what student was looking at
                   4342: 
                   4343: =cut
                   4344: 
1.10      albertel 4345: sub get_student_view {
1.186     albertel 4346:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4347:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4348:   my (%form);
1.10      albertel 4349:   my @elements=('symb','courseid','domain','username');
                   4350:   foreach my $element (@elements) {
1.186     albertel 4351:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4352:   }
1.186     albertel 4353:   if (defined($moreenv)) {
                   4354:       %form=(%form,%{$moreenv});
                   4355:   }
1.236     albertel 4356:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4357:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4358:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4359:   $userview=~s/\<body[^\>]*\>//gi;
                   4360:   $userview=~s/\<\/body\>//gi;
                   4361:   $userview=~s/\<html\>//gi;
                   4362:   $userview=~s/\<\/html\>//gi;
                   4363:   $userview=~s/\<head\>//gi;
                   4364:   $userview=~s/\<\/head\>//gi;
                   4365:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4366:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4367:   if (wantarray) {
                   4368:      return ($userview,$response);
                   4369:   } else {
                   4370:      return $userview;
                   4371:   }
                   4372: }
                   4373: 
                   4374: sub get_student_view_with_retries {
                   4375:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4376: 
                   4377:     my $ok = 0;                 # True if we got a good response.
                   4378:     my $content;
                   4379:     my $response;
                   4380: 
                   4381:     # Try to get the student_view done. within the retries count:
                   4382:     
                   4383:     do {
                   4384:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4385:          $ok      = $response->is_success;
                   4386:          if (!$ok) {
                   4387:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4388:          }
                   4389:          $retries--;
                   4390:     } while (!$ok && ($retries > 0));
                   4391:     
                   4392:     if (!$ok) {
                   4393:        $content = '';          # On error return an empty content.
                   4394:     }
1.651     www      4395:     if (wantarray) {
                   4396:        return ($content, $response);
                   4397:     } else {
                   4398:        return $content;
                   4399:     }
1.11      albertel 4400: }
                   4401: 
1.112     bowersj2 4402: =pod
                   4403: 
1.648     raeburn  4404: =item * &get_student_answers() 
1.112     bowersj2 4405: 
                   4406: show a snapshot of how student was answering problem
                   4407: 
                   4408: =cut
                   4409: 
1.11      albertel 4410: sub get_student_answers {
1.100     sakharuk 4411:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4412:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4413:   my (%moreenv);
1.11      albertel 4414:   my @elements=('symb','courseid','domain','username');
                   4415:   foreach my $element (@elements) {
1.186     albertel 4416:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4417:   }
1.186     albertel 4418:   $moreenv{'grade_target'}='answer';
                   4419:   %moreenv=(%form,%moreenv);
1.497     raeburn  4420:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4421:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4422:   return $userview;
1.1       albertel 4423: }
1.116     albertel 4424: 
                   4425: =pod
                   4426: 
                   4427: =item * &submlink()
                   4428: 
1.242     albertel 4429: Inputs: $text $uname $udom $symb $target
1.116     albertel 4430: 
                   4431: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4432: 
                   4433: =cut
                   4434: 
                   4435: ###############################################
                   4436: sub submlink {
1.242     albertel 4437:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4438:     if (!($uname && $udom)) {
                   4439: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4440: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4441: 	if (!$symb) { $symb=$cursymb; }
                   4442:     }
1.254     matthew  4443:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4444:     $symb=&escape($symb);
1.960     bisitz   4445:     if ($target) { $target=" target=\"$target\""; }
                   4446:     return
                   4447:         '<a href="/adm/grades?command=submission'.
                   4448:         '&amp;symb='.$symb.
                   4449:         '&amp;student='.$uname.
                   4450:         '&amp;userdom='.$udom.'"'.
                   4451:         $target.'>'.$text.'</a>';
1.242     albertel 4452: }
                   4453: ##############################################
                   4454: 
                   4455: =pod
                   4456: 
                   4457: =item * &pgrdlink()
                   4458: 
                   4459: Inputs: $text $uname $udom $symb $target
                   4460: 
                   4461: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4462: 
                   4463: =cut
                   4464: 
                   4465: ###############################################
                   4466: sub pgrdlink {
                   4467:     my $link=&submlink(@_);
                   4468:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4469:     return $link;
                   4470: }
                   4471: ##############################################
                   4472: 
                   4473: =pod
                   4474: 
                   4475: =item * &pprmlink()
                   4476: 
                   4477: Inputs: $text $uname $udom $symb $target
                   4478: 
                   4479: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4480: student and a specific resource
1.242     albertel 4481: 
                   4482: =cut
                   4483: 
                   4484: ###############################################
                   4485: sub pprmlink {
                   4486:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4487:     if (!($uname && $udom)) {
                   4488: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4489: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4490: 	if (!$symb) { $symb=$cursymb; }
                   4491:     }
1.254     matthew  4492:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4493:     $symb=&escape($symb);
1.242     albertel 4494:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4495:     return '<a href="/adm/parmset?command=set&amp;'.
                   4496: 	'symb='.$symb.'&amp;uname='.$uname.
                   4497: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4498: }
                   4499: ##############################################
1.37      matthew  4500: 
1.112     bowersj2 4501: =pod
                   4502: 
                   4503: =back
                   4504: 
                   4505: =cut
                   4506: 
1.37      matthew  4507: ###############################################
1.51      www      4508: 
                   4509: 
                   4510: sub timehash {
1.687     raeburn  4511:     my ($thistime) = @_;
                   4512:     my $timezone = &Apache::lonlocal::gettimezone();
                   4513:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4514:                      ->set_time_zone($timezone);
                   4515:     my $wday = $dt->day_of_week();
                   4516:     if ($wday == 7) { $wday = 0; }
                   4517:     return ( 'second' => $dt->second(),
                   4518:              'minute' => $dt->minute(),
                   4519:              'hour'   => $dt->hour(),
                   4520:              'day'     => $dt->day_of_month(),
                   4521:              'month'   => $dt->month(),
                   4522:              'year'    => $dt->year(),
                   4523:              'weekday' => $wday,
                   4524:              'dayyear' => $dt->day_of_year(),
                   4525:              'dlsav'   => $dt->is_dst() );
1.51      www      4526: }
                   4527: 
1.370     www      4528: sub utc_string {
                   4529:     my ($date)=@_;
1.371     www      4530:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4531: }
                   4532: 
1.51      www      4533: sub maketime {
                   4534:     my %th=@_;
1.687     raeburn  4535:     my ($epoch_time,$timezone,$dt);
                   4536:     $timezone = &Apache::lonlocal::gettimezone();
                   4537:     eval {
                   4538:         $dt = DateTime->new( year   => $th{'year'},
                   4539:                              month  => $th{'month'},
                   4540:                              day    => $th{'day'},
                   4541:                              hour   => $th{'hour'},
                   4542:                              minute => $th{'minute'},
                   4543:                              second => $th{'second'},
                   4544:                              time_zone => $timezone,
                   4545:                          );
                   4546:     };
                   4547:     if (!$@) {
                   4548:         $epoch_time = $dt->epoch;
                   4549:         if ($epoch_time) {
                   4550:             return $epoch_time;
                   4551:         }
                   4552:     }
1.51      www      4553:     return POSIX::mktime(
                   4554:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4555:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4556: }
                   4557: 
                   4558: #########################################
1.51      www      4559: 
                   4560: sub findallcourses {
1.482     raeburn  4561:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4562:     my %roles;
                   4563:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4564:     my %courses;
1.51      www      4565:     my $now=time;
1.482     raeburn  4566:     if (!defined($uname)) {
                   4567:         $uname = $env{'user.name'};
                   4568:     }
                   4569:     if (!defined($udom)) {
                   4570:         $udom = $env{'user.domain'};
                   4571:     }
                   4572:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4573:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4574:         if (!%roles) {
                   4575:             %roles = (
                   4576:                        cc => 1,
1.907     raeburn  4577:                        co => 1,
1.482     raeburn  4578:                        in => 1,
                   4579:                        ep => 1,
                   4580:                        ta => 1,
                   4581:                        cr => 1,
                   4582:                        st => 1,
                   4583:              );
                   4584:         }
                   4585:         foreach my $entry (keys(%roleshash)) {
                   4586:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4587:             if ($trole =~ /^cr/) { 
                   4588:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4589:             } else {
                   4590:                 next if (!exists($roles{$trole}));
                   4591:             }
                   4592:             if ($tend) {
                   4593:                 next if ($tend < $now);
                   4594:             }
                   4595:             if ($tstart) {
                   4596:                 next if ($tstart > $now);
                   4597:             }
1.1058    raeburn  4598:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4599:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4600:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4601:             if ($secpart eq '') {
                   4602:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4603:                 $sec = 'none';
1.1058    raeburn  4604:                 $value .= $cnum.'/';
1.482     raeburn  4605:             } else {
                   4606:                 $cnum = $cnumpart;
                   4607:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4608:                 $value .= $cnum.'/'.$sec;
                   4609:             }
                   4610:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4611:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4612:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4613:                 }
                   4614:             } else {
                   4615:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4616:             }
1.482     raeburn  4617:         }
                   4618:     } else {
                   4619:         foreach my $key (keys(%env)) {
1.483     albertel 4620: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4621:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4622: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4623: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4624: 	        next if (%roles && !exists($roles{$role}));
                   4625: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4626:                 my $active=1;
                   4627:                 if ($starttime) {
                   4628: 		    if ($now<$starttime) { $active=0; }
                   4629:                 }
                   4630:                 if ($endtime) {
                   4631:                     if ($now>$endtime) { $active=0; }
                   4632:                 }
                   4633:                 if ($active) {
1.1058    raeburn  4634:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4635:                     if ($sec eq '') {
                   4636:                         $sec = 'none';
1.1058    raeburn  4637:                     } else {
                   4638:                         $value .= $sec;
                   4639:                     }
                   4640:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4641:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4642:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4643:                         }
                   4644:                     } else {
                   4645:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4646:                     }
1.474     raeburn  4647:                 }
                   4648:             }
1.51      www      4649:         }
                   4650:     }
1.474     raeburn  4651:     return %courses;
1.51      www      4652: }
1.37      matthew  4653: 
1.54      www      4654: ###############################################
1.474     raeburn  4655: 
                   4656: sub blockcheck {
1.1189    raeburn  4657:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4658: 
1.1189    raeburn  4659:     if (defined($udom) && defined($uname)) {
                   4660:         # If uname and udom are for a course, check for blocks in the course.
                   4661:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4662:             my ($startblock,$endblock,$triggerblock) =
                   4663:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4664:             return ($startblock,$endblock,$triggerblock);
                   4665:         }
                   4666:     } else {
1.490     raeburn  4667:         $udom = $env{'user.domain'};
                   4668:         $uname = $env{'user.name'};
                   4669:     }
                   4670: 
1.502     raeburn  4671:     my $startblock = 0;
                   4672:     my $endblock = 0;
1.1062    raeburn  4673:     my $triggerblock = '';
1.482     raeburn  4674:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4675: 
1.490     raeburn  4676:     # If uname is for a user, and activity is course-specific, i.e.,
                   4677:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4678: 
1.490     raeburn  4679:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1189    raeburn  4680:          $activity eq 'groups' || $activity eq 'printout') &&
                   4681:         ($env{'request.course.id'})) {
1.490     raeburn  4682:         foreach my $key (keys(%live_courses)) {
                   4683:             if ($key ne $env{'request.course.id'}) {
                   4684:                 delete($live_courses{$key});
                   4685:             }
                   4686:         }
                   4687:     }
                   4688: 
                   4689:     my $otheruser = 0;
                   4690:     my %own_courses;
                   4691:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4692:         # Resource belongs to user other than current user.
                   4693:         $otheruser = 1;
                   4694:         # Gather courses for current user
                   4695:         %own_courses = 
                   4696:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4697:     }
                   4698: 
                   4699:     # Gather active course roles - course coordinator, instructor, 
                   4700:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4701: 
                   4702:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4703:         my ($cdom,$cnum);
                   4704:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4705:             $cdom = $env{'course.'.$course.'.domain'};
                   4706:             $cnum = $env{'course.'.$course.'.num'};
                   4707:         } else {
1.490     raeburn  4708:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4709:         }
                   4710:         my $no_ownblock = 0;
                   4711:         my $no_userblock = 0;
1.533     raeburn  4712:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4713:             # Check if current user has 'evb' priv for this
                   4714:             if (defined($own_courses{$course})) {
                   4715:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4716:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4717:                     if ($sec ne 'none') {
                   4718:                         $checkrole .= '/'.$sec;
                   4719:                     }
                   4720:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4721:                         $no_ownblock = 1;
                   4722:                         last;
                   4723:                     }
                   4724:                 }
                   4725:             }
                   4726:             # if they have 'evb' priv and are currently not playing student
                   4727:             next if (($no_ownblock) &&
                   4728:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4729:         }
1.474     raeburn  4730:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4731:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4732:             if ($sec ne 'none') {
1.482     raeburn  4733:                 $checkrole .= '/'.$sec;
1.474     raeburn  4734:             }
1.490     raeburn  4735:             if ($otheruser) {
                   4736:                 # Resource belongs to user other than current user.
                   4737:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4738:                 my (%allroles,%userroles);
                   4739:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4740:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4741:                         my ($trole,$tdom,$tnum,$tsec);
                   4742:                         if ($entry =~ /^cr/) {
                   4743:                             ($trole,$tdom,$tnum,$tsec) = 
                   4744:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4745:                         } else {
                   4746:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4747:                         }
                   4748:                         my ($spec,$area,$trest);
                   4749:                         $area = '/'.$tdom.'/'.$tnum;
                   4750:                         $trest = $tnum;
                   4751:                         if ($tsec ne '') {
                   4752:                             $area .= '/'.$tsec;
                   4753:                             $trest .= '/'.$tsec;
                   4754:                         }
                   4755:                         $spec = $trole.'.'.$area;
                   4756:                         if ($trole =~ /^cr/) {
                   4757:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4758:                                                               $tdom,$spec,$trest,$area);
                   4759:                         } else {
                   4760:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4761:                                                                 $tdom,$spec,$trest,$area);
                   4762:                         }
                   4763:                     }
                   4764:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4765:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4766:                         if ($1) {
                   4767:                             $no_userblock = 1;
                   4768:                             last;
                   4769:                         }
1.486     raeburn  4770:                     }
                   4771:                 }
1.490     raeburn  4772:             } else {
                   4773:                 # Resource belongs to current user
                   4774:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4775:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4776:                     $no_ownblock = 1;
                   4777:                     last;
                   4778:                 }
1.474     raeburn  4779:             }
                   4780:         }
                   4781:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4782:         next if (($no_ownblock) &&
1.491     albertel 4783:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4784:         next if ($no_userblock);
1.474     raeburn  4785: 
1.866     kalberla 4786:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4787:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4788:         
1.1062    raeburn  4789:         my ($start,$end,$trigger) = 
                   4790:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4791:         if (($start != 0) && 
                   4792:             (($startblock == 0) || ($startblock > $start))) {
                   4793:             $startblock = $start;
1.1062    raeburn  4794:             if ($trigger ne '') {
                   4795:                 $triggerblock = $trigger;
                   4796:             }
1.502     raeburn  4797:         }
                   4798:         if (($end != 0)  &&
                   4799:             (($endblock == 0) || ($endblock < $end))) {
                   4800:             $endblock = $end;
1.1062    raeburn  4801:             if ($trigger ne '') {
                   4802:                 $triggerblock = $trigger;
                   4803:             }
1.502     raeburn  4804:         }
1.490     raeburn  4805:     }
1.1062    raeburn  4806:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4807: }
                   4808: 
                   4809: sub get_blocks {
1.1062    raeburn  4810:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4811:     my $startblock = 0;
                   4812:     my $endblock = 0;
1.1062    raeburn  4813:     my $triggerblock = '';
1.490     raeburn  4814:     my $course = $cdom.'_'.$cnum;
                   4815:     $setters->{$course} = {};
                   4816:     $setters->{$course}{'staff'} = [];
                   4817:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4818:     $setters->{$course}{'triggers'} = [];
                   4819:     my (@blockers,%triggered);
                   4820:     my $now = time;
                   4821:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4822:     if ($activity eq 'docs') {
                   4823:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4824:         foreach my $block (@blockers) {
                   4825:             if ($block =~ /^firstaccess____(.+)$/) {
                   4826:                 my $item = $1;
                   4827:                 my $type = 'map';
                   4828:                 my $timersymb = $item;
                   4829:                 if ($item eq 'course') {
                   4830:                     $type = 'course';
                   4831:                 } elsif ($item =~ /___\d+___/) {
                   4832:                     $type = 'resource';
                   4833:                 } else {
                   4834:                     $timersymb = &Apache::lonnet::symbread($item);
                   4835:                 }
                   4836:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4837:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4838:                 $triggered{$block} = {
                   4839:                                        start => $start,
                   4840:                                        end   => $end,
                   4841:                                        type  => $type,
                   4842:                                      };
                   4843:             }
                   4844:         }
                   4845:     } else {
                   4846:         foreach my $block (keys(%commblocks)) {
                   4847:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4848:                 my ($start,$end) = ($1,$2);
                   4849:                 if ($start <= time && $end >= time) {
                   4850:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4851:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4852:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4853:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4854:                                     push(@blockers,$block);
                   4855:                                 }
                   4856:                             }
                   4857:                         }
                   4858:                     }
                   4859:                 }
                   4860:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4861:                 my $item = $1;
                   4862:                 my $timersymb = $item; 
                   4863:                 my $type = 'map';
                   4864:                 if ($item eq 'course') {
                   4865:                     $type = 'course';
                   4866:                 } elsif ($item =~ /___\d+___/) {
                   4867:                     $type = 'resource';
                   4868:                 } else {
                   4869:                     $timersymb = &Apache::lonnet::symbread($item);
                   4870:                 }
                   4871:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4872:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4873:                 if ($start && $end) {
                   4874:                     if (($start <= time) && ($end >= time)) {
                   4875:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4876:                             push(@blockers,$block);
                   4877:                             $triggered{$block} = {
                   4878:                                                    start => $start,
                   4879:                                                    end   => $end,
                   4880:                                                    type  => $type,
                   4881:                                                  };
                   4882:                         }
                   4883:                     }
1.490     raeburn  4884:                 }
1.1062    raeburn  4885:             }
                   4886:         }
                   4887:     }
                   4888:     foreach my $blocker (@blockers) {
                   4889:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4890:             &parse_block_record($commblocks{$blocker});
                   4891:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4892:         my ($start,$end,$triggertype);
                   4893:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4894:             ($start,$end) = ($1,$2);
                   4895:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4896:             $start = $triggered{$blocker}{'start'};
                   4897:             $end = $triggered{$blocker}{'end'};
                   4898:             $triggertype = $triggered{$blocker}{'type'};
                   4899:         }
                   4900:         if ($start) {
                   4901:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4902:             if ($triggertype) {
                   4903:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4904:             } else {
                   4905:                 push(@{$$setters{$course}{'triggers'}},0);
                   4906:             }
                   4907:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4908:                 $startblock = $start;
                   4909:                 if ($triggertype) {
                   4910:                     $triggerblock = $blocker;
1.474     raeburn  4911:                 }
                   4912:             }
1.1062    raeburn  4913:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4914:                $endblock = $end;
                   4915:                if ($triggertype) {
                   4916:                    $triggerblock = $blocker;
                   4917:                }
                   4918:             }
1.474     raeburn  4919:         }
                   4920:     }
1.1062    raeburn  4921:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4922: }
                   4923: 
                   4924: sub parse_block_record {
                   4925:     my ($record) = @_;
                   4926:     my ($setuname,$setudom,$title,$blocks);
                   4927:     if (ref($record) eq 'HASH') {
                   4928:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4929:         $title = &unescape($record->{'event'});
                   4930:         $blocks = $record->{'blocks'};
                   4931:     } else {
                   4932:         my @data = split(/:/,$record,3);
                   4933:         if (scalar(@data) eq 2) {
                   4934:             $title = $data[1];
                   4935:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4936:         } else {
                   4937:             ($setuname,$setudom,$title) = @data;
                   4938:         }
                   4939:         $blocks = { 'com' => 'on' };
                   4940:     }
                   4941:     return ($setuname,$setudom,$title,$blocks);
                   4942: }
                   4943: 
1.854     kalberla 4944: sub blocking_status {
1.1189    raeburn  4945:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4946:     my %setters;
1.890     droeschl 4947: 
1.1061    raeburn  4948: # check for active blocking
1.1062    raeburn  4949:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  4950:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4951:     my $blocked = 0;
                   4952:     if ($startblock && $endblock) {
                   4953:         $blocked = 1;
                   4954:     }
1.890     droeschl 4955: 
1.1061    raeburn  4956: # caller just wants to know whether a block is active
                   4957:     if (!wantarray) { return $blocked; }
                   4958: 
                   4959: # build a link to a popup window containing the details
                   4960:     my $querystring  = "?activity=$activity";
                   4961: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4962:     if ($activity eq 'port') {
                   4963:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4964:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4965:     } elsif ($activity eq 'docs') {
                   4966:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4967:     }
1.1061    raeburn  4968: 
                   4969:     my $output .= <<'END_MYBLOCK';
                   4970: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4971:     var options = "width=" + w + ",height=" + h + ",";
                   4972:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4973:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4974:     var newWin = window.open(url, wdwName, options);
                   4975:     newWin.focus();
                   4976: }
1.890     droeschl 4977: END_MYBLOCK
1.854     kalberla 4978: 
1.1061    raeburn  4979:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4980:   
1.1061    raeburn  4981:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4982:     my $text = &mt('Communication Blocked');
1.1217    raeburn  4983:     my $class = 'LC_comblock';
1.1062    raeburn  4984:     if ($activity eq 'docs') {
                   4985:         $text = &mt('Content Access Blocked');
1.1217    raeburn  4986:         $class = '';
1.1063    raeburn  4987:     } elsif ($activity eq 'printout') {
                   4988:         $text = &mt('Printing Blocked');
1.1062    raeburn  4989:     }
1.1061    raeburn  4990:     $output .= <<"END_BLOCK";
1.1217    raeburn  4991: <div class='$class'>
1.869     kalberla 4992:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4993:   title='$text'>
                   4994:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4995:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4996:   title='$text'>$text</a>
1.867     kalberla 4997: </div>
                   4998: 
                   4999: END_BLOCK
1.474     raeburn  5000: 
1.1061    raeburn  5001:     return ($blocked, $output);
1.854     kalberla 5002: }
1.490     raeburn  5003: 
1.60      matthew  5004: ###############################################
                   5005: 
1.682     raeburn  5006: sub check_ip_acc {
1.1201    raeburn  5007:     my ($acc,$clientip)=@_;
1.682     raeburn  5008:     &Apache::lonxml::debug("acc is $acc");
                   5009:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5010:         return 1;
                   5011:     }
1.1219    raeburn  5012:     my $allowed;
1.1201    raeburn  5013:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
1.682     raeburn  5014: 
                   5015:     my $name;
1.1219    raeburn  5016:     my %access = (
                   5017:                      allowfrom => 1,
                   5018:                      denyfrom  => 0,
                   5019:                  );
                   5020:     my @allows;
                   5021:     my @denies;
                   5022:     foreach my $item (split(',',$acc)) {
                   5023:         $item =~ s/^\s*//;
                   5024:         $item =~ s/\s*$//;
                   5025:         my $pattern;
                   5026:         if ($item =~ /^\!(.+)$/) {
                   5027:             push(@denies,$1);
                   5028:         } else {
                   5029:             push(@allows,$item);
                   5030:         }
                   5031:    }
                   5032:    my $numdenies = scalar(@denies);
                   5033:    my $numallows = scalar(@allows);
                   5034:    my $count = 0;
                   5035:    foreach my $pattern (@denies,@allows) {
                   5036:         $count ++; 
                   5037:         my $acctype = 'allowfrom';
                   5038:         if ($count <= $numdenies) {
                   5039:             $acctype = 'denyfrom';
                   5040:         }
1.682     raeburn  5041:         if ($pattern =~ /\*$/) {
                   5042:             #35.8.*
                   5043:             $pattern=~s/\*//;
1.1219    raeburn  5044:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5045:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5046:             #35.8.3.[34-56]
                   5047:             my $low=$2;
                   5048:             my $high=$3;
                   5049:             $pattern=$1;
                   5050:             if ($ip =~ /^\Q$pattern\E/) {
                   5051:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5052:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5053:             }
                   5054:         } elsif ($pattern =~ /^\*/) {
                   5055:             #*.msu.edu
                   5056:             $pattern=~s/\*//;
                   5057:             if (!defined($name)) {
                   5058:                 use Socket;
                   5059:                 my $netaddr=inet_aton($ip);
                   5060:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5061:             }
1.1219    raeburn  5062:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5063:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5064:             #127.0.0.1
1.1219    raeburn  5065:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5066:         } else {
                   5067:             #some.name.com
                   5068:             if (!defined($name)) {
                   5069:                 use Socket;
                   5070:                 my $netaddr=inet_aton($ip);
                   5071:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5072:             }
1.1219    raeburn  5073:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5074:         }
                   5075:         if ($allowed =~ /^(0|1)$/) { last; }
                   5076:     }
                   5077:     if ($allowed eq '') {
                   5078:         if ($numdenies && !$numallows) {
                   5079:             $allowed = 1;
                   5080:         } else {
                   5081:             $allowed = 0;
1.682     raeburn  5082:         }
                   5083:     }
                   5084:     return $allowed;
                   5085: }
                   5086: 
                   5087: ###############################################
                   5088: 
1.60      matthew  5089: =pod
                   5090: 
1.112     bowersj2 5091: =head1 Domain Template Functions
                   5092: 
                   5093: =over 4
                   5094: 
                   5095: =item * &determinedomain()
1.60      matthew  5096: 
                   5097: Inputs: $domain (usually will be undef)
                   5098: 
1.63      www      5099: Returns: Determines which domain should be used for designs
1.60      matthew  5100: 
                   5101: =cut
1.54      www      5102: 
1.60      matthew  5103: ###############################################
1.63      www      5104: sub determinedomain {
                   5105:     my $domain=shift;
1.531     albertel 5106:     if (! $domain) {
1.60      matthew  5107:         # Determine domain if we have not been given one
1.893     raeburn  5108:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5109:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5110:         if ($env{'request.role.domain'}) { 
                   5111:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5112:         }
                   5113:     }
1.63      www      5114:     return $domain;
                   5115: }
                   5116: ###############################################
1.517     raeburn  5117: 
1.518     albertel 5118: sub devalidate_domconfig_cache {
                   5119:     my ($udom)=@_;
                   5120:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5121: }
                   5122: 
                   5123: # ---------------------- Get domain configuration for a domain
                   5124: sub get_domainconf {
                   5125:     my ($udom) = @_;
                   5126:     my $cachetime=1800;
                   5127:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5128:     if (defined($cached)) { return %{$result}; }
                   5129: 
                   5130:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5131: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5132:     my (%designhash,%legacy);
1.518     albertel 5133:     if (keys(%domconfig) > 0) {
                   5134:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5135:             if (keys(%{$domconfig{'login'}})) {
                   5136:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5137:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5138:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5139:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5140:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5141:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5142:                                         if ($key eq 'loginvia') {
                   5143:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5144:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5145:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5146:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5147: 
                   5148:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5149:                                                 } else {
                   5150:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5151:                                                 }
1.948     raeburn  5152:                                             }
1.1208    raeburn  5153:                                         } elsif ($key eq 'headtag') {
                   5154:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5155:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5156:                                             }
1.946     raeburn  5157:                                         }
1.1208    raeburn  5158:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5159:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5160:                                         }
1.946     raeburn  5161:                                     }
                   5162:                                 }
                   5163:                             }
                   5164:                         } else {
                   5165:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5166:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5167:                                     $domconfig{'login'}{$key}{$img};
                   5168:                             }
1.699     raeburn  5169:                         }
                   5170:                     } else {
                   5171:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5172:                     }
1.632     raeburn  5173:                 }
                   5174:             } else {
                   5175:                 $legacy{'login'} = 1;
1.518     albertel 5176:             }
1.632     raeburn  5177:         } else {
                   5178:             $legacy{'login'} = 1;
1.518     albertel 5179:         }
                   5180:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5181:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5182:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5183:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5184:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5185:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5186:                         }
1.518     albertel 5187:                     }
                   5188:                 }
1.632     raeburn  5189:             } else {
                   5190:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5191:             }
1.632     raeburn  5192:         } else {
                   5193:             $legacy{'rolecolors'} = 1;
1.518     albertel 5194:         }
1.948     raeburn  5195:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5196:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5197:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5198:             }
                   5199:         }
1.632     raeburn  5200:         if (keys(%legacy) > 0) {
                   5201:             my %legacyhash = &get_legacy_domconf($udom);
                   5202:             foreach my $item (keys(%legacyhash)) {
                   5203:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5204:                     if ($legacy{'login'}) { 
                   5205:                         $designhash{$item} = $legacyhash{$item};
                   5206:                     }
                   5207:                 } else {
                   5208:                     if ($legacy{'rolecolors'}) {
                   5209:                         $designhash{$item} = $legacyhash{$item};
                   5210:                     }
1.518     albertel 5211:                 }
                   5212:             }
                   5213:         }
1.632     raeburn  5214:     } else {
                   5215:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5216:     }
                   5217:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5218: 				  $cachetime);
                   5219:     return %designhash;
                   5220: }
                   5221: 
1.632     raeburn  5222: sub get_legacy_domconf {
                   5223:     my ($udom) = @_;
                   5224:     my %legacyhash;
                   5225:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5226:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5227:     if (-e $designfile) {
                   5228:         if ( open (my $fh,"<$designfile") ) {
                   5229:             while (my $line = <$fh>) {
                   5230:                 next if ($line =~ /^\#/);
                   5231:                 chomp($line);
                   5232:                 my ($key,$val)=(split(/\=/,$line));
                   5233:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5234:             }
                   5235:             close($fh);
                   5236:         }
                   5237:     }
1.1026    raeburn  5238:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5239:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5240:     }
                   5241:     return %legacyhash;
                   5242: }
                   5243: 
1.63      www      5244: =pod
                   5245: 
1.112     bowersj2 5246: =item * &domainlogo()
1.63      www      5247: 
                   5248: Inputs: $domain (usually will be undef)
                   5249: 
                   5250: Returns: A link to a domain logo, if the domain logo exists.
                   5251: If the domain logo does not exist, a description of the domain.
                   5252: 
                   5253: =cut
1.112     bowersj2 5254: 
1.63      www      5255: ###############################################
                   5256: sub domainlogo {
1.517     raeburn  5257:     my $domain = &determinedomain(shift);
1.518     albertel 5258:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5259:     # See if there is a logo
                   5260:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5261:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5262:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5263: 	    if ($imgsrc =~ m{^/res/}) {
                   5264: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5265: 		&Apache::lonnet::repcopy($local_name);
                   5266: 	    }
                   5267: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5268:         } 
                   5269:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5270:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5271:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5272:     } else {
1.60      matthew  5273:         return '';
1.59      www      5274:     }
                   5275: }
1.63      www      5276: ##############################################
                   5277: 
                   5278: =pod
                   5279: 
1.112     bowersj2 5280: =item * &designparm()
1.63      www      5281: 
                   5282: Inputs: $which parameter; $domain (usually will be undef)
                   5283: 
                   5284: Returns: value of designparamter $which
                   5285: 
                   5286: =cut
1.112     bowersj2 5287: 
1.397     albertel 5288: 
1.400     albertel 5289: ##############################################
1.397     albertel 5290: sub designparm {
                   5291:     my ($which,$domain)=@_;
                   5292:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5293:         return $env{'environment.color.'.$which};
1.96      www      5294:     }
1.63      www      5295:     $domain=&determinedomain($domain);
1.1016    raeburn  5296:     my %domdesign;
                   5297:     unless ($domain eq 'public') {
                   5298:         %domdesign = &get_domainconf($domain);
                   5299:     }
1.520     raeburn  5300:     my $output;
1.517     raeburn  5301:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5302:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5303:     } else {
1.520     raeburn  5304:         $output = $defaultdesign{$which};
                   5305:     }
                   5306:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5307:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5308:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5309:             if ($output =~ m{^/res/}) {
                   5310:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5311:                 &Apache::lonnet::repcopy($local_name);
                   5312:             }
1.520     raeburn  5313:             $output = &lonhttpdurl($output);
                   5314:         }
1.63      www      5315:     }
1.520     raeburn  5316:     return $output;
1.63      www      5317: }
1.59      www      5318: 
1.822     bisitz   5319: ##############################################
                   5320: =pod
                   5321: 
1.832     bisitz   5322: =item * &authorspace()
                   5323: 
1.1028    raeburn  5324: Inputs: $url (usually will be undef).
1.832     bisitz   5325: 
1.1132    raeburn  5326: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5327:          directory being viewed (or for which action is being taken). 
                   5328:          If $url is provided, and begins /priv/<domain>/<uname>
                   5329:          the path will be that portion of the $context argument.
                   5330:          Otherwise the path will be for the author space of the current
                   5331:          user when the current role is author, or for that of the 
                   5332:          co-author/assistant co-author space when the current role 
                   5333:          is co-author or assistant co-author.
1.832     bisitz   5334: 
                   5335: =cut
                   5336: 
                   5337: sub authorspace {
1.1028    raeburn  5338:     my ($url) = @_;
                   5339:     if ($url ne '') {
                   5340:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5341:            return $1;
                   5342:         }
                   5343:     }
1.832     bisitz   5344:     my $caname = '';
1.1024    www      5345:     my $cadom = '';
1.1028    raeburn  5346:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5347:         ($cadom,$caname) =
1.832     bisitz   5348:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5349:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5350:         $caname = $env{'user.name'};
1.1024    www      5351:         $cadom = $env{'user.domain'};
1.832     bisitz   5352:     }
1.1028    raeburn  5353:     if (($caname ne '') && ($cadom ne '')) {
                   5354:         return "/priv/$cadom/$caname/";
                   5355:     }
                   5356:     return;
1.832     bisitz   5357: }
                   5358: 
                   5359: ##############################################
                   5360: =pod
                   5361: 
1.822     bisitz   5362: =item * &head_subbox()
                   5363: 
                   5364: Inputs: $content (contains HTML code with page functions, etc.)
                   5365: 
                   5366: Returns: HTML div with $content
                   5367:          To be included in page header
                   5368: 
                   5369: =cut
                   5370: 
                   5371: sub head_subbox {
                   5372:     my ($content)=@_;
                   5373:     my $output =
1.993     raeburn  5374:         '<div class="LC_head_subbox">'
1.822     bisitz   5375:        .$content
                   5376:        .'</div>'
                   5377: }
                   5378: 
                   5379: ##############################################
                   5380: =pod
                   5381: 
                   5382: =item * &CSTR_pageheader()
                   5383: 
1.1026    raeburn  5384: Input: (optional) filename from which breadcrumb trail is built.
                   5385:        In most cases no input as needed, as $env{'request.filename'}
                   5386:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5387: 
                   5388: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5389:          To be included on Authoring Space pages
1.822     bisitz   5390: 
                   5391: =cut
                   5392: 
                   5393: sub CSTR_pageheader {
1.1026    raeburn  5394:     my ($trailfile) = @_;
                   5395:     if ($trailfile eq '') {
                   5396:         $trailfile = $env{'request.filename'};
                   5397:     }
                   5398: 
                   5399: # this is for resources; directories have customtitle, and crumbs
                   5400: # and select recent are created in lonpubdir.pm
                   5401: 
                   5402:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5403:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5404:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5405:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5406:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5407: 
                   5408:     my $parentpath = '';
                   5409:     my $lastitem = '';
                   5410:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5411:         $parentpath = $1;
                   5412:         $lastitem = $2;
                   5413:     } else {
                   5414:         $lastitem = $thisdisfn;
                   5415:     }
1.921     bisitz   5416: 
                   5417:     my $output =
1.822     bisitz   5418:          '<div>'
                   5419:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1132    raeburn  5420:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5421:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5422:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5423:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5424: 
                   5425:     if ($lastitem) {
                   5426:         $output .=
                   5427:              '<span class="LC_filename">'
                   5428:             .$lastitem
                   5429:             .'</span>';
                   5430:     }
                   5431:     $output .=
                   5432:          '<br />'
1.822     bisitz   5433:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5434:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5435:         .'</form>'
                   5436:         .&Apache::lonmenu::constspaceform()
                   5437:         .'</div>';
1.921     bisitz   5438: 
                   5439:     return $output;
1.822     bisitz   5440: }
                   5441: 
1.60      matthew  5442: ###############################################
                   5443: ###############################################
                   5444: 
                   5445: =pod
                   5446: 
1.112     bowersj2 5447: =back
                   5448: 
1.549     albertel 5449: =head1 HTML Helpers
1.112     bowersj2 5450: 
                   5451: =over 4
                   5452: 
                   5453: =item * &bodytag()
1.60      matthew  5454: 
                   5455: Returns a uniform header for LON-CAPA web pages.
                   5456: 
                   5457: Inputs: 
                   5458: 
1.112     bowersj2 5459: =over 4
                   5460: 
                   5461: =item * $title, A title to be displayed on the page.
                   5462: 
                   5463: =item * $function, the current role (can be undef).
                   5464: 
                   5465: =item * $addentries, extra parameters for the <body> tag.
                   5466: 
                   5467: =item * $bodyonly, if defined, only return the <body> tag.
                   5468: 
                   5469: =item * $domain, if defined, force a given domain.
                   5470: 
                   5471: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5472:             text interface only)
1.60      matthew  5473: 
1.814     bisitz   5474: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5475:                      navigational links
1.317     albertel 5476: 
1.338     albertel 5477: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5478: 
1.460     albertel 5479: =item * $args, optional argument valid values are
                   5480:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 5481:             inherit_jsmath -> when creating popup window in a page,
                   5482:                               should it have jsmath forced on by the
                   5483:                               current page
1.460     albertel 5484: 
1.1096    raeburn  5485: =item * $advtoolsref, optional argument, ref to an array containing
                   5486:             inlineremote items to be added in "Functions" menu below
                   5487:             breadcrumbs.
                   5488: 
1.112     bowersj2 5489: =back
                   5490: 
1.60      matthew  5491: Returns: A uniform header for LON-CAPA web pages.  
                   5492: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5493: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5494: other decorations will be returned.
                   5495: 
                   5496: =cut
                   5497: 
1.54      www      5498: sub bodytag {
1.831     bisitz   5499:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5500:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5501: 
1.954     raeburn  5502:     my $public;
                   5503:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5504:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5505:         $public = 1;
                   5506:     }
1.460     albertel 5507:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5508:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5509: 
1.183     matthew  5510:     $function = &get_users_function() if (!$function);
1.339     albertel 5511:     my $img =    &designparm($function.'.img',$domain);
                   5512:     my $font =   &designparm($function.'.font',$domain);
                   5513:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5514: 
1.803     bisitz   5515:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5516: 		   'bgcolor' => $pgbg,
1.339     albertel 5517: 		   'text'    => $font,
                   5518:                    'alink'   => &designparm($function.'.alink',$domain),
                   5519: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5520: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5521:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5522: 
1.63      www      5523:  # role and realm
1.1178    raeburn  5524:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5525:     if ($realm) {
                   5526:         $realm = '/'.$realm;
                   5527:     }
1.378     raeburn  5528:     if ($role  eq 'ca') {
1.479     albertel 5529:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5530:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5531:     } 
1.55      www      5532: # realm
1.258     albertel 5533:     if ($env{'request.course.id'}) {
1.378     raeburn  5534:         if ($env{'request.role'} !~ /^cr/) {
                   5535:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5536:         }
1.898     raeburn  5537:         if ($env{'request.course.sec'}) {
                   5538:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5539:         }   
1.359     albertel 5540: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5541:     } else {
                   5542:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5543:     }
1.433     albertel 5544: 
1.359     albertel 5545:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5546: 
1.438     albertel 5547:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5548: 
1.101     www      5549: # construct main body tag
1.359     albertel 5550:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5551: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5552: 
1.1131    raeburn  5553:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5554: 
1.1130    raeburn  5555:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5556:         return $bodytag;
1.1130    raeburn  5557:     }
1.359     albertel 5558: 
1.954     raeburn  5559:     if ($public) {
1.433     albertel 5560: 	undef($role);
                   5561:     }
1.359     albertel 5562:     
1.762     bisitz   5563:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5564:     #
                   5565:     # Extra info if you are the DC
                   5566:     my $dc_info = '';
                   5567:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5568:                         $env{'course.'.$env{'request.course.id'}.
                   5569:                                  '.domain'}.'/'})) {
                   5570:         my $cid = $env{'request.course.id'};
1.917     raeburn  5571:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5572:         $dc_info =~ s/\s+$//;
1.359     albertel 5573:     }
                   5574: 
1.898     raeburn  5575:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.853     droeschl 5576: 
1.903     droeschl 5577:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5578: 
                   5579:         #    if ($env{'request.state'} eq 'construct') {
                   5580:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5581:         #    }
                   5582: 
1.1130    raeburn  5583:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5584:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5585: 
1.1130    raeburn  5586:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.359     albertel 5587: 
1.916     droeschl 5588:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5589:              if ($dc_info) {
                   5590:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5591:              }
1.1130    raeburn  5592:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5593:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5594:             return $bodytag;
                   5595:         }
1.894     droeschl 5596: 
1.927     raeburn  5597:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5598:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5599:         }
1.916     droeschl 5600: 
1.1130    raeburn  5601:         $bodytag .= $right;
1.852     droeschl 5602: 
1.917     raeburn  5603:         if ($dc_info) {
                   5604:             $dc_info = &dc_courseid_toggle($dc_info);
                   5605:         }
                   5606:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5607: 
1.1169    raeburn  5608:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5609:         if ($args->{'no_secondary_menu'}) {
                   5610:             return $bodytag;
                   5611:         }
1.1169    raeburn  5612:         #don't show menus for public users
1.954     raeburn  5613:         if (!$public){
1.1154    raeburn  5614:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5615:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5616:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5617:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5618:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5619:                                 $args->{'bread_crumbs'});
1.1096    raeburn  5620:             } elsif ($forcereg) {
                   5621:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5622:                                                             $args->{'group'});
                   5623:             } else {
                   5624:                 $bodytag .= 
                   5625:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5626:                                                         $forcereg,$args->{'group'},
                   5627:                                                         $args->{'bread_crumbs'},
                   5628:                                                         $advtoolsref);
1.920     raeburn  5629:             }
1.903     droeschl 5630:         }else{
                   5631:             # this is to seperate menu from content when there's no secondary
                   5632:             # menu. Especially needed for public accessible ressources.
                   5633:             $bodytag .= '<hr style="clear:both" />';
                   5634:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5635:         }
1.903     droeschl 5636: 
1.235     raeburn  5637:         return $bodytag;
1.182     matthew  5638: }
                   5639: 
1.917     raeburn  5640: sub dc_courseid_toggle {
                   5641:     my ($dc_info) = @_;
1.980     raeburn  5642:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5643:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5644:            &mt('(More ...)').'</a></span>'.
                   5645:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5646: }
                   5647: 
1.330     albertel 5648: sub make_attr_string {
                   5649:     my ($register,$attr_ref) = @_;
                   5650: 
                   5651:     if ($attr_ref && !ref($attr_ref)) {
                   5652: 	die("addentries Must be a hash ref ".
                   5653: 	    join(':',caller(1))." ".
                   5654: 	    join(':',caller(0))." ");
                   5655:     }
                   5656: 
                   5657:     if ($register) {
1.339     albertel 5658: 	my ($on_load,$on_unload);
                   5659: 	foreach my $key (keys(%{$attr_ref})) {
                   5660: 	    if      (lc($key) eq 'onload') {
                   5661: 		$on_load.=$attr_ref->{$key}.';';
                   5662: 		delete($attr_ref->{$key});
                   5663: 
                   5664: 	    } elsif (lc($key) eq 'onunload') {
                   5665: 		$on_unload.=$attr_ref->{$key}.';';
                   5666: 		delete($attr_ref->{$key});
                   5667: 	    }
                   5668: 	}
1.953     droeschl 5669: 	$attr_ref->{'onload'}  = $on_load;
                   5670: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 5671:     }
1.339     albertel 5672: 
1.330     albertel 5673:     my $attr_string;
1.1159    raeburn  5674:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5675: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5676:     }
                   5677:     return $attr_string;
                   5678: }
                   5679: 
                   5680: 
1.182     matthew  5681: ###############################################
1.251     albertel 5682: ###############################################
                   5683: 
                   5684: =pod
                   5685: 
                   5686: =item * &endbodytag()
                   5687: 
                   5688: Returns a uniform footer for LON-CAPA web pages.
                   5689: 
1.635     raeburn  5690: Inputs: 1 - optional reference to an args hash
                   5691: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5692: a 'Continue' link is not displayed if the page contains an
                   5693: internal redirect in the <head></head> section,
                   5694: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5695: 
                   5696: =cut
                   5697: 
                   5698: sub endbodytag {
1.635     raeburn  5699:     my ($args) = @_;
1.1080    raeburn  5700:     my $endbodytag;
                   5701:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5702:         $endbodytag='</body>';
                   5703:     }
1.269     albertel 5704:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5705:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5706:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5707: 	    $endbodytag=
                   5708: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5709: 	        &mt('Continue').'</a>'.
                   5710: 	        $endbodytag;
                   5711:         }
1.315     albertel 5712:     }
1.251     albertel 5713:     return $endbodytag;
                   5714: }
                   5715: 
1.352     albertel 5716: =pod
                   5717: 
                   5718: =item * &standard_css()
                   5719: 
                   5720: Returns a style sheet
                   5721: 
                   5722: Inputs: (all optional)
                   5723:             domain         -> force to color decorate a page for a specific
                   5724:                                domain
                   5725:             function       -> force usage of a specific rolish color scheme
                   5726:             bgcolor        -> override the default page bgcolor
                   5727: 
                   5728: =cut
                   5729: 
1.343     albertel 5730: sub standard_css {
1.345     albertel 5731:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5732:     $function  = &get_users_function() if (!$function);
                   5733:     my $img    = &designparm($function.'.img',   $domain);
                   5734:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5735:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5736:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5737: #second colour for later usage
1.345     albertel 5738:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5739:     my $pgbg_or_bgcolor =
                   5740: 	         $bgcolor ||
1.352     albertel 5741: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5742:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5743:     my $alink  = &designparm($function.'.alink', $domain);
                   5744:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5745:     my $link   = &designparm($function.'.link',  $domain);
                   5746: 
1.602     albertel 5747:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5748:     my $mono                 = 'monospace';
1.850     bisitz   5749:     my $data_table_head      = $sidebg;
                   5750:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5751:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5752:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5753:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5754:     my $mail_new             = '#FFBB77';
                   5755:     my $mail_new_hover       = '#DD9955';
                   5756:     my $mail_read            = '#BBBB77';
                   5757:     my $mail_read_hover      = '#999944';
                   5758:     my $mail_replied         = '#AAAA88';
                   5759:     my $mail_replied_hover   = '#888855';
                   5760:     my $mail_other           = '#99BBBB';
                   5761:     my $mail_other_hover     = '#669999';
1.391     albertel 5762:     my $table_header         = '#DDDDDD';
1.489     raeburn  5763:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5764:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5765:     my $button_hover         = '#BF2317';
1.392     albertel 5766: 
1.608     albertel 5767:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5768:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5769:                                              : '0 3px 0 4px';
1.448     albertel 5770: 
1.523     albertel 5771: 
1.343     albertel 5772:     return <<END;
1.947     droeschl 5773: 
                   5774: /* needed for iframe to allow 100% height in FF */
                   5775: body, html { 
                   5776:     margin: 0;
                   5777:     padding: 0 0.5%;
                   5778:     height: 99%; /* to avoid scrollbars */
                   5779: }
                   5780: 
1.795     www      5781: body {
1.911     bisitz   5782:   font-family: $sans;
                   5783:   line-height:130%;
                   5784:   font-size:0.83em;
                   5785:   color:$font;
1.795     www      5786: }
                   5787: 
1.959     onken    5788: a:focus,
                   5789: a:focus img {
1.795     www      5790:   color: red;
                   5791: }
1.698     harmsja  5792: 
1.911     bisitz   5793: form, .inline {
                   5794:   display: inline;
1.795     www      5795: }
1.721     harmsja  5796: 
1.795     www      5797: .LC_right {
1.911     bisitz   5798:   text-align:right;
1.795     www      5799: }
                   5800: 
                   5801: .LC_middle {
1.911     bisitz   5802:   vertical-align:middle;
1.795     www      5803: }
1.721     harmsja  5804: 
1.1130    raeburn  5805: .LC_floatleft {
                   5806:   float: left;
                   5807: }
                   5808: 
                   5809: .LC_floatright {
                   5810:   float: right;
                   5811: }
                   5812: 
1.911     bisitz   5813: .LC_400Box {
                   5814:   width:400px;
                   5815: }
1.721     harmsja  5816: 
1.947     droeschl 5817: .LC_iframecontainer {
                   5818:     width: 98%;
                   5819:     margin: 0;
                   5820:     position: fixed;
                   5821:     top: 8.5em;
                   5822:     bottom: 0;
                   5823: }
                   5824: 
                   5825: .LC_iframecontainer iframe{
                   5826:     border: none;
                   5827:     width: 100%;
                   5828:     height: 100%;
                   5829: }
                   5830: 
1.778     bisitz   5831: .LC_filename {
                   5832:   font-family: $mono;
                   5833:   white-space:pre;
1.921     bisitz   5834:   font-size: 120%;
1.778     bisitz   5835: }
                   5836: 
                   5837: .LC_fileicon {
                   5838:   border: none;
                   5839:   height: 1.3em;
                   5840:   vertical-align: text-bottom;
                   5841:   margin-right: 0.3em;
                   5842:   text-decoration:none;
                   5843: }
                   5844: 
1.1008    www      5845: .LC_setting {
                   5846:   text-decoration:underline;
                   5847: }
                   5848: 
1.350     albertel 5849: .LC_error {
                   5850:   color: red;
                   5851: }
1.795     www      5852: 
1.1097    bisitz   5853: .LC_warning {
                   5854:   color: darkorange;
                   5855: }
                   5856: 
1.457     albertel 5857: .LC_diff_removed {
1.733     bisitz   5858:   color: red;
1.394     albertel 5859: }
1.532     albertel 5860: 
                   5861: .LC_info,
1.457     albertel 5862: .LC_success,
                   5863: .LC_diff_added {
1.350     albertel 5864:   color: green;
                   5865: }
1.795     www      5866: 
1.802     bisitz   5867: div.LC_confirm_box {
                   5868:   background-color: #FAFAFA;
                   5869:   border: 1px solid $lg_border_color;
                   5870:   margin-right: 0;
                   5871:   padding: 5px;
                   5872: }
                   5873: 
                   5874: div.LC_confirm_box .LC_error img,
                   5875: div.LC_confirm_box .LC_success img {
                   5876:   vertical-align: middle;
                   5877: }
                   5878: 
1.440     albertel 5879: .LC_icon {
1.771     droeschl 5880:   border: none;
1.790     droeschl 5881:   vertical-align: middle;
1.771     droeschl 5882: }
                   5883: 
1.543     albertel 5884: .LC_docs_spacer {
                   5885:   width: 25px;
                   5886:   height: 1px;
1.771     droeschl 5887:   border: none;
1.543     albertel 5888: }
1.346     albertel 5889: 
1.532     albertel 5890: .LC_internal_info {
1.735     bisitz   5891:   color: #999999;
1.532     albertel 5892: }
                   5893: 
1.794     www      5894: .LC_discussion {
1.1050    www      5895:   background: $data_table_dark;
1.911     bisitz   5896:   border: 1px solid black;
                   5897:   margin: 2px;
1.794     www      5898: }
                   5899: 
                   5900: .LC_disc_action_left {
1.1050    www      5901:   background: $sidebg;
1.911     bisitz   5902:   text-align: left;
1.1050    www      5903:   padding: 4px;
                   5904:   margin: 2px;
1.794     www      5905: }
                   5906: 
                   5907: .LC_disc_action_right {
1.1050    www      5908:   background: $sidebg;
1.911     bisitz   5909:   text-align: right;
1.1050    www      5910:   padding: 4px;
                   5911:   margin: 2px;
1.794     www      5912: }
                   5913: 
                   5914: .LC_disc_new_item {
1.911     bisitz   5915:   background: white;
                   5916:   border: 2px solid red;
1.1050    www      5917:   margin: 4px;
                   5918:   padding: 4px;
1.794     www      5919: }
                   5920: 
                   5921: .LC_disc_old_item {
1.911     bisitz   5922:   background: white;
1.1050    www      5923:   margin: 4px;
                   5924:   padding: 4px;
1.794     www      5925: }
                   5926: 
1.458     albertel 5927: table.LC_pastsubmission {
                   5928:   border: 1px solid black;
                   5929:   margin: 2px;
                   5930: }
                   5931: 
1.924     bisitz   5932: table#LC_menubuttons {
1.345     albertel 5933:   width: 100%;
                   5934:   background: $pgbg;
1.392     albertel 5935:   border: 2px;
1.402     albertel 5936:   border-collapse: separate;
1.803     bisitz   5937:   padding: 0;
1.345     albertel 5938: }
1.392     albertel 5939: 
1.801     tempelho 5940: table#LC_title_bar a {
                   5941:   color: $fontmenu;
                   5942: }
1.836     bisitz   5943: 
1.807     droeschl 5944: table#LC_title_bar {
1.819     tempelho 5945:   clear: both;
1.836     bisitz   5946:   display: none;
1.807     droeschl 5947: }
                   5948: 
1.795     www      5949: table#LC_title_bar,
1.933     droeschl 5950: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5951: table#LC_title_bar.LC_with_remote {
1.359     albertel 5952:   width: 100%;
1.392     albertel 5953:   border-color: $pgbg;
                   5954:   border-style: solid;
                   5955:   border-width: $border;
1.379     albertel 5956:   background: $pgbg;
1.801     tempelho 5957:   color: $fontmenu;
1.392     albertel 5958:   border-collapse: collapse;
1.803     bisitz   5959:   padding: 0;
1.819     tempelho 5960:   margin: 0;
1.359     albertel 5961: }
1.795     www      5962: 
1.933     droeschl 5963: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5964:     margin: 0;
                   5965:     padding: 0;
1.933     droeschl 5966:     position: relative;
                   5967:     list-style: none;
1.913     droeschl 5968: }
1.933     droeschl 5969: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5970:     display: inline;
                   5971: }
1.933     droeschl 5972: 
                   5973: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5974:     padding: 0;
1.933     droeschl 5975:     margin: 0;
                   5976:     float: left;
1.913     droeschl 5977: }
1.933     droeschl 5978: .LC_breadcrumb_tools_tools {
                   5979:     padding: 0;
                   5980:     margin: 0;
1.913     droeschl 5981:     float: right;
                   5982: }
                   5983: 
1.359     albertel 5984: table#LC_title_bar td {
                   5985:   background: $tabbg;
                   5986: }
1.795     www      5987: 
1.911     bisitz   5988: table#LC_menubuttons img {
1.803     bisitz   5989:   border: none;
1.346     albertel 5990: }
1.795     www      5991: 
1.842     droeschl 5992: .LC_breadcrumbs_component {
1.911     bisitz   5993:   float: right;
                   5994:   margin: 0 1em;
1.357     albertel 5995: }
1.842     droeschl 5996: .LC_breadcrumbs_component img {
1.911     bisitz   5997:   vertical-align: middle;
1.777     tempelho 5998: }
1.795     www      5999: 
1.383     albertel 6000: td.LC_table_cell_checkbox {
                   6001:   text-align: center;
                   6002: }
1.795     www      6003: 
                   6004: .LC_fontsize_small {
1.911     bisitz   6005:   font-size: 70%;
1.705     tempelho 6006: }
                   6007: 
1.844     bisitz   6008: #LC_breadcrumbs {
1.911     bisitz   6009:   clear:both;
                   6010:   background: $sidebg;
                   6011:   border-bottom: 1px solid $lg_border_color;
                   6012:   line-height: 2.5em;
1.933     droeschl 6013:   overflow: hidden;
1.911     bisitz   6014:   margin: 0;
                   6015:   padding: 0;
1.995     raeburn  6016:   text-align: left;
1.819     tempelho 6017: }
1.862     bisitz   6018: 
1.1098    bisitz   6019: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6020:   clear:both;
                   6021:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6022:   border: 1px solid $sidebg;
1.1098    bisitz   6023:   margin: 0 0 10px 0;
1.966     bisitz   6024:   padding: 3px;
1.995     raeburn  6025:   text-align: left;
1.822     bisitz   6026: }
                   6027: 
1.795     www      6028: .LC_fontsize_medium {
1.911     bisitz   6029:   font-size: 85%;
1.705     tempelho 6030: }
                   6031: 
1.795     www      6032: .LC_fontsize_large {
1.911     bisitz   6033:   font-size: 120%;
1.705     tempelho 6034: }
                   6035: 
1.346     albertel 6036: .LC_menubuttons_inline_text {
                   6037:   color: $font;
1.698     harmsja  6038:   font-size: 90%;
1.701     harmsja  6039:   padding-left:3px;
1.346     albertel 6040: }
                   6041: 
1.934     droeschl 6042: .LC_menubuttons_inline_text img{
                   6043:   vertical-align: middle;
                   6044: }
                   6045: 
1.1051    www      6046: li.LC_menubuttons_inline_text img {
1.951     onken    6047:   cursor:pointer;
1.1002    droeschl 6048:   text-decoration: none;
1.951     onken    6049: }
                   6050: 
1.526     www      6051: .LC_menubuttons_link {
                   6052:   text-decoration: none;
                   6053: }
1.795     www      6054: 
1.522     albertel 6055: .LC_menubuttons_category {
1.521     www      6056:   color: $font;
1.526     www      6057:   background: $pgbg;
1.521     www      6058:   font-size: larger;
                   6059:   font-weight: bold;
                   6060: }
                   6061: 
1.346     albertel 6062: td.LC_menubuttons_text {
1.911     bisitz   6063:   color: $font;
1.346     albertel 6064: }
1.706     harmsja  6065: 
1.346     albertel 6066: .LC_current_location {
                   6067:   background: $tabbg;
                   6068: }
1.795     www      6069: 
1.938     bisitz   6070: table.LC_data_table {
1.347     albertel 6071:   border: 1px solid #000000;
1.402     albertel 6072:   border-collapse: separate;
1.426     albertel 6073:   border-spacing: 1px;
1.610     albertel 6074:   background: $pgbg;
1.347     albertel 6075: }
1.795     www      6076: 
1.422     albertel 6077: .LC_data_table_dense {
                   6078:   font-size: small;
                   6079: }
1.795     www      6080: 
1.507     raeburn  6081: table.LC_nested_outer {
                   6082:   border: 1px solid #000000;
1.589     raeburn  6083:   border-collapse: collapse;
1.803     bisitz   6084:   border-spacing: 0;
1.507     raeburn  6085:   width: 100%;
                   6086: }
1.795     www      6087: 
1.879     raeburn  6088: table.LC_innerpickbox,
1.507     raeburn  6089: table.LC_nested {
1.803     bisitz   6090:   border: none;
1.589     raeburn  6091:   border-collapse: collapse;
1.803     bisitz   6092:   border-spacing: 0;
1.507     raeburn  6093:   width: 100%;
                   6094: }
1.795     www      6095: 
1.911     bisitz   6096: table.LC_data_table tr th,
                   6097: table.LC_calendar tr th,
1.879     raeburn  6098: table.LC_prior_tries tr th,
                   6099: table.LC_innerpickbox tr th {
1.349     albertel 6100:   font-weight: bold;
                   6101:   background-color: $data_table_head;
1.801     tempelho 6102:   color:$fontmenu;
1.701     harmsja  6103:   font-size:90%;
1.347     albertel 6104: }
1.795     www      6105: 
1.879     raeburn  6106: table.LC_innerpickbox tr th,
                   6107: table.LC_innerpickbox tr td {
                   6108:   vertical-align: top;
                   6109: }
                   6110: 
1.711     raeburn  6111: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6112:   background-color: #CCCCCC;
1.711     raeburn  6113:   font-weight: bold;
                   6114:   text-align: left;
                   6115: }
1.795     www      6116: 
1.912     bisitz   6117: table.LC_data_table tr.LC_odd_row > td {
                   6118:   background-color: $data_table_light;
                   6119:   padding: 2px;
                   6120:   vertical-align: top;
                   6121: }
                   6122: 
1.809     bisitz   6123: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6124:   background-color: $data_table_light;
1.912     bisitz   6125:   vertical-align: top;
                   6126: }
                   6127: 
                   6128: table.LC_data_table tr.LC_even_row > td {
                   6129:   background-color: $data_table_dark;
1.425     albertel 6130:   padding: 2px;
1.900     bisitz   6131:   vertical-align: top;
1.347     albertel 6132: }
1.795     www      6133: 
1.809     bisitz   6134: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6135:   background-color: $data_table_dark;
1.900     bisitz   6136:   vertical-align: top;
1.347     albertel 6137: }
1.795     www      6138: 
1.425     albertel 6139: table.LC_data_table tr.LC_data_table_highlight td {
                   6140:   background-color: $data_table_darker;
                   6141: }
1.795     www      6142: 
1.639     raeburn  6143: table.LC_data_table tr td.LC_leftcol_header {
                   6144:   background-color: $data_table_head;
                   6145:   font-weight: bold;
                   6146: }
1.795     www      6147: 
1.451     albertel 6148: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6149: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6150:   font-weight: bold;
                   6151:   font-style: italic;
                   6152:   text-align: center;
                   6153:   padding: 8px;
1.347     albertel 6154: }
1.795     www      6155: 
1.1114    raeburn  6156: table.LC_data_table tr.LC_empty_row td,
                   6157: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6158:   background-color: $sidebg;
                   6159: }
                   6160: 
                   6161: table.LC_nested tr.LC_empty_row td {
                   6162:   background-color: #FFFFFF;
                   6163: }
                   6164: 
1.890     droeschl 6165: table.LC_caption {
                   6166: }
                   6167: 
1.507     raeburn  6168: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6169:   padding: 4ex
                   6170: }
1.795     www      6171: 
1.507     raeburn  6172: table.LC_nested_outer tr th {
                   6173:   font-weight: bold;
1.801     tempelho 6174:   color:$fontmenu;
1.507     raeburn  6175:   background-color: $data_table_head;
1.701     harmsja  6176:   font-size: small;
1.507     raeburn  6177:   border-bottom: 1px solid #000000;
                   6178: }
1.795     www      6179: 
1.507     raeburn  6180: table.LC_nested_outer tr td.LC_subheader {
                   6181:   background-color: $data_table_head;
                   6182:   font-weight: bold;
                   6183:   font-size: small;
                   6184:   border-bottom: 1px solid #000000;
                   6185:   text-align: right;
1.451     albertel 6186: }
1.795     www      6187: 
1.507     raeburn  6188: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6189:   background-color: #CCCCCC;
1.451     albertel 6190:   font-weight: bold;
                   6191:   font-size: small;
1.507     raeburn  6192:   text-align: center;
                   6193: }
1.795     www      6194: 
1.589     raeburn  6195: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6196: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6197:   text-align: left;
1.451     albertel 6198: }
1.795     www      6199: 
1.507     raeburn  6200: table.LC_nested td {
1.735     bisitz   6201:   background-color: #FFFFFF;
1.451     albertel 6202:   font-size: small;
1.507     raeburn  6203: }
1.795     www      6204: 
1.507     raeburn  6205: table.LC_nested_outer tr th.LC_right_item,
                   6206: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6207: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6208: table.LC_nested tr td.LC_right_item {
1.451     albertel 6209:   text-align: right;
                   6210: }
                   6211: 
1.507     raeburn  6212: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6213:   background-color: #EEEEEE;
1.451     albertel 6214: }
                   6215: 
1.473     raeburn  6216: table.LC_createuser {
                   6217: }
                   6218: 
                   6219: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6220:   font-size: small;
1.473     raeburn  6221: }
                   6222: 
                   6223: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6224:   background-color: #CCCCCC;
1.473     raeburn  6225:   font-weight: bold;
                   6226:   text-align: center;
                   6227: }
                   6228: 
1.349     albertel 6229: table.LC_calendar {
                   6230:   border: 1px solid #000000;
                   6231:   border-collapse: collapse;
1.917     raeburn  6232:   width: 98%;
1.349     albertel 6233: }
1.795     www      6234: 
1.349     albertel 6235: table.LC_calendar_pickdate {
                   6236:   font-size: xx-small;
                   6237: }
1.795     www      6238: 
1.349     albertel 6239: table.LC_calendar tr td {
                   6240:   border: 1px solid #000000;
                   6241:   vertical-align: top;
1.917     raeburn  6242:   width: 14%;
1.349     albertel 6243: }
1.795     www      6244: 
1.349     albertel 6245: table.LC_calendar tr td.LC_calendar_day_empty {
                   6246:   background-color: $data_table_dark;
                   6247: }
1.795     www      6248: 
1.779     bisitz   6249: table.LC_calendar tr td.LC_calendar_day_current {
                   6250:   background-color: $data_table_highlight;
1.777     tempelho 6251: }
1.795     www      6252: 
1.938     bisitz   6253: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6254:   background-color: $mail_new;
                   6255: }
1.795     www      6256: 
1.938     bisitz   6257: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6258:   background-color: $mail_new_hover;
                   6259: }
1.795     www      6260: 
1.938     bisitz   6261: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6262:   background-color: $mail_read;
                   6263: }
1.795     www      6264: 
1.938     bisitz   6265: /*
                   6266: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6267:   background-color: $mail_read_hover;
                   6268: }
1.938     bisitz   6269: */
1.795     www      6270: 
1.938     bisitz   6271: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6272:   background-color: $mail_replied;
                   6273: }
1.795     www      6274: 
1.938     bisitz   6275: /*
                   6276: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6277:   background-color: $mail_replied_hover;
                   6278: }
1.938     bisitz   6279: */
1.795     www      6280: 
1.938     bisitz   6281: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6282:   background-color: $mail_other;
                   6283: }
1.795     www      6284: 
1.938     bisitz   6285: /*
                   6286: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6287:   background-color: $mail_other_hover;
                   6288: }
1.938     bisitz   6289: */
1.494     raeburn  6290: 
1.777     tempelho 6291: table.LC_data_table tr > td.LC_browser_file,
                   6292: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6293:   background: #AAEE77;
1.389     albertel 6294: }
1.795     www      6295: 
1.777     tempelho 6296: table.LC_data_table tr > td.LC_browser_file_locked,
                   6297: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6298:   background: #FFAA99;
1.387     albertel 6299: }
1.795     www      6300: 
1.777     tempelho 6301: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6302:   background: #888888;
1.779     bisitz   6303: }
1.795     www      6304: 
1.777     tempelho 6305: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6306: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6307:   background: #F8F866;
1.777     tempelho 6308: }
1.795     www      6309: 
1.696     bisitz   6310: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6311:   background: #E0E8FF;
1.387     albertel 6312: }
1.696     bisitz   6313: 
1.707     bisitz   6314: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6315:   /* background: #77FF77; */
1.707     bisitz   6316: }
1.795     www      6317: 
1.707     bisitz   6318: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6319:   border-right: 8px solid #FFFF77;
1.707     bisitz   6320: }
1.795     www      6321: 
1.707     bisitz   6322: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6323:   border-right: 8px solid #FFAA77;
1.707     bisitz   6324: }
1.795     www      6325: 
1.707     bisitz   6326: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6327:   border-right: 8px solid #FF7777;
1.707     bisitz   6328: }
1.795     www      6329: 
1.707     bisitz   6330: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6331:   border-right: 8px solid #AAFF77;
1.707     bisitz   6332: }
1.795     www      6333: 
1.707     bisitz   6334: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6335:   border-right: 8px solid #11CC55;
1.707     bisitz   6336: }
                   6337: 
1.388     albertel 6338: span.LC_current_location {
1.701     harmsja  6339:   font-size:larger;
1.388     albertel 6340:   background: $pgbg;
                   6341: }
1.387     albertel 6342: 
1.1029    www      6343: span.LC_current_nav_location {
                   6344:   font-weight:bold;
                   6345:   background: $sidebg;
                   6346: }
                   6347: 
1.395     albertel 6348: span.LC_parm_menu_item {
                   6349:   font-size: larger;
                   6350: }
1.795     www      6351: 
1.395     albertel 6352: span.LC_parm_scope_all {
                   6353:   color: red;
                   6354: }
1.795     www      6355: 
1.395     albertel 6356: span.LC_parm_scope_folder {
                   6357:   color: green;
                   6358: }
1.795     www      6359: 
1.395     albertel 6360: span.LC_parm_scope_resource {
                   6361:   color: orange;
                   6362: }
1.795     www      6363: 
1.395     albertel 6364: span.LC_parm_part {
                   6365:   color: blue;
                   6366: }
1.795     www      6367: 
1.911     bisitz   6368: span.LC_parm_folder,
                   6369: span.LC_parm_symb {
1.395     albertel 6370:   font-size: x-small;
                   6371:   font-family: $mono;
                   6372:   color: #AAAAAA;
                   6373: }
                   6374: 
1.977     bisitz   6375: ul.LC_parm_parmlist li {
                   6376:   display: inline-block;
                   6377:   padding: 0.3em 0.8em;
                   6378:   vertical-align: top;
                   6379:   width: 150px;
                   6380:   border-top:1px solid $lg_border_color;
                   6381: }
                   6382: 
1.795     www      6383: td.LC_parm_overview_level_menu,
                   6384: td.LC_parm_overview_map_menu,
                   6385: td.LC_parm_overview_parm_selectors,
                   6386: td.LC_parm_overview_restrictions  {
1.396     albertel 6387:   border: 1px solid black;
                   6388:   border-collapse: collapse;
                   6389: }
1.795     www      6390: 
1.396     albertel 6391: table.LC_parm_overview_restrictions td {
                   6392:   border-width: 1px 4px 1px 4px;
                   6393:   border-style: solid;
                   6394:   border-color: $pgbg;
                   6395:   text-align: center;
                   6396: }
1.795     www      6397: 
1.396     albertel 6398: table.LC_parm_overview_restrictions th {
                   6399:   background: $tabbg;
                   6400:   border-width: 1px 4px 1px 4px;
                   6401:   border-style: solid;
                   6402:   border-color: $pgbg;
                   6403: }
1.795     www      6404: 
1.398     albertel 6405: table#LC_helpmenu {
1.803     bisitz   6406:   border: none;
1.398     albertel 6407:   height: 55px;
1.803     bisitz   6408:   border-spacing: 0;
1.398     albertel 6409: }
                   6410: 
                   6411: table#LC_helpmenu fieldset legend {
                   6412:   font-size: larger;
                   6413: }
1.795     www      6414: 
1.397     albertel 6415: table#LC_helpmenu_links {
                   6416:   width: 100%;
                   6417:   border: 1px solid black;
                   6418:   background: $pgbg;
1.803     bisitz   6419:   padding: 0;
1.397     albertel 6420:   border-spacing: 1px;
                   6421: }
1.795     www      6422: 
1.397     albertel 6423: table#LC_helpmenu_links tr td {
                   6424:   padding: 1px;
                   6425:   background: $tabbg;
1.399     albertel 6426:   text-align: center;
                   6427:   font-weight: bold;
1.397     albertel 6428: }
1.396     albertel 6429: 
1.795     www      6430: table#LC_helpmenu_links a:link,
                   6431: table#LC_helpmenu_links a:visited,
1.397     albertel 6432: table#LC_helpmenu_links a:active {
                   6433:   text-decoration: none;
                   6434:   color: $font;
                   6435: }
1.795     www      6436: 
1.397     albertel 6437: table#LC_helpmenu_links a:hover {
                   6438:   text-decoration: underline;
                   6439:   color: $vlink;
                   6440: }
1.396     albertel 6441: 
1.417     albertel 6442: .LC_chrt_popup_exists {
                   6443:   border: 1px solid #339933;
                   6444:   margin: -1px;
                   6445: }
1.795     www      6446: 
1.417     albertel 6447: .LC_chrt_popup_up {
                   6448:   border: 1px solid yellow;
                   6449:   margin: -1px;
                   6450: }
1.795     www      6451: 
1.417     albertel 6452: .LC_chrt_popup {
                   6453:   border: 1px solid #8888FF;
                   6454:   background: #CCCCFF;
                   6455: }
1.795     www      6456: 
1.421     albertel 6457: table.LC_pick_box {
                   6458:   border-collapse: separate;
                   6459:   background: white;
                   6460:   border: 1px solid black;
                   6461:   border-spacing: 1px;
                   6462: }
1.795     www      6463: 
1.421     albertel 6464: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6465:   background: $sidebg;
1.421     albertel 6466:   font-weight: bold;
1.900     bisitz   6467:   text-align: left;
1.740     bisitz   6468:   vertical-align: top;
1.421     albertel 6469:   width: 184px;
                   6470:   padding: 8px;
                   6471: }
1.795     www      6472: 
1.579     raeburn  6473: table.LC_pick_box td.LC_pick_box_value {
                   6474:   text-align: left;
                   6475:   padding: 8px;
                   6476: }
1.795     www      6477: 
1.579     raeburn  6478: table.LC_pick_box td.LC_pick_box_select {
                   6479:   text-align: left;
                   6480:   padding: 8px;
                   6481: }
1.795     www      6482: 
1.424     albertel 6483: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6484:   padding: 0;
1.421     albertel 6485:   height: 1px;
                   6486:   background: black;
                   6487: }
1.795     www      6488: 
1.421     albertel 6489: table.LC_pick_box td.LC_pick_box_submit {
                   6490:   text-align: right;
                   6491: }
1.795     www      6492: 
1.579     raeburn  6493: table.LC_pick_box td.LC_evenrow_value {
                   6494:   text-align: left;
                   6495:   padding: 8px;
                   6496:   background-color: $data_table_light;
                   6497: }
1.795     www      6498: 
1.579     raeburn  6499: table.LC_pick_box td.LC_oddrow_value {
                   6500:   text-align: left;
                   6501:   padding: 8px;
                   6502:   background-color: $data_table_light;
                   6503: }
1.795     www      6504: 
1.579     raeburn  6505: span.LC_helpform_receipt_cat {
                   6506:   font-weight: bold;
                   6507: }
1.795     www      6508: 
1.424     albertel 6509: table.LC_group_priv_box {
                   6510:   background: white;
                   6511:   border: 1px solid black;
                   6512:   border-spacing: 1px;
                   6513: }
1.795     www      6514: 
1.424     albertel 6515: table.LC_group_priv_box td.LC_pick_box_title {
                   6516:   background: $tabbg;
                   6517:   font-weight: bold;
                   6518:   text-align: right;
                   6519:   width: 184px;
                   6520: }
1.795     www      6521: 
1.424     albertel 6522: table.LC_group_priv_box td.LC_groups_fixed {
                   6523:   background: $data_table_light;
                   6524:   text-align: center;
                   6525: }
1.795     www      6526: 
1.424     albertel 6527: table.LC_group_priv_box td.LC_groups_optional {
                   6528:   background: $data_table_dark;
                   6529:   text-align: center;
                   6530: }
1.795     www      6531: 
1.424     albertel 6532: table.LC_group_priv_box td.LC_groups_functionality {
                   6533:   background: $data_table_darker;
                   6534:   text-align: center;
                   6535:   font-weight: bold;
                   6536: }
1.795     www      6537: 
1.424     albertel 6538: table.LC_group_priv td {
                   6539:   text-align: left;
1.803     bisitz   6540:   padding: 0;
1.424     albertel 6541: }
                   6542: 
                   6543: .LC_navbuttons {
                   6544:   margin: 2ex 0ex 2ex 0ex;
                   6545: }
1.795     www      6546: 
1.423     albertel 6547: .LC_topic_bar {
                   6548:   font-weight: bold;
                   6549:   background: $tabbg;
1.918     wenzelju 6550:   margin: 1em 0em 1em 2em;
1.805     bisitz   6551:   padding: 3px;
1.918     wenzelju 6552:   font-size: 1.2em;
1.423     albertel 6553: }
1.795     www      6554: 
1.423     albertel 6555: .LC_topic_bar span {
1.918     wenzelju 6556:   left: 0.5em;
                   6557:   position: absolute;
1.423     albertel 6558:   vertical-align: middle;
1.918     wenzelju 6559:   font-size: 1.2em;
1.423     albertel 6560: }
1.795     www      6561: 
1.423     albertel 6562: table.LC_course_group_status {
                   6563:   margin: 20px;
                   6564: }
1.795     www      6565: 
1.423     albertel 6566: table.LC_status_selector td {
                   6567:   vertical-align: top;
                   6568:   text-align: center;
1.424     albertel 6569:   padding: 4px;
                   6570: }
1.795     www      6571: 
1.599     albertel 6572: div.LC_feedback_link {
1.616     albertel 6573:   clear: both;
1.829     kalberla 6574:   background: $sidebg;
1.779     bisitz   6575:   width: 100%;
1.829     kalberla 6576:   padding-bottom: 10px;
                   6577:   border: 1px $tabbg solid;
1.833     kalberla 6578:   height: 22px;
                   6579:   line-height: 22px;
                   6580:   padding-top: 5px;
                   6581: }
                   6582: 
                   6583: div.LC_feedback_link img {
                   6584:   height: 22px;
1.867     kalberla 6585:   vertical-align:middle;
1.829     kalberla 6586: }
                   6587: 
1.911     bisitz   6588: div.LC_feedback_link a {
1.829     kalberla 6589:   text-decoration: none;
1.489     raeburn  6590: }
1.795     www      6591: 
1.867     kalberla 6592: div.LC_comblock {
1.911     bisitz   6593:   display:inline;
1.867     kalberla 6594:   color:$font;
                   6595:   font-size:90%;
                   6596: }
                   6597: 
                   6598: div.LC_feedback_link div.LC_comblock {
                   6599:   padding-left:5px;
                   6600: }
                   6601: 
                   6602: div.LC_feedback_link div.LC_comblock a {
                   6603:   color:$font;
                   6604: }
                   6605: 
1.489     raeburn  6606: span.LC_feedback_link {
1.858     bisitz   6607:   /* background: $feedback_link_bg; */
1.599     albertel 6608:   font-size: larger;
                   6609: }
1.795     www      6610: 
1.599     albertel 6611: span.LC_message_link {
1.858     bisitz   6612:   /* background: $feedback_link_bg; */
1.599     albertel 6613:   font-size: larger;
                   6614:   position: absolute;
                   6615:   right: 1em;
1.489     raeburn  6616: }
1.421     albertel 6617: 
1.515     albertel 6618: table.LC_prior_tries {
1.524     albertel 6619:   border: 1px solid #000000;
                   6620:   border-collapse: separate;
                   6621:   border-spacing: 1px;
1.515     albertel 6622: }
1.523     albertel 6623: 
1.515     albertel 6624: table.LC_prior_tries td {
1.524     albertel 6625:   padding: 2px;
1.515     albertel 6626: }
1.523     albertel 6627: 
                   6628: .LC_answer_correct {
1.795     www      6629:   background: lightgreen;
                   6630:   color: darkgreen;
                   6631:   padding: 6px;
1.523     albertel 6632: }
1.795     www      6633: 
1.523     albertel 6634: .LC_answer_charged_try {
1.797     www      6635:   background: #FFAAAA;
1.795     www      6636:   color: darkred;
                   6637:   padding: 6px;
1.523     albertel 6638: }
1.795     www      6639: 
1.779     bisitz   6640: .LC_answer_not_charged_try,
1.523     albertel 6641: .LC_answer_no_grade,
                   6642: .LC_answer_late {
1.795     www      6643:   background: lightyellow;
1.523     albertel 6644:   color: black;
1.795     www      6645:   padding: 6px;
1.523     albertel 6646: }
1.795     www      6647: 
1.523     albertel 6648: .LC_answer_previous {
1.795     www      6649:   background: lightblue;
                   6650:   color: darkblue;
                   6651:   padding: 6px;
1.523     albertel 6652: }
1.795     www      6653: 
1.779     bisitz   6654: .LC_answer_no_message {
1.777     tempelho 6655:   background: #FFFFFF;
                   6656:   color: black;
1.795     www      6657:   padding: 6px;
1.779     bisitz   6658: }
1.795     www      6659: 
1.779     bisitz   6660: .LC_answer_unknown {
                   6661:   background: orange;
                   6662:   color: black;
1.795     www      6663:   padding: 6px;
1.777     tempelho 6664: }
1.795     www      6665: 
1.529     albertel 6666: span.LC_prior_numerical,
                   6667: span.LC_prior_string,
                   6668: span.LC_prior_custom,
                   6669: span.LC_prior_reaction,
                   6670: span.LC_prior_math {
1.925     bisitz   6671:   font-family: $mono;
1.523     albertel 6672:   white-space: pre;
                   6673: }
                   6674: 
1.525     albertel 6675: span.LC_prior_string {
1.925     bisitz   6676:   font-family: $mono;
1.525     albertel 6677:   white-space: pre;
                   6678: }
                   6679: 
1.523     albertel 6680: table.LC_prior_option {
                   6681:   width: 100%;
                   6682:   border-collapse: collapse;
                   6683: }
1.795     www      6684: 
1.911     bisitz   6685: table.LC_prior_rank,
1.795     www      6686: table.LC_prior_match {
1.528     albertel 6687:   border-collapse: collapse;
                   6688: }
1.795     www      6689: 
1.528     albertel 6690: table.LC_prior_option tr td,
                   6691: table.LC_prior_rank tr td,
                   6692: table.LC_prior_match tr td {
1.524     albertel 6693:   border: 1px solid #000000;
1.515     albertel 6694: }
                   6695: 
1.855     bisitz   6696: .LC_nobreak {
1.544     albertel 6697:   white-space: nowrap;
1.519     raeburn  6698: }
                   6699: 
1.576     raeburn  6700: span.LC_cusr_emph {
                   6701:   font-style: italic;
                   6702: }
                   6703: 
1.633     raeburn  6704: span.LC_cusr_subheading {
                   6705:   font-weight: normal;
                   6706:   font-size: 85%;
                   6707: }
                   6708: 
1.861     bisitz   6709: div.LC_docs_entry_move {
1.859     bisitz   6710:   border: 1px solid #BBBBBB;
1.545     albertel 6711:   background: #DDDDDD;
1.861     bisitz   6712:   width: 22px;
1.859     bisitz   6713:   padding: 1px;
                   6714:   margin: 0;
1.545     albertel 6715: }
                   6716: 
1.861     bisitz   6717: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6718: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6719:   font-size: x-small;
                   6720: }
1.795     www      6721: 
1.861     bisitz   6722: .LC_docs_entry_parameter {
                   6723:   white-space: nowrap;
                   6724: }
                   6725: 
1.544     albertel 6726: .LC_docs_copy {
1.545     albertel 6727:   color: #000099;
1.544     albertel 6728: }
1.795     www      6729: 
1.544     albertel 6730: .LC_docs_cut {
1.545     albertel 6731:   color: #550044;
1.544     albertel 6732: }
1.795     www      6733: 
1.544     albertel 6734: .LC_docs_rename {
1.545     albertel 6735:   color: #009900;
1.544     albertel 6736: }
1.795     www      6737: 
1.544     albertel 6738: .LC_docs_remove {
1.545     albertel 6739:   color: #990000;
                   6740: }
                   6741: 
1.547     albertel 6742: .LC_docs_reinit_warn,
                   6743: .LC_docs_ext_edit {
                   6744:   font-size: x-small;
                   6745: }
                   6746: 
1.545     albertel 6747: table.LC_docs_adddocs td,
                   6748: table.LC_docs_adddocs th {
                   6749:   border: 1px solid #BBBBBB;
                   6750:   padding: 4px;
                   6751:   background: #DDDDDD;
1.543     albertel 6752: }
                   6753: 
1.584     albertel 6754: table.LC_sty_begin {
                   6755:   background: #BBFFBB;
                   6756: }
1.795     www      6757: 
1.584     albertel 6758: table.LC_sty_end {
                   6759:   background: #FFBBBB;
                   6760: }
                   6761: 
1.589     raeburn  6762: table.LC_double_column {
1.803     bisitz   6763:   border-width: 0;
1.589     raeburn  6764:   border-collapse: collapse;
                   6765:   width: 100%;
                   6766:   padding: 2px;
                   6767: }
                   6768: 
                   6769: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6770:   top: 2px;
1.589     raeburn  6771:   left: 2px;
                   6772:   width: 47%;
                   6773:   vertical-align: top;
                   6774: }
                   6775: 
                   6776: table.LC_double_column tr td.LC_right_col {
                   6777:   top: 2px;
1.779     bisitz   6778:   right: 2px;
1.589     raeburn  6779:   width: 47%;
                   6780:   vertical-align: top;
                   6781: }
                   6782: 
1.591     raeburn  6783: div.LC_left_float {
                   6784:   float: left;
                   6785:   padding-right: 5%;
1.597     albertel 6786:   padding-bottom: 4px;
1.591     raeburn  6787: }
                   6788: 
                   6789: div.LC_clear_float_header {
1.597     albertel 6790:   padding-bottom: 2px;
1.591     raeburn  6791: }
                   6792: 
                   6793: div.LC_clear_float_footer {
1.597     albertel 6794:   padding-top: 10px;
1.591     raeburn  6795:   clear: both;
                   6796: }
                   6797: 
1.597     albertel 6798: div.LC_grade_show_user {
1.941     bisitz   6799: /*  border-left: 5px solid $sidebg; */
                   6800:   border-top: 5px solid #000000;
                   6801:   margin: 50px 0 0 0;
1.936     bisitz   6802:   padding: 15px 0 5px 10px;
1.597     albertel 6803: }
1.795     www      6804: 
1.936     bisitz   6805: div.LC_grade_show_user_odd_row {
1.941     bisitz   6806: /*  border-left: 5px solid #000000; */
                   6807: }
                   6808: 
                   6809: div.LC_grade_show_user div.LC_Box {
                   6810:   margin-right: 50px;
1.597     albertel 6811: }
                   6812: 
                   6813: div.LC_grade_submissions,
                   6814: div.LC_grade_message_center,
1.936     bisitz   6815: div.LC_grade_info_links {
1.597     albertel 6816:   margin: 5px;
                   6817:   width: 99%;
                   6818:   background: #FFFFFF;
                   6819: }
1.795     www      6820: 
1.597     albertel 6821: div.LC_grade_submissions_header,
1.936     bisitz   6822: div.LC_grade_message_center_header {
1.705     tempelho 6823:   font-weight: bold;
                   6824:   font-size: large;
1.597     albertel 6825: }
1.795     www      6826: 
1.597     albertel 6827: div.LC_grade_submissions_body,
1.936     bisitz   6828: div.LC_grade_message_center_body {
1.597     albertel 6829:   border: 1px solid black;
                   6830:   width: 99%;
                   6831:   background: #FFFFFF;
                   6832: }
1.795     www      6833: 
1.613     albertel 6834: table.LC_scantron_action {
                   6835:   width: 100%;
                   6836: }
1.795     www      6837: 
1.613     albertel 6838: table.LC_scantron_action tr th {
1.698     harmsja  6839:   font-weight:bold;
                   6840:   font-style:normal;
1.613     albertel 6841: }
1.795     www      6842: 
1.779     bisitz   6843: .LC_edit_problem_header,
1.614     albertel 6844: div.LC_edit_problem_footer {
1.705     tempelho 6845:   font-weight: normal;
                   6846:   font-size:  medium;
1.602     albertel 6847:   margin: 2px;
1.1060    bisitz   6848:   background-color: $sidebg;
1.600     albertel 6849: }
1.795     www      6850: 
1.600     albertel 6851: div.LC_edit_problem_header,
1.602     albertel 6852: div.LC_edit_problem_header div,
1.614     albertel 6853: div.LC_edit_problem_footer,
                   6854: div.LC_edit_problem_footer div,
1.602     albertel 6855: div.LC_edit_problem_editxml_header,
                   6856: div.LC_edit_problem_editxml_header div {
1.1205    golterma 6857:   z-index: 100;
1.600     albertel 6858: }
1.795     www      6859: 
1.600     albertel 6860: div.LC_edit_problem_header_title {
1.705     tempelho 6861:   font-weight: bold;
                   6862:   font-size: larger;
1.602     albertel 6863:   background: $tabbg;
                   6864:   padding: 3px;
1.1060    bisitz   6865:   margin: 0 0 5px 0;
1.602     albertel 6866: }
1.795     www      6867: 
1.602     albertel 6868: table.LC_edit_problem_header_title {
                   6869:   width: 100%;
1.600     albertel 6870:   background: $tabbg;
1.602     albertel 6871: }
                   6872: 
1.1205    golterma 6873: div.LC_edit_actionbar {
                   6874:     background-color: $sidebg;
1.1218    droeschl 6875:     margin: 0;
                   6876:     padding: 0;
                   6877:     line-height: 200%;
1.602     albertel 6878: }
1.795     www      6879: 
1.1218    droeschl 6880: div.LC_edit_actionbar div{
                   6881:     padding: 0;
                   6882:     margin: 0;
                   6883:     display: inline-block;
1.600     albertel 6884: }
1.795     www      6885: 
1.1124    bisitz   6886: .LC_edit_opt {
                   6887:   padding-left: 1em;
                   6888:   white-space: nowrap;
                   6889: }
                   6890: 
1.1152    golterma 6891: .LC_edit_problem_latexhelper{
                   6892:     text-align: right;
                   6893: }
                   6894: 
                   6895: #LC_edit_problem_colorful div{
                   6896:     margin-left: 40px;
                   6897: }
                   6898: 
1.1205    golterma 6899: #LC_edit_problem_codemirror div{
                   6900:     margin-left: 0px;
                   6901: }
                   6902: 
1.911     bisitz   6903: img.stift {
1.803     bisitz   6904:   border-width: 0;
                   6905:   vertical-align: middle;
1.677     riegler  6906: }
1.680     riegler  6907: 
1.923     bisitz   6908: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6909:   vertical-align: top;
1.777     tempelho 6910: }
1.795     www      6911: 
1.716     raeburn  6912: div.LC_createcourse {
1.911     bisitz   6913:   margin: 10px 10px 10px 10px;
1.716     raeburn  6914: }
                   6915: 
1.917     raeburn  6916: .LC_dccid {
1.1130    raeburn  6917:   float: right;
1.917     raeburn  6918:   margin: 0.2em 0 0 0;
                   6919:   padding: 0;
                   6920:   font-size: 90%;
                   6921:   display:none;
                   6922: }
                   6923: 
1.897     wenzelju 6924: ol.LC_primary_menu a:hover,
1.721     harmsja  6925: ol#LC_MenuBreadcrumbs a:hover,
                   6926: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6927: ul#LC_secondary_menu a:hover,
1.721     harmsja  6928: .LC_FormSectionClearButton input:hover
1.795     www      6929: ul.LC_TabContent   li:hover a {
1.952     onken    6930:   color:$button_hover;
1.911     bisitz   6931:   text-decoration:none;
1.693     droeschl 6932: }
                   6933: 
1.779     bisitz   6934: h1 {
1.911     bisitz   6935:   padding: 0;
                   6936:   line-height:130%;
1.693     droeschl 6937: }
1.698     harmsja  6938: 
1.911     bisitz   6939: h2,
                   6940: h3,
                   6941: h4,
                   6942: h5,
                   6943: h6 {
                   6944:   margin: 5px 0 5px 0;
                   6945:   padding: 0;
                   6946:   line-height:130%;
1.693     droeschl 6947: }
1.795     www      6948: 
                   6949: .LC_hcell {
1.911     bisitz   6950:   padding:3px 15px 3px 15px;
                   6951:   margin: 0;
                   6952:   background-color:$tabbg;
                   6953:   color:$fontmenu;
                   6954:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6955: }
1.795     www      6956: 
1.840     bisitz   6957: .LC_Box > .LC_hcell {
1.911     bisitz   6958:   margin: 0 -10px 10px -10px;
1.835     bisitz   6959: }
                   6960: 
1.721     harmsja  6961: .LC_noBorder {
1.911     bisitz   6962:   border: 0;
1.698     harmsja  6963: }
1.693     droeschl 6964: 
1.721     harmsja  6965: .LC_FormSectionClearButton input {
1.911     bisitz   6966:   background-color:transparent;
                   6967:   border: none;
                   6968:   cursor:pointer;
                   6969:   text-decoration:underline;
1.693     droeschl 6970: }
1.763     bisitz   6971: 
                   6972: .LC_help_open_topic {
1.911     bisitz   6973:   color: #FFFFFF;
                   6974:   background-color: #EEEEFF;
                   6975:   margin: 1px;
                   6976:   padding: 4px;
                   6977:   border: 1px solid #000033;
                   6978:   white-space: nowrap;
                   6979:   /* vertical-align: middle; */
1.759     neumanie 6980: }
1.693     droeschl 6981: 
1.911     bisitz   6982: dl,
                   6983: ul,
                   6984: div,
                   6985: fieldset {
                   6986:   margin: 10px 10px 10px 0;
                   6987:   /* overflow: hidden; */
1.693     droeschl 6988: }
1.795     www      6989: 
1.1211    raeburn  6990: article.geogebraweb div {
                   6991:     margin: 0;
                   6992: }
                   6993: 
1.838     bisitz   6994: fieldset > legend {
1.911     bisitz   6995:   font-weight: bold;
                   6996:   padding: 0 5px 0 5px;
1.838     bisitz   6997: }
                   6998: 
1.813     bisitz   6999: #LC_nav_bar {
1.911     bisitz   7000:   float: left;
1.995     raeburn  7001:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7002:   margin: 0 0 2px 0;
1.807     droeschl 7003: }
                   7004: 
1.916     droeschl 7005: #LC_realm {
                   7006:   margin: 0.2em 0 0 0;
                   7007:   padding: 0;
                   7008:   font-weight: bold;
                   7009:   text-align: center;
1.995     raeburn  7010:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7011: }
                   7012: 
1.911     bisitz   7013: #LC_nav_bar em {
                   7014:   font-weight: bold;
                   7015:   font-style: normal;
1.807     droeschl 7016: }
                   7017: 
1.897     wenzelju 7018: ol.LC_primary_menu {
1.934     droeschl 7019:   margin: 0;
1.1076    raeburn  7020:   padding: 0;
1.807     droeschl 7021: }
                   7022: 
1.852     droeschl 7023: ol#LC_PathBreadcrumbs {
1.911     bisitz   7024:   margin: 0;
1.693     droeschl 7025: }
                   7026: 
1.897     wenzelju 7027: ol.LC_primary_menu li {
1.1076    raeburn  7028:   color: RGB(80, 80, 80);
                   7029:   vertical-align: middle;
                   7030:   text-align: left;
                   7031:   list-style: none;
1.1205    golterma 7032:   position: relative;
1.1076    raeburn  7033:   float: left;
1.1205    golterma 7034:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7035:   line-height: 1.5em;
1.1076    raeburn  7036: }
                   7037: 
1.1205    golterma 7038: ol.LC_primary_menu li a,
                   7039: ol.LC_primary_menu li p {
1.1076    raeburn  7040:   display: block;
                   7041:   margin: 0;
                   7042:   padding: 0 5px 0 10px;
                   7043:   text-decoration: none;
                   7044: }
                   7045: 
1.1205    golterma 7046: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7047:   display: inline-block;
                   7048:   width: 95%;
                   7049:   text-align: left;
                   7050: }
                   7051: 
                   7052: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7053:   display: inline-block;	
                   7054:   width: 5%;
                   7055:   float: right;
                   7056:   text-align: right;
                   7057:   font-size: 70%;
                   7058: }
                   7059: 
                   7060: ol.LC_primary_menu ul {
1.1076    raeburn  7061:   display: none;
1.1205    golterma 7062:   width: 15em;
1.1076    raeburn  7063:   background-color: $data_table_light;
1.1205    golterma 7064:   position: absolute;
                   7065:   top: 100%;
1.1076    raeburn  7066: }
                   7067: 
1.1205    golterma 7068: ol.LC_primary_menu ul ul {
                   7069:   left: 100%;
                   7070:   top: 0;
                   7071: }
                   7072: 
                   7073: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7074:   display: block;
                   7075:   position: absolute;
                   7076:   margin: 0;
                   7077:   padding: 0;
1.1078    raeburn  7078:   z-index: 2;
1.1076    raeburn  7079: }
                   7080: 
                   7081: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7082: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7083:   font-size: 90%;
1.911     bisitz   7084:   vertical-align: top;
1.1076    raeburn  7085:   float: none;
1.1079    raeburn  7086:   border-left: 1px solid black;
                   7087:   border-right: 1px solid black;
1.1205    golterma 7088: /* A dark bottom border to visualize different menu options; 
                   7089: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7090:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7091: }
                   7092: 
1.1205    golterma 7093: ol.LC_primary_menu li li p:hover {
                   7094:   color:$button_hover;
                   7095:   text-decoration:none;
                   7096:   background-color:$data_table_dark;
1.1076    raeburn  7097: }
                   7098: 
                   7099: ol.LC_primary_menu li li a:hover {
                   7100:    color:$button_hover;
                   7101:    background-color:$data_table_dark;
1.693     droeschl 7102: }
                   7103: 
1.1205    golterma 7104: /* Font-size equal to the size of the predecessors*/
                   7105: ol.LC_primary_menu li:hover li li {
                   7106:   font-size: 100%;
                   7107: }
                   7108: 
1.897     wenzelju 7109: ol.LC_primary_menu li img {
1.911     bisitz   7110:   vertical-align: bottom;
1.934     droeschl 7111:   height: 1.1em;
1.1077    raeburn  7112:   margin: 0.2em 0 0 0;
1.693     droeschl 7113: }
                   7114: 
1.897     wenzelju 7115: ol.LC_primary_menu a {
1.911     bisitz   7116:   color: RGB(80, 80, 80);
                   7117:   text-decoration: none;
1.693     droeschl 7118: }
1.795     www      7119: 
1.949     droeschl 7120: ol.LC_primary_menu a.LC_new_message {
                   7121:   font-weight:bold;
                   7122:   color: darkred;
                   7123: }
                   7124: 
1.975     raeburn  7125: ol.LC_docs_parameters {
                   7126:   margin-left: 0;
                   7127:   padding: 0;
                   7128:   list-style: none;
                   7129: }
                   7130: 
                   7131: ol.LC_docs_parameters li {
                   7132:   margin: 0;
                   7133:   padding-right: 20px;
                   7134:   display: inline;
                   7135: }
                   7136: 
1.976     raeburn  7137: ol.LC_docs_parameters li:before {
                   7138:   content: "\\002022 \\0020";
                   7139: }
                   7140: 
                   7141: li.LC_docs_parameters_title {
                   7142:   font-weight: bold;
                   7143: }
                   7144: 
                   7145: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7146:   content: "";
                   7147: }
                   7148: 
1.897     wenzelju 7149: ul#LC_secondary_menu {
1.1107    raeburn  7150:   clear: right;
1.911     bisitz   7151:   color: $fontmenu;
                   7152:   background: $tabbg;
                   7153:   list-style: none;
                   7154:   padding: 0;
                   7155:   margin: 0;
                   7156:   width: 100%;
1.995     raeburn  7157:   text-align: left;
1.1107    raeburn  7158:   float: left;
1.808     droeschl 7159: }
                   7160: 
1.897     wenzelju 7161: ul#LC_secondary_menu li {
1.911     bisitz   7162:   font-weight: bold;
                   7163:   line-height: 1.8em;
1.1107    raeburn  7164:   border-right: 1px solid black;
                   7165:   float: left;
                   7166: }
                   7167: 
                   7168: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7169:   background-color: $data_table_light;
                   7170: }
                   7171: 
                   7172: ul#LC_secondary_menu li a {
1.911     bisitz   7173:   padding: 0 0.8em;
1.1107    raeburn  7174: }
                   7175: 
                   7176: ul#LC_secondary_menu li ul {
                   7177:   display: none;
                   7178: }
                   7179: 
                   7180: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7181:   display: block;
                   7182:   position: absolute;
                   7183:   margin: 0;
                   7184:   padding: 0;
                   7185:   list-style:none;
                   7186:   float: none;
                   7187:   background-color: $data_table_light;
                   7188:   z-index: 2;
                   7189:   margin-left: -1px;
                   7190: }
                   7191: 
                   7192: ul#LC_secondary_menu li ul li {
                   7193:   font-size: 90%;
                   7194:   vertical-align: top;
                   7195:   border-left: 1px solid black;
1.911     bisitz   7196:   border-right: 1px solid black;
1.1119    raeburn  7197:   background-color: $data_table_light;
1.1107    raeburn  7198:   list-style:none;
                   7199:   float: none;
                   7200: }
                   7201: 
                   7202: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7203:   background-color: $data_table_dark;
1.807     droeschl 7204: }
                   7205: 
1.847     tempelho 7206: ul.LC_TabContent {
1.911     bisitz   7207:   display:block;
                   7208:   background: $sidebg;
                   7209:   border-bottom: solid 1px $lg_border_color;
                   7210:   list-style:none;
1.1020    raeburn  7211:   margin: -1px -10px 0 -10px;
1.911     bisitz   7212:   padding: 0;
1.693     droeschl 7213: }
                   7214: 
1.795     www      7215: ul.LC_TabContent li,
                   7216: ul.LC_TabContentBigger li {
1.911     bisitz   7217:   float:left;
1.741     harmsja  7218: }
1.795     www      7219: 
1.897     wenzelju 7220: ul#LC_secondary_menu li a {
1.911     bisitz   7221:   color: $fontmenu;
                   7222:   text-decoration: none;
1.693     droeschl 7223: }
1.795     www      7224: 
1.721     harmsja  7225: ul.LC_TabContent {
1.952     onken    7226:   min-height:20px;
1.721     harmsja  7227: }
1.795     www      7228: 
                   7229: ul.LC_TabContent li {
1.911     bisitz   7230:   vertical-align:middle;
1.959     onken    7231:   padding: 0 16px 0 10px;
1.911     bisitz   7232:   background-color:$tabbg;
                   7233:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7234:   border-left: solid 1px $font;
1.721     harmsja  7235: }
1.795     www      7236: 
1.847     tempelho 7237: ul.LC_TabContent .right {
1.911     bisitz   7238:   float:right;
1.847     tempelho 7239: }
                   7240: 
1.911     bisitz   7241: ul.LC_TabContent li a,
                   7242: ul.LC_TabContent li {
                   7243:   color:rgb(47,47,47);
                   7244:   text-decoration:none;
                   7245:   font-size:95%;
                   7246:   font-weight:bold;
1.952     onken    7247:   min-height:20px;
                   7248: }
                   7249: 
1.959     onken    7250: ul.LC_TabContent li a:hover,
                   7251: ul.LC_TabContent li a:focus {
1.952     onken    7252:   color: $button_hover;
1.959     onken    7253:   background:none;
                   7254:   outline:none;
1.952     onken    7255: }
                   7256: 
                   7257: ul.LC_TabContent li:hover {
                   7258:   color: $button_hover;
                   7259:   cursor:pointer;
1.721     harmsja  7260: }
1.795     www      7261: 
1.911     bisitz   7262: ul.LC_TabContent li.active {
1.952     onken    7263:   color: $font;
1.911     bisitz   7264:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7265:   border-bottom:solid 1px #FFFFFF;
                   7266:   cursor: default;
1.744     ehlerst  7267: }
1.795     www      7268: 
1.959     onken    7269: ul.LC_TabContent li.active a {
                   7270:   color:$font;
                   7271:   background:#FFFFFF;
                   7272:   outline: none;
                   7273: }
1.1047    raeburn  7274: 
                   7275: ul.LC_TabContent li.goback {
                   7276:   float: left;
                   7277:   border-left: none;
                   7278: }
                   7279: 
1.870     tempelho 7280: #maincoursedoc {
1.911     bisitz   7281:   clear:both;
1.870     tempelho 7282: }
                   7283: 
                   7284: ul.LC_TabContentBigger {
1.911     bisitz   7285:   display:block;
                   7286:   list-style:none;
                   7287:   padding: 0;
1.870     tempelho 7288: }
                   7289: 
1.795     www      7290: ul.LC_TabContentBigger li {
1.911     bisitz   7291:   vertical-align:bottom;
                   7292:   height: 30px;
                   7293:   font-size:110%;
                   7294:   font-weight:bold;
                   7295:   color: #737373;
1.841     tempelho 7296: }
                   7297: 
1.957     onken    7298: ul.LC_TabContentBigger li.active {
                   7299:   position: relative;
                   7300:   top: 1px;
                   7301: }
                   7302: 
1.870     tempelho 7303: ul.LC_TabContentBigger li a {
1.911     bisitz   7304:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7305:   height: 30px;
                   7306:   line-height: 30px;
                   7307:   text-align: center;
                   7308:   display: block;
                   7309:   text-decoration: none;
1.958     onken    7310:   outline: none;  
1.741     harmsja  7311: }
1.795     www      7312: 
1.870     tempelho 7313: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7314:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7315:   color:$font;
1.744     ehlerst  7316: }
1.795     www      7317: 
1.870     tempelho 7318: ul.LC_TabContentBigger li b {
1.911     bisitz   7319:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7320:   display: block;
                   7321:   float: left;
                   7322:   padding: 0 30px;
1.957     onken    7323:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7324: }
                   7325: 
1.956     onken    7326: ul.LC_TabContentBigger li:hover b {
                   7327:   color:$button_hover;
                   7328: }
                   7329: 
1.870     tempelho 7330: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7331:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7332:   color:$font;
1.957     onken    7333:   border: 0;
1.741     harmsja  7334: }
1.693     droeschl 7335: 
1.870     tempelho 7336: 
1.862     bisitz   7337: ul.LC_CourseBreadcrumbs {
                   7338:   background: $sidebg;
1.1020    raeburn  7339:   height: 2em;
1.862     bisitz   7340:   padding-left: 10px;
1.1020    raeburn  7341:   margin: 0;
1.862     bisitz   7342:   list-style-position: inside;
                   7343: }
                   7344: 
1.911     bisitz   7345: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7346: ol#LC_PathBreadcrumbs {
1.911     bisitz   7347:   padding-left: 10px;
                   7348:   margin: 0;
1.933     droeschl 7349:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7350: }
                   7351: 
1.911     bisitz   7352: ol#LC_MenuBreadcrumbs li,
                   7353: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7354: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7355:   display: inline;
1.933     droeschl 7356:   white-space: normal;  
1.693     droeschl 7357: }
                   7358: 
1.823     bisitz   7359: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7360: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7361:   text-decoration: none;
                   7362:   font-size:90%;
1.693     droeschl 7363: }
1.795     www      7364: 
1.969     droeschl 7365: ol#LC_MenuBreadcrumbs h1 {
                   7366:   display: inline;
                   7367:   font-size: 90%;
                   7368:   line-height: 2.5em;
                   7369:   margin: 0;
                   7370:   padding: 0;
                   7371: }
                   7372: 
1.795     www      7373: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7374:   text-decoration:none;
                   7375:   font-size:100%;
                   7376:   font-weight:bold;
1.693     droeschl 7377: }
1.795     www      7378: 
1.840     bisitz   7379: .LC_Box {
1.911     bisitz   7380:   border: solid 1px $lg_border_color;
                   7381:   padding: 0 10px 10px 10px;
1.746     neumanie 7382: }
1.795     www      7383: 
1.1020    raeburn  7384: .LC_DocsBox {
                   7385:   border: solid 1px $lg_border_color;
                   7386:   padding: 0 0 10px 10px;
                   7387: }
                   7388: 
1.795     www      7389: .LC_AboutMe_Image {
1.911     bisitz   7390:   float:left;
                   7391:   margin-right:10px;
1.747     neumanie 7392: }
1.795     www      7393: 
                   7394: .LC_Clear_AboutMe_Image {
1.911     bisitz   7395:   clear:left;
1.747     neumanie 7396: }
1.795     www      7397: 
1.721     harmsja  7398: dl.LC_ListStyleClean dt {
1.911     bisitz   7399:   padding-right: 5px;
                   7400:   display: table-header-group;
1.693     droeschl 7401: }
                   7402: 
1.721     harmsja  7403: dl.LC_ListStyleClean dd {
1.911     bisitz   7404:   display: table-row;
1.693     droeschl 7405: }
                   7406: 
1.721     harmsja  7407: .LC_ListStyleClean,
                   7408: .LC_ListStyleSimple,
                   7409: .LC_ListStyleNormal,
1.795     www      7410: .LC_ListStyleSpecial {
1.911     bisitz   7411:   /* display:block; */
                   7412:   list-style-position: inside;
                   7413:   list-style-type: none;
                   7414:   overflow: hidden;
                   7415:   padding: 0;
1.693     droeschl 7416: }
                   7417: 
1.721     harmsja  7418: .LC_ListStyleSimple li,
                   7419: .LC_ListStyleSimple dd,
                   7420: .LC_ListStyleNormal li,
                   7421: .LC_ListStyleNormal dd,
                   7422: .LC_ListStyleSpecial li,
1.795     www      7423: .LC_ListStyleSpecial dd {
1.911     bisitz   7424:   margin: 0;
                   7425:   padding: 5px 5px 5px 10px;
                   7426:   clear: both;
1.693     droeschl 7427: }
                   7428: 
1.721     harmsja  7429: .LC_ListStyleClean li,
                   7430: .LC_ListStyleClean dd {
1.911     bisitz   7431:   padding-top: 0;
                   7432:   padding-bottom: 0;
1.693     droeschl 7433: }
                   7434: 
1.721     harmsja  7435: .LC_ListStyleSimple dd,
1.795     www      7436: .LC_ListStyleSimple li {
1.911     bisitz   7437:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7438: }
                   7439: 
1.721     harmsja  7440: .LC_ListStyleSpecial li,
                   7441: .LC_ListStyleSpecial dd {
1.911     bisitz   7442:   list-style-type: none;
                   7443:   background-color: RGB(220, 220, 220);
                   7444:   margin-bottom: 4px;
1.693     droeschl 7445: }
                   7446: 
1.721     harmsja  7447: table.LC_SimpleTable {
1.911     bisitz   7448:   margin:5px;
                   7449:   border:solid 1px $lg_border_color;
1.795     www      7450: }
1.693     droeschl 7451: 
1.721     harmsja  7452: table.LC_SimpleTable tr {
1.911     bisitz   7453:   padding: 0;
                   7454:   border:solid 1px $lg_border_color;
1.693     droeschl 7455: }
1.795     www      7456: 
                   7457: table.LC_SimpleTable thead {
1.911     bisitz   7458:   background:rgb(220,220,220);
1.693     droeschl 7459: }
                   7460: 
1.721     harmsja  7461: div.LC_columnSection {
1.911     bisitz   7462:   display: block;
                   7463:   clear: both;
                   7464:   overflow: hidden;
                   7465:   margin: 0;
1.693     droeschl 7466: }
                   7467: 
1.721     harmsja  7468: div.LC_columnSection>* {
1.911     bisitz   7469:   float: left;
                   7470:   margin: 10px 20px 10px 0;
                   7471:   overflow:hidden;
1.693     droeschl 7472: }
1.721     harmsja  7473: 
1.795     www      7474: table em {
1.911     bisitz   7475:   font-weight: bold;
                   7476:   font-style: normal;
1.748     schulted 7477: }
1.795     www      7478: 
1.779     bisitz   7479: table.LC_tableBrowseRes,
1.795     www      7480: table.LC_tableOfContent {
1.911     bisitz   7481:   border:none;
                   7482:   border-spacing: 1px;
                   7483:   padding: 3px;
                   7484:   background-color: #FFFFFF;
                   7485:   font-size: 90%;
1.753     droeschl 7486: }
1.789     droeschl 7487: 
1.911     bisitz   7488: table.LC_tableOfContent {
                   7489:   border-collapse: collapse;
1.789     droeschl 7490: }
                   7491: 
1.771     droeschl 7492: table.LC_tableBrowseRes a,
1.768     schulted 7493: table.LC_tableOfContent a {
1.911     bisitz   7494:   background-color: transparent;
                   7495:   text-decoration: none;
1.753     droeschl 7496: }
                   7497: 
1.795     www      7498: table.LC_tableOfContent img {
1.911     bisitz   7499:   border: none;
                   7500:   height: 1.3em;
                   7501:   vertical-align: text-bottom;
                   7502:   margin-right: 0.3em;
1.753     droeschl 7503: }
1.757     schulted 7504: 
1.795     www      7505: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7506:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7507: }
                   7508: 
1.795     www      7509: a#LC_content_toolbar_everything {
1.911     bisitz   7510:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7511: }
                   7512: 
1.795     www      7513: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7514:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7515: }
                   7516: 
1.795     www      7517: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7518:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7519: }
                   7520: 
1.795     www      7521: a#LC_content_toolbar_changefolder {
1.911     bisitz   7522:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7523: }
                   7524: 
1.795     www      7525: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7526:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7527: }
                   7528: 
1.1043    raeburn  7529: a#LC_content_toolbar_edittoplevel {
                   7530:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7531: }
                   7532: 
1.795     www      7533: ul#LC_toolbar li a:hover {
1.911     bisitz   7534:   background-position: bottom center;
1.757     schulted 7535: }
                   7536: 
1.795     www      7537: ul#LC_toolbar {
1.911     bisitz   7538:   padding: 0;
                   7539:   margin: 2px;
                   7540:   list-style:none;
                   7541:   position:relative;
                   7542:   background-color:white;
1.1082    raeburn  7543:   overflow: auto;
1.757     schulted 7544: }
                   7545: 
1.795     www      7546: ul#LC_toolbar li {
1.911     bisitz   7547:   border:1px solid white;
                   7548:   padding: 0;
                   7549:   margin: 0;
                   7550:   float: left;
                   7551:   display:inline;
                   7552:   vertical-align:middle;
1.1082    raeburn  7553:   white-space: nowrap;
1.911     bisitz   7554: }
1.757     schulted 7555: 
1.783     amueller 7556: 
1.795     www      7557: a.LC_toolbarItem {
1.911     bisitz   7558:   display:block;
                   7559:   padding: 0;
                   7560:   margin: 0;
                   7561:   height: 32px;
                   7562:   width: 32px;
                   7563:   color:white;
                   7564:   border: none;
                   7565:   background-repeat:no-repeat;
                   7566:   background-color:transparent;
1.757     schulted 7567: }
                   7568: 
1.915     droeschl 7569: ul.LC_funclist {
                   7570:     margin: 0;
                   7571:     padding: 0.5em 1em 0.5em 0;
                   7572: }
                   7573: 
1.933     droeschl 7574: ul.LC_funclist > li:first-child {
                   7575:     font-weight:bold; 
                   7576:     margin-left:0.8em;
                   7577: }
                   7578: 
1.915     droeschl 7579: ul.LC_funclist + ul.LC_funclist {
                   7580:     /* 
                   7581:        left border as a seperator if we have more than
                   7582:        one list 
                   7583:     */
                   7584:     border-left: 1px solid $sidebg;
                   7585:     /* 
                   7586:        this hides the left border behind the border of the 
                   7587:        outer box if element is wrapped to the next 'line' 
                   7588:     */
                   7589:     margin-left: -1px;
                   7590: }
                   7591: 
1.843     bisitz   7592: ul.LC_funclist li {
1.915     droeschl 7593:   display: inline;
1.782     bisitz   7594:   white-space: nowrap;
1.915     droeschl 7595:   margin: 0 0 0 25px;
                   7596:   line-height: 150%;
1.782     bisitz   7597: }
                   7598: 
1.974     wenzelju 7599: .LC_hidden {
                   7600:   display: none;
                   7601: }
                   7602: 
1.1030    www      7603: .LCmodal-overlay {
                   7604: 		position:fixed;
                   7605: 		top:0;
                   7606: 		right:0;
                   7607: 		bottom:0;
                   7608: 		left:0;
                   7609: 		height:100%;
                   7610: 		width:100%;
                   7611: 		margin:0;
                   7612: 		padding:0;
                   7613: 		background:#999;
                   7614: 		opacity:.75;
                   7615: 		filter: alpha(opacity=75);
                   7616: 		-moz-opacity: 0.75;
                   7617: 		z-index:101;
                   7618: }
                   7619: 
                   7620: * html .LCmodal-overlay {   
                   7621: 		position: absolute;
                   7622: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7623: }
                   7624: 
                   7625: .LCmodal-window {
                   7626: 		position:fixed;
                   7627: 		top:50%;
                   7628: 		left:50%;
                   7629: 		margin:0;
                   7630: 		padding:0;
                   7631: 		z-index:102;
                   7632: 	}
                   7633: 
                   7634: * html .LCmodal-window {
                   7635: 		position:absolute;
                   7636: }
                   7637: 
                   7638: .LCclose-window {
                   7639: 		position:absolute;
                   7640: 		width:32px;
                   7641: 		height:32px;
                   7642: 		right:8px;
                   7643: 		top:8px;
                   7644: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7645: 		text-indent:-99999px;
                   7646: 		overflow:hidden;
                   7647: 		cursor:pointer;
                   7648: }
                   7649: 
1.1100    raeburn  7650: /*
                   7651:   styles used by TTH when "Default set of options to pass to tth/m
                   7652:   when converting TeX" in course settings has been set
                   7653: 
                   7654:   option passed: -t
                   7655: 
                   7656: */
                   7657: 
                   7658: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7659: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7660: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7661: td div.norm {line-height:normal;}
                   7662: 
                   7663: /*
                   7664:   option passed -y3
                   7665: */
                   7666: 
                   7667: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7668: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7669: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7670: 
1.1230  ! damieng  7671: /*
        !          7672:   sections with roles, for content only
        !          7673: */
        !          7674: section[class^="role-"] {
        !          7675:   padding-left: 10px;
        !          7676:   padding-right: 5px;
        !          7677:   margin-top: 8px;
        !          7678:   margin-bottom: 8px;
        !          7679:   border: 1px solid #2A4;
        !          7680:   border-radius: 5px;
        !          7681:   box-shadow: 0px 1px 1px #BBB;
        !          7682: }
        !          7683: section[class^="role-"]>h1 {
        !          7684:   position: relative;
        !          7685:   margin: 0px;
        !          7686:   padding-top: 10px;
        !          7687:   padding-left: 40px;
        !          7688: }
        !          7689: section[class^="role-"]>h1:before {
        !          7690:   position: absolute;
        !          7691:   left: -5px;
        !          7692:   top: 5px;
        !          7693: }
        !          7694: section.role-activity>h1:before {
        !          7695:   content:url('/adm/daxe/images/section_icons/activity.png');
        !          7696: }
        !          7697: section.role-advice>h1:before {
        !          7698:   content:url('/adm/daxe/images/section_icons/advice.png');
        !          7699: }
        !          7700: section.role-bibliography>h1:before {
        !          7701:   content:url('/adm/daxe/images/section_icons/bibliography.png');
        !          7702: }
        !          7703: section.role-citation>h1:before {
        !          7704:   content:url('/adm/daxe/images/section_icons/citation.png');
        !          7705: }
        !          7706: section.role-conclusion>h1:before {
        !          7707:   content:url('/adm/daxe/images/section_icons/conclusion.png');
        !          7708: }
        !          7709: section.role-definition>h1:before {
        !          7710:   content:url('/adm/daxe/images/section_icons/definition.png');
        !          7711: }
        !          7712: section.role-demonstration>h1:before {
        !          7713:   content:url('/adm/daxe/images/section_icons/demonstration.png');
        !          7714: }
        !          7715: section.role-example>h1:before {
        !          7716:   content:url('/adm/daxe/images/section_icons/example.png');
        !          7717: }
        !          7718: section.role-explanation>h1:before {
        !          7719:   content:url('/adm/daxe/images/section_icons/explanation.png');
        !          7720: }
        !          7721: section.role-introduction>h1:before {
        !          7722:   content:url('/adm/daxe/images/section_icons/introduction.png');
        !          7723: }
        !          7724: section.role-method>h1:before {
        !          7725:   content:url('/adm/daxe/images/section_icons/method.png');
        !          7726: }
        !          7727: section.role-more_information>h1:before {
        !          7728:   content:url('/adm/daxe/images/section_icons/more_information.png');
        !          7729: }
        !          7730: section.role-objectives>h1:before {
        !          7731:   content:url('/adm/daxe/images/section_icons/objectives.png');
        !          7732: }
        !          7733: section.role-prerequisites>h1:before {
        !          7734:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
        !          7735: }
        !          7736: section.role-remark>h1:before {
        !          7737:   content:url('/adm/daxe/images/section_icons/remark.png');
        !          7738: }
        !          7739: section.role-reminder>h1:before {
        !          7740:   content:url('/adm/daxe/images/section_icons/reminder.png');
        !          7741: }
        !          7742: section.role-summary>h1:before {
        !          7743:   content:url('/adm/daxe/images/section_icons/summary.png');
        !          7744: }
        !          7745: section.role-syntax>h1:before {
        !          7746:   content:url('/adm/daxe/images/section_icons/syntax.png');
        !          7747: }
        !          7748: section.role-warning>h1:before {
        !          7749:   content:url('/adm/daxe/images/section_icons/warning.png');
        !          7750: }
        !          7751: 
1.343     albertel 7752: END
                   7753: }
                   7754: 
1.306     albertel 7755: =pod
                   7756: 
                   7757: =item * &headtag()
                   7758: 
                   7759: Returns a uniform footer for LON-CAPA web pages.
                   7760: 
1.307     albertel 7761: Inputs: $title - optional title for the head
                   7762:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7763:         $args - optional arguments
1.319     albertel 7764:             force_register - if is true call registerurl so the remote is 
                   7765:                              informed
1.415     albertel 7766:             redirect       -> array ref of
                   7767:                                    1- seconds before redirect occurs
                   7768:                                    2- url to redirect to
                   7769:                                    3- whether the side effect should occur
1.315     albertel 7770:                            (side effect of setting 
                   7771:                                $env{'internal.head.redirect'} to the url 
                   7772:                                redirected too)
1.352     albertel 7773:             domain         -> force to color decorate a page for a specific
                   7774:                                domain
                   7775:             function       -> force usage of a specific rolish color scheme
                   7776:             bgcolor        -> override the default page bgcolor
1.460     albertel 7777:             no_auto_mt_title
                   7778:                            -> prevent &mt()ing the title arg
1.464     albertel 7779: 
1.306     albertel 7780: =cut
                   7781: 
                   7782: sub headtag {
1.313     albertel 7783:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7784:     
1.363     albertel 7785:     my $function = $args->{'function'} || &get_users_function();
                   7786:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7787:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  7788:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7789:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7790: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7791: 		   #time(),
1.418     albertel 7792: 		   $env{'environment.color.timestamp'},
1.363     albertel 7793: 		   $function,$domain,$bgcolor);
                   7794: 
1.369     www      7795:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7796: 
1.308     albertel 7797:     my $result =
                   7798: 	'<head>'.
1.1160    raeburn  7799: 	&font_settings($args);
1.319     albertel 7800: 
1.1188    raeburn  7801:     my $inhibitprint;
                   7802:     if ($args->{'print_suppress'}) {
                   7803:         $inhibitprint = &print_suppression();
                   7804:     }
1.1064    raeburn  7805: 
1.461     albertel 7806:     if (!$args->{'frameset'}) {
                   7807: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7808:     }
1.962     droeschl 7809:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7810:         $result .= Apache::lonxml::display_title();
1.319     albertel 7811:     }
1.436     albertel 7812:     if (!$args->{'no_nav_bar'} 
                   7813: 	&& !$args->{'only_body'}
                   7814: 	&& !$args->{'frameset'}) {
1.1154    raeburn  7815: 	$result .= &help_menu_js($httphost);
1.1032    www      7816:         $result.=&modal_window();
1.1038    www      7817:         $result.=&togglebox_script();
1.1034    www      7818:         $result.=&wishlist_window();
1.1041    www      7819:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7820:     } else {
                   7821:         if ($args->{'add_modal'}) {
                   7822:            $result.=&modal_window();
                   7823:         }
                   7824:         if ($args->{'add_wishlist'}) {
                   7825:            $result.=&wishlist_window();
                   7826:         }
1.1038    www      7827:         if ($args->{'add_togglebox'}) {
                   7828:            $result.=&togglebox_script();
                   7829:         }
1.1041    www      7830:         if ($args->{'add_progressbar'}) {
                   7831:            $result.=&LCprogressbarUpdate_script();
                   7832:         }
1.436     albertel 7833:     }
1.314     albertel 7834:     if (ref($args->{'redirect'})) {
1.414     albertel 7835: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7836: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7837: 	if (!$inhibit_continue) {
                   7838: 	    $env{'internal.head.redirect'} = $url;
                   7839: 	}
1.313     albertel 7840: 	$result.=<<ADDMETA
                   7841: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7842: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7843: ADDMETA
1.1210    raeburn  7844:     } else {
                   7845:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7846:             my $requrl = $env{'request.uri'};
                   7847:             if ($requrl eq '') {
                   7848:                 $requrl = $ENV{'REQUEST_URI'};
                   7849:                 $requrl =~ s/\?.+$//;
                   7850:             }
                   7851:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7852:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7853:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7854:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7855:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7856:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7857:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7858:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7859:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7860:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7861:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7862:                                 my $numsec = 5;
                   7863:                                 my $timeout = $numsec * 1000;
                   7864:                                 my ($newurl,$locknum,%locks,$msg);
                   7865:                                 if ($env{'request.role.adv'}) {
                   7866:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7867:                                 }
                   7868:                                 my $disable_submit = 0;
                   7869:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7870:                                     $disable_submit = 1;
                   7871:                                 }
                   7872:                                 if ($locknum) {
                   7873:                                     my @lockinfo = sort(values(%locks));
                   7874:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7875:                                            join(", ",sort(values(%locks)))."\\n".
                   7876:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7877:                                 } else {
                   7878:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7879:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7880:                                     }
                   7881:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7882:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7883:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7884:                                         $newurl .= '&role='.$env{'request.role'};
                   7885:                                     }
                   7886:                                     if ($env{'request.symb'}) {
                   7887:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7888:                                     } else {
                   7889:                                         $newurl .= '&origurl='.$requrl;
                   7890:                                     }
                   7891:                                 }
1.1222    damieng  7892:                                 &js_escape(\$msg);
1.1210    raeburn  7893:                                 $result.=<<OFFLOAD
                   7894: <meta http-equiv="pragma" content="no-cache" />
                   7895: <script type="text/javascript">
1.1215    raeburn  7896: // <![CDATA[
1.1210    raeburn  7897: function LC_Offload_Now() {
                   7898:     var dest = "$newurl";
                   7899:     if (dest != '') {
                   7900:         window.location.href="$newurl";
                   7901:     }
                   7902: }
1.1214    raeburn  7903: \$(document).ready(function () {
                   7904:     window.alert('$msg');
                   7905:     if ($disable_submit) {
1.1210    raeburn  7906:         \$(".LC_hwk_submit").prop("disabled", true);
                   7907:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  7908:     }
                   7909:     setTimeout('LC_Offload_Now()', $timeout);
                   7910: });
1.1215    raeburn  7911: // ]]>
1.1210    raeburn  7912: </script>
                   7913: OFFLOAD
                   7914:                             }
                   7915:                         }
                   7916:                     }
                   7917:                 }
                   7918:             }
                   7919:         }
1.313     albertel 7920:     }
1.306     albertel 7921:     if (!defined($title)) {
                   7922: 	$title = 'The LearningOnline Network with CAPA';
                   7923:     }
1.460     albertel 7924:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7925:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  7926: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7927:     if (!$args->{'frameset'}) {
                   7928:         $result .= ' /';
                   7929:     }
                   7930:     $result .= '>' 
1.1064    raeburn  7931:         .$inhibitprint
1.414     albertel 7932: 	.$head_extra;
1.1137    raeburn  7933:     if ($env{'browser.mobile'}) {
                   7934:         $result .= '
                   7935: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7936: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7937:     }
1.962     droeschl 7938:     return $result.'</head>';
1.306     albertel 7939: }
                   7940: 
                   7941: =pod
                   7942: 
1.340     albertel 7943: =item * &font_settings()
                   7944: 
                   7945: Returns neccessary <meta> to set the proper encoding
                   7946: 
1.1160    raeburn  7947: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7948: 
                   7949: =cut
                   7950: 
                   7951: sub font_settings {
1.1160    raeburn  7952:     my ($args) = @_;
1.340     albertel 7953:     my $headerstring='';
1.1160    raeburn  7954:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7955:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  7956:         $headerstring.=
                   7957:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7958:         if (!$args->{'frameset'}) {
                   7959: 	    $headerstring.= ' /';
                   7960:         }
                   7961: 	$headerstring .= '>'."\n";
1.340     albertel 7962:     }
                   7963:     return $headerstring;
                   7964: }
                   7965: 
1.341     albertel 7966: =pod
                   7967: 
1.1064    raeburn  7968: =item * &print_suppression()
                   7969: 
                   7970: In course context returns css which causes the body to be blank when media="print",
                   7971: if printout generation is unavailable for the current resource.
                   7972: 
                   7973: This could be because:
                   7974: 
                   7975: (a) printstartdate is in the future
                   7976: 
                   7977: (b) printenddate is in the past
                   7978: 
                   7979: (c) there is an active exam block with "printout"
                   7980: functionality blocked
                   7981: 
                   7982: Users with pav, pfo or evb privileges are exempt.
                   7983: 
                   7984: Inputs: none
                   7985: 
                   7986: =cut
                   7987: 
                   7988: 
                   7989: sub print_suppression {
                   7990:     my $noprint;
                   7991:     if ($env{'request.course.id'}) {
                   7992:         my $scope = $env{'request.course.id'};
                   7993:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7994:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7995:             return;
                   7996:         }
                   7997:         if ($env{'request.course.sec'} ne '') {
                   7998:             $scope .= "/$env{'request.course.sec'}";
                   7999:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8000:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8001:                 return;
1.1064    raeburn  8002:             }
                   8003:         }
                   8004:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8005:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8006:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8007:         if ($blocked) {
                   8008:             my $checkrole = "cm./$cdom/$cnum";
                   8009:             if ($env{'request.course.sec'} ne '') {
                   8010:                 $checkrole .= "/$env{'request.course.sec'}";
                   8011:             }
                   8012:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8013:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8014:                 $noprint = 1;
                   8015:             }
                   8016:         }
                   8017:         unless ($noprint) {
                   8018:             my $symb = &Apache::lonnet::symbread();
                   8019:             if ($symb ne '') {
                   8020:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8021:                 if (ref($navmap)) {
                   8022:                     my $res = $navmap->getBySymb($symb);
                   8023:                     if (ref($res)) {
                   8024:                         if (!$res->resprintable()) {
                   8025:                             $noprint = 1;
                   8026:                         }
                   8027:                     }
                   8028:                 }
                   8029:             }
                   8030:         }
                   8031:         if ($noprint) {
                   8032:             return <<"ENDSTYLE";
                   8033: <style type="text/css" media="print">
                   8034:     body { display:none }
                   8035: </style>
                   8036: ENDSTYLE
                   8037:         }
                   8038:     }
                   8039:     return;
                   8040: }
                   8041: 
                   8042: =pod
                   8043: 
1.341     albertel 8044: =item * &xml_begin()
                   8045: 
                   8046: Returns the needed doctype and <html>
                   8047: 
                   8048: Inputs: none
                   8049: 
                   8050: =cut
                   8051: 
                   8052: sub xml_begin {
1.1168    raeburn  8053:     my ($is_frameset) = @_;
1.341     albertel 8054:     my $output='';
                   8055: 
                   8056:     if ($env{'browser.mathml'}) {
                   8057: 	$output='<?xml version="1.0"?>'
                   8058:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8059: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8060:             
                   8061: #	    .'<!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">] >'
                   8062: 	    .'<!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">'
                   8063:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8064: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8065:     } elsif ($is_frameset) {
                   8066:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8067:                 '<html>'."\n";
1.341     albertel 8068:     } else {
1.1168    raeburn  8069: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8070:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8071:     }
                   8072:     return $output;
                   8073: }
1.340     albertel 8074: 
                   8075: =pod
                   8076: 
1.306     albertel 8077: =item * &start_page()
                   8078: 
                   8079: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8080: 
1.648     raeburn  8081: Inputs:
                   8082: 
                   8083: =over 4
                   8084: 
                   8085: $title - optional title for the page
                   8086: 
                   8087: $head_extra - optional extra HTML to incude inside the <head>
                   8088: 
                   8089: $args - additional optional args supported are:
                   8090: 
                   8091: =over 8
                   8092: 
                   8093:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8094:                                     arg on
1.814     bisitz   8095:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8096:              add_entries    -> additional attributes to add to the  <body>
                   8097:              domain         -> force to color decorate a page for a 
1.317     albertel 8098:                                     specific domain
1.648     raeburn  8099:              function       -> force usage of a specific rolish color
1.317     albertel 8100:                                     scheme
1.648     raeburn  8101:              redirect       -> see &headtag()
                   8102:              bgcolor        -> override the default page bg color
                   8103:              js_ready       -> return a string ready for being used in 
1.317     albertel 8104:                                     a javascript writeln
1.648     raeburn  8105:              html_encode    -> return a string ready for being used in 
1.320     albertel 8106:                                     a html attribute
1.648     raeburn  8107:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8108:                                     $forcereg arg
1.648     raeburn  8109:              frameset       -> if true will start with a <frameset>
1.330     albertel 8110:                                     rather than <body>
1.648     raeburn  8111:              skip_phases    -> hash ref of 
1.338     albertel 8112:                                     head -> skip the <html><head> generation
                   8113:                                     body -> skip all <body> generation
1.648     raeburn  8114:              no_auto_mt_title -> prevent &mt()ing the title arg
                   8115:              inherit_jsmath -> when creating popup window in a page,
                   8116:                                     should it have jsmath forced on by the
                   8117:                                     current page
1.867     kalberla 8118:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8119:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  8120:              group          -> includes the current group, if page is for a 
                   8121:                                specific group  
1.361     albertel 8122: 
1.648     raeburn  8123: =back
1.460     albertel 8124: 
1.648     raeburn  8125: =back
1.562     albertel 8126: 
1.306     albertel 8127: =cut
                   8128: 
                   8129: sub start_page {
1.309     albertel 8130:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8131:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8132: 
1.315     albertel 8133:     $env{'internal.start_page'}++;
1.1096    raeburn  8134:     my ($result,@advtools);
1.964     droeschl 8135: 
1.338     albertel 8136:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8137:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8138:     }
                   8139:     
                   8140:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8141: 	if ($args->{'frameset'}) {
                   8142: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8143: 						$args->{'add_entries'});
                   8144: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8145:         } else {
                   8146:             $result .=
                   8147:                 &bodytag($title, 
                   8148:                          $args->{'function'},       $args->{'add_entries'},
                   8149:                          $args->{'only_body'},      $args->{'domain'},
                   8150:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8151:                          $args->{'bgcolor'},        $args,
                   8152:                          \@advtools);
1.831     bisitz   8153:         }
1.330     albertel 8154:     }
1.338     albertel 8155: 
1.315     albertel 8156:     if ($args->{'js_ready'}) {
1.713     kaisler  8157: 		$result = &js_ready($result);
1.315     albertel 8158:     }
1.320     albertel 8159:     if ($args->{'html_encode'}) {
1.713     kaisler  8160: 		$result = &html_encode($result);
                   8161:     }
                   8162: 
1.813     bisitz   8163:     # Preparation for new and consistent functionlist at top of screen
                   8164:     # if ($args->{'functionlist'}) {
                   8165:     #            $result .= &build_functionlist();
                   8166:     #}
                   8167: 
1.964     droeschl 8168:     # Don't add anything more if only_body wanted or in const space
                   8169:     return $result if    $args->{'only_body'} 
                   8170:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8171: 
                   8172:     #Breadcrumbs
1.758     kaisler  8173:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8174: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8175: 		#if any br links exists, add them to the breadcrumbs
                   8176: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8177: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8178: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8179: 			}
                   8180: 		}
1.1096    raeburn  8181:                 # if @advtools array contains items add then to the breadcrumbs
                   8182:                 if (@advtools > 0) {
                   8183:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8184:                 }
1.758     kaisler  8185: 
                   8186: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8187: 		if(exists($args->{'bread_crumbs_component'})){
                   8188: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   8189: 		}else{
                   8190: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   8191: 		}
1.320     albertel 8192:     }
1.315     albertel 8193:     return $result;
1.306     albertel 8194: }
                   8195: 
                   8196: sub end_page {
1.315     albertel 8197:     my ($args) = @_;
                   8198:     $env{'internal.end_page'}++;
1.330     albertel 8199:     my $result;
1.335     albertel 8200:     if ($args->{'discussion'}) {
                   8201: 	my ($target,$parser);
                   8202: 	if (ref($args->{'discussion'})) {
                   8203: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8204: 				$args->{'discussion'}{'parser'});
                   8205: 	}
                   8206: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8207:     }
1.330     albertel 8208:     if ($args->{'frameset'}) {
                   8209: 	$result .= '</frameset>';
                   8210:     } else {
1.635     raeburn  8211: 	$result .= &endbodytag($args);
1.330     albertel 8212:     }
1.1080    raeburn  8213:     unless ($args->{'notbody'}) {
                   8214:         $result .= "\n</html>";
                   8215:     }
1.330     albertel 8216: 
1.315     albertel 8217:     if ($args->{'js_ready'}) {
1.317     albertel 8218: 	$result = &js_ready($result);
1.315     albertel 8219:     }
1.335     albertel 8220: 
1.320     albertel 8221:     if ($args->{'html_encode'}) {
                   8222: 	$result = &html_encode($result);
                   8223:     }
1.335     albertel 8224: 
1.315     albertel 8225:     return $result;
                   8226: }
                   8227: 
1.1034    www      8228: sub wishlist_window {
                   8229:     return(<<'ENDWISHLIST');
1.1046    raeburn  8230: <script type="text/javascript">
1.1034    www      8231: // <![CDATA[
                   8232: // <!-- BEGIN LON-CAPA Internal
                   8233: function set_wishlistlink(title, path) {
                   8234:     if (!title) {
                   8235:         title = document.title;
                   8236:         title = title.replace(/^LON-CAPA /,'');
                   8237:     }
1.1175    raeburn  8238:     title = encodeURIComponent(title);
1.1203    raeburn  8239:     title = title.replace("'","\\\'");
1.1034    www      8240:     if (!path) {
                   8241:         path = location.pathname;
                   8242:     }
1.1175    raeburn  8243:     path = encodeURIComponent(path);
1.1203    raeburn  8244:     path = path.replace("'","\\\'");
1.1034    www      8245:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8246:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8247: }
                   8248: // END LON-CAPA Internal -->
                   8249: // ]]>
                   8250: </script>
                   8251: ENDWISHLIST
                   8252: }
                   8253: 
1.1030    www      8254: sub modal_window {
                   8255:     return(<<'ENDMODAL');
1.1046    raeburn  8256: <script type="text/javascript">
1.1030    www      8257: // <![CDATA[
                   8258: // <!-- BEGIN LON-CAPA Internal
                   8259: var modalWindow = {
                   8260: 	parent:"body",
                   8261: 	windowId:null,
                   8262: 	content:null,
                   8263: 	width:null,
                   8264: 	height:null,
                   8265: 	close:function()
                   8266: 	{
                   8267: 	        $(".LCmodal-window").remove();
                   8268: 	        $(".LCmodal-overlay").remove();
                   8269: 	},
                   8270: 	open:function()
                   8271: 	{
                   8272: 		var modal = "";
                   8273: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8274: 		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;\">";
                   8275: 		modal += this.content;
                   8276: 		modal += "</div>";	
                   8277: 
                   8278: 		$(this.parent).append(modal);
                   8279: 
                   8280: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8281: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8282: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8283: 	}
                   8284: };
1.1140    raeburn  8285: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8286: 	{
1.1203    raeburn  8287:                 source = source.replace("'","&#39;");
1.1030    www      8288: 		modalWindow.windowId = "myModal";
                   8289: 		modalWindow.width = width;
                   8290: 		modalWindow.height = height;
1.1196    raeburn  8291: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8292: 		modalWindow.open();
1.1208    raeburn  8293: 	};
1.1030    www      8294: // END LON-CAPA Internal -->
                   8295: // ]]>
                   8296: </script>
                   8297: ENDMODAL
                   8298: }
                   8299: 
                   8300: sub modal_link {
1.1140    raeburn  8301:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8302:     unless ($width) { $width=480; }
                   8303:     unless ($height) { $height=400; }
1.1031    www      8304:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8305:     unless ($transparency) { $transparency='true'; }
                   8306: 
1.1074    raeburn  8307:     my $target_attr;
                   8308:     if (defined($target)) {
                   8309:         $target_attr = 'target="'.$target.'"';
                   8310:     }
                   8311:     return <<"ENDLINK";
1.1140    raeburn  8312: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8313:            $linktext</a>
                   8314: ENDLINK
1.1030    www      8315: }
                   8316: 
1.1032    www      8317: sub modal_adhoc_script {
                   8318:     my ($funcname,$width,$height,$content)=@_;
                   8319:     return (<<ENDADHOC);
1.1046    raeburn  8320: <script type="text/javascript">
1.1032    www      8321: // <![CDATA[
                   8322:         var $funcname = function()
                   8323:         {
                   8324:                 modalWindow.windowId = "myModal";
                   8325:                 modalWindow.width = $width;
                   8326:                 modalWindow.height = $height;
                   8327:                 modalWindow.content = '$content';
                   8328:                 modalWindow.open();
                   8329:         };  
                   8330: // ]]>
                   8331: </script>
                   8332: ENDADHOC
                   8333: }
                   8334: 
1.1041    www      8335: sub modal_adhoc_inner {
                   8336:     my ($funcname,$width,$height,$content)=@_;
                   8337:     my $innerwidth=$width-20;
                   8338:     $content=&js_ready(
1.1140    raeburn  8339:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8340:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8341:                  $content.
1.1041    www      8342:                  &end_scrollbox().
1.1140    raeburn  8343:                  &end_page()
1.1041    www      8344:              );
                   8345:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8346: }
                   8347: 
                   8348: sub modal_adhoc_window {
                   8349:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8350:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8351:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8352: }
                   8353: 
                   8354: sub modal_adhoc_launch {
                   8355:     my ($funcname,$width,$height,$content)=@_;
                   8356:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8357: <script type="text/javascript">
                   8358: // <![CDATA[
                   8359: $funcname();
                   8360: // ]]>
                   8361: </script>
                   8362: ENDLAUNCH
                   8363: }
                   8364: 
                   8365: sub modal_adhoc_close {
                   8366:     return (<<ENDCLOSE);
                   8367: <script type="text/javascript">
                   8368: // <![CDATA[
                   8369: modalWindow.close();
                   8370: // ]]>
                   8371: </script>
                   8372: ENDCLOSE
                   8373: }
                   8374: 
1.1038    www      8375: sub togglebox_script {
                   8376:    return(<<ENDTOGGLE);
                   8377: <script type="text/javascript"> 
                   8378: // <![CDATA[
                   8379: function LCtoggleDisplay(id,hidetext,showtext) {
                   8380:    link = document.getElementById(id + "link").childNodes[0];
                   8381:    with (document.getElementById(id).style) {
                   8382:       if (display == "none" ) {
                   8383:           display = "inline";
                   8384:           link.nodeValue = hidetext;
                   8385:         } else {
                   8386:           display = "none";
                   8387:           link.nodeValue = showtext;
                   8388:        }
                   8389:    }
                   8390: }
                   8391: // ]]>
                   8392: </script>
                   8393: ENDTOGGLE
                   8394: }
                   8395: 
1.1039    www      8396: sub start_togglebox {
                   8397:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8398:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8399:     unless ($showtext) { $showtext=&mt('show'); }
                   8400:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8401:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8402:     return &start_data_table().
                   8403:            &start_data_table_header_row().
                   8404:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8405:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8406:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8407:            &end_data_table_header_row().
                   8408:            '<tr id="'.$id.'" style="display:none""><td>';
                   8409: }
                   8410: 
                   8411: sub end_togglebox {
                   8412:     return '</td></tr>'.&end_data_table();
                   8413: }
                   8414: 
1.1041    www      8415: sub LCprogressbar_script {
1.1045    www      8416:    my ($id)=@_;
1.1041    www      8417:    return(<<ENDPROGRESS);
                   8418: <script type="text/javascript">
                   8419: // <![CDATA[
1.1045    www      8420: \$('#progressbar$id').progressbar({
1.1041    www      8421:   value: 0,
                   8422:   change: function(event, ui) {
                   8423:     var newVal = \$(this).progressbar('option', 'value');
                   8424:     \$('.pblabel', this).text(LCprogressTxt);
                   8425:   }
                   8426: });
                   8427: // ]]>
                   8428: </script>
                   8429: ENDPROGRESS
                   8430: }
                   8431: 
                   8432: sub LCprogressbarUpdate_script {
                   8433:    return(<<ENDPROGRESSUPDATE);
                   8434: <style type="text/css">
                   8435: .ui-progressbar { position:relative; }
                   8436: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8437: </style>
                   8438: <script type="text/javascript">
                   8439: // <![CDATA[
1.1045    www      8440: var LCprogressTxt='---';
                   8441: 
                   8442: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8443:    LCprogressTxt=progresstext;
1.1045    www      8444:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8445: }
                   8446: // ]]>
                   8447: </script>
                   8448: ENDPROGRESSUPDATE
                   8449: }
                   8450: 
1.1042    www      8451: my $LClastpercent;
1.1045    www      8452: my $LCidcnt;
                   8453: my $LCcurrentid;
1.1042    www      8454: 
1.1041    www      8455: sub LCprogressbar {
1.1042    www      8456:     my ($r)=(@_);
                   8457:     $LClastpercent=0;
1.1045    www      8458:     $LCidcnt++;
                   8459:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8460:     my $starting=&mt('Starting');
                   8461:     my $content=(<<ENDPROGBAR);
1.1045    www      8462:   <div id="progressbar$LCcurrentid">
1.1041    www      8463:     <span class="pblabel">$starting</span>
                   8464:   </div>
                   8465: ENDPROGBAR
1.1045    www      8466:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8467: }
                   8468: 
                   8469: sub LCprogressbarUpdate {
1.1042    www      8470:     my ($r,$val,$text)=@_;
                   8471:     unless ($val) { 
                   8472:        if ($LClastpercent) {
                   8473:            $val=$LClastpercent;
                   8474:        } else {
                   8475:            $val=0;
                   8476:        }
                   8477:     }
1.1041    www      8478:     if ($val<0) { $val=0; }
                   8479:     if ($val>100) { $val=0; }
1.1042    www      8480:     $LClastpercent=$val;
1.1041    www      8481:     unless ($text) { $text=$val.'%'; }
                   8482:     $text=&js_ready($text);
1.1044    www      8483:     &r_print($r,<<ENDUPDATE);
1.1041    www      8484: <script type="text/javascript">
                   8485: // <![CDATA[
1.1045    www      8486: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8487: // ]]>
                   8488: </script>
                   8489: ENDUPDATE
1.1035    www      8490: }
                   8491: 
1.1042    www      8492: sub LCprogressbarClose {
                   8493:     my ($r)=@_;
                   8494:     $LClastpercent=0;
1.1044    www      8495:     &r_print($r,<<ENDCLOSE);
1.1042    www      8496: <script type="text/javascript">
                   8497: // <![CDATA[
1.1045    www      8498: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8499: // ]]>
                   8500: </script>
                   8501: ENDCLOSE
1.1044    www      8502: }
                   8503: 
                   8504: sub r_print {
                   8505:     my ($r,$to_print)=@_;
                   8506:     if ($r) {
                   8507:       $r->print($to_print);
                   8508:       $r->rflush();
                   8509:     } else {
                   8510:       print($to_print);
                   8511:     }
1.1042    www      8512: }
                   8513: 
1.320     albertel 8514: sub html_encode {
                   8515:     my ($result) = @_;
                   8516: 
1.322     albertel 8517:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8518:     
                   8519:     return $result;
                   8520: }
1.1044    www      8521: 
1.317     albertel 8522: sub js_ready {
                   8523:     my ($result) = @_;
                   8524: 
1.323     albertel 8525:     $result =~ s/[\n\r]/ /xmsg;
                   8526:     $result =~ s/\\/\\\\/xmsg;
                   8527:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8528:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8529:     
                   8530:     return $result;
                   8531: }
                   8532: 
1.315     albertel 8533: sub validate_page {
                   8534:     if (  exists($env{'internal.start_page'})
1.316     albertel 8535: 	  &&     $env{'internal.start_page'} > 1) {
                   8536: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8537: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8538: 				 $ENV{'request.filename'});
1.315     albertel 8539:     }
                   8540:     if (  exists($env{'internal.end_page'})
1.316     albertel 8541: 	  &&     $env{'internal.end_page'} > 1) {
                   8542: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8543: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8544: 				 $env{'request.filename'});
1.315     albertel 8545:     }
                   8546:     if (     exists($env{'internal.start_page'})
                   8547: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8548: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8549: 				 $env{'request.filename'});
1.315     albertel 8550:     }
                   8551:     if (   ! exists($env{'internal.start_page'})
                   8552: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8553: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8554: 				 $env{'request.filename'});
1.315     albertel 8555:     }
1.306     albertel 8556: }
1.315     albertel 8557: 
1.996     www      8558: 
                   8559: sub start_scrollbox {
1.1140    raeburn  8560:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8561:     unless ($outerwidth) { $outerwidth='520px'; }
                   8562:     unless ($width) { $width='500px'; }
                   8563:     unless ($height) { $height='200px'; }
1.1075    raeburn  8564:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8565:     if ($id ne '') {
1.1140    raeburn  8566:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  8567:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8568:     }
1.1075    raeburn  8569:     if ($bgcolor ne '') {
                   8570:         $tdcol = "background-color: $bgcolor;";
                   8571:     }
1.1137    raeburn  8572:     my $nicescroll_js;
                   8573:     if ($env{'browser.mobile'}) {
1.1140    raeburn  8574:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8575:     }
                   8576:     return <<"END";
                   8577: $nicescroll_js
                   8578: 
                   8579: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   8580: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   8581: END
                   8582: }
                   8583: 
                   8584: sub end_scrollbox {
                   8585:     return '</div></td></tr></table>';
                   8586: }
                   8587: 
                   8588: sub nicescroll_javascript {
                   8589:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8590:     my %options;
                   8591:     if (ref($cursor) eq 'HASH') {
                   8592:         %options = %{$cursor};
                   8593:     }
                   8594:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8595:         $options{'railalign'} = 'left';
                   8596:     }
                   8597:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8598:         my $function  = &get_users_function();
                   8599:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  8600:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  8601:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  8602:         }
1.1140    raeburn  8603:     }
                   8604:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8605:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  8606:             $options{'cursoropacity'}='1.0';
                   8607:         }
1.1140    raeburn  8608:     } else {
                   8609:         $options{'cursoropacity'}='1.0';
                   8610:     }
                   8611:     if ($options{'cursorfixedheight'} eq 'none') {
                   8612:         delete($options{'cursorfixedheight'});
                   8613:     } else {
                   8614:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8615:     }
                   8616:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8617:         delete($options{'railoffset'});
                   8618:     }
                   8619:     my @niceoptions;
                   8620:     while (my($key,$value) = each(%options)) {
                   8621:         if ($value =~ /^\{.+\}$/) {
                   8622:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  8623:         } else {
1.1140    raeburn  8624:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  8625:         }
1.1140    raeburn  8626:     }
                   8627:     my $nicescroll_js = '
1.1137    raeburn  8628: $(document).ready(
1.1140    raeburn  8629:       function() {
                   8630:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8631:       }
1.1137    raeburn  8632: );
                   8633: ';
1.1140    raeburn  8634:     if ($framecheck) {
                   8635:         $nicescroll_js .= '
                   8636: function expand_div(caller) {
                   8637:     if (top === self) {
                   8638:         document.getElementById("'.$id.'").style.width = "auto";
                   8639:         document.getElementById("'.$id.'").style.height = "auto";
                   8640:     } else {
                   8641:         try {
                   8642:             if (parent.frames) {
                   8643:                 if (parent.frames.length > 1) {
                   8644:                     var framesrc = parent.frames[1].location.href;
                   8645:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8646:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8647:                         document.getElementById("'.$id.'").style.width = "auto";
                   8648:                         document.getElementById("'.$id.'").style.height = "auto";
                   8649:                     }
                   8650:                 }
                   8651:             }
                   8652:         } catch (e) {
                   8653:             return;
                   8654:         }
1.1137    raeburn  8655:     }
1.1140    raeburn  8656:     return;
1.996     www      8657: }
1.1140    raeburn  8658: ';
                   8659:     }
                   8660:     if ($needjsready) {
                   8661:         $nicescroll_js = '
                   8662: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8663:     } else {
                   8664:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8665:     }
                   8666:     return $nicescroll_js;
1.996     www      8667: }
                   8668: 
1.318     albertel 8669: sub simple_error_page {
1.1150    bisitz   8670:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  8671:     if (ref($args) eq 'HASH') {
                   8672:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8673:     } else {
                   8674:         $msg = &mt($msg);
                   8675:     }
1.1150    bisitz   8676: 
1.318     albertel 8677:     my $page =
                   8678: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   8679: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8680: 	&Apache::loncommon::end_page();
                   8681:     if (ref($r)) {
                   8682: 	$r->print($page);
1.327     albertel 8683: 	return;
1.318     albertel 8684:     }
                   8685:     return $page;
                   8686: }
1.347     albertel 8687: 
                   8688: {
1.610     albertel 8689:     my @row_count;
1.961     onken    8690: 
                   8691:     sub start_data_table_count {
                   8692:         unshift(@row_count, 0);
                   8693:         return;
                   8694:     }
                   8695: 
                   8696:     sub end_data_table_count {
                   8697:         shift(@row_count);
                   8698:         return;
                   8699:     }
                   8700: 
1.347     albertel 8701:     sub start_data_table {
1.1018    raeburn  8702: 	my ($add_class,$id) = @_;
1.422     albertel 8703: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8704:         my $table_id;
                   8705:         if (defined($id)) {
                   8706:             $table_id = ' id="'.$id.'"';
                   8707:         }
1.961     onken    8708: 	&start_data_table_count();
1.1018    raeburn  8709: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8710:     }
                   8711: 
                   8712:     sub end_data_table {
1.961     onken    8713: 	&end_data_table_count();
1.389     albertel 8714: 	return '</table>'."\n";;
1.347     albertel 8715:     }
                   8716: 
                   8717:     sub start_data_table_row {
1.974     wenzelju 8718: 	my ($add_class, $id) = @_;
1.610     albertel 8719: 	$row_count[0]++;
                   8720: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8721: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8722:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8723:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8724:     }
1.471     banghart 8725:     
                   8726:     sub continue_data_table_row {
1.974     wenzelju 8727: 	my ($add_class, $id) = @_;
1.610     albertel 8728: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8729: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8730:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8731:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8732:     }
1.347     albertel 8733: 
                   8734:     sub end_data_table_row {
1.389     albertel 8735: 	return '</tr>'."\n";;
1.347     albertel 8736:     }
1.367     www      8737: 
1.421     albertel 8738:     sub start_data_table_empty_row {
1.707     bisitz   8739: #	$row_count[0]++;
1.421     albertel 8740: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8741:     }
                   8742: 
                   8743:     sub end_data_table_empty_row {
                   8744: 	return '</tr>'."\n";;
                   8745:     }
                   8746: 
1.367     www      8747:     sub start_data_table_header_row {
1.389     albertel 8748: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8749:     }
                   8750: 
                   8751:     sub end_data_table_header_row {
1.389     albertel 8752: 	return '</tr>'."\n";;
1.367     www      8753:     }
1.890     droeschl 8754: 
                   8755:     sub data_table_caption {
                   8756:         my $caption = shift;
                   8757:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8758:     }
1.347     albertel 8759: }
                   8760: 
1.548     albertel 8761: =pod
                   8762: 
                   8763: =item * &inhibit_menu_check($arg)
                   8764: 
                   8765: Checks for a inhibitmenu state and generates output to preserve it
                   8766: 
                   8767: Inputs:         $arg - can be any of
                   8768:                      - undef - in which case the return value is a string 
                   8769:                                to add  into arguments list of a uri
                   8770:                      - 'input' - in which case the return value is a HTML
                   8771:                                  <form> <input> field of type hidden to
                   8772:                                  preserve the value
                   8773:                      - a url - in which case the return value is the url with
                   8774:                                the neccesary cgi args added to preserve the
                   8775:                                inhibitmenu state
                   8776:                      - a ref to a url - no return value, but the string is
                   8777:                                         updated to include the neccessary cgi
                   8778:                                         args to preserve the inhibitmenu state
                   8779: 
                   8780: =cut
                   8781: 
                   8782: sub inhibit_menu_check {
                   8783:     my ($arg) = @_;
                   8784:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8785:     if ($arg eq 'input') {
                   8786: 	if ($env{'form.inhibitmenu'}) {
                   8787: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8788: 	} else {
                   8789: 	    return
                   8790: 	}
                   8791:     }
                   8792:     if ($env{'form.inhibitmenu'}) {
                   8793: 	if (ref($arg)) {
                   8794: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8795: 	} elsif ($arg eq '') {
                   8796: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8797: 	} else {
                   8798: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8799: 	}
                   8800:     }
                   8801:     if (!ref($arg)) {
                   8802: 	return $arg;
                   8803:     }
                   8804: }
                   8805: 
1.251     albertel 8806: ###############################################
1.182     matthew  8807: 
                   8808: =pod
                   8809: 
1.549     albertel 8810: =back
                   8811: 
                   8812: =head1 User Information Routines
                   8813: 
                   8814: =over 4
                   8815: 
1.405     albertel 8816: =item * &get_users_function()
1.182     matthew  8817: 
                   8818: Used by &bodytag to determine the current users primary role.
                   8819: Returns either 'student','coordinator','admin', or 'author'.
                   8820: 
                   8821: =cut
                   8822: 
                   8823: ###############################################
                   8824: sub get_users_function {
1.815     tempelho 8825:     my $function = 'norole';
1.818     tempelho 8826:     if ($env{'request.role'}=~/^(st)/) {
                   8827:         $function='student';
                   8828:     }
1.907     raeburn  8829:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8830:         $function='coordinator';
                   8831:     }
1.258     albertel 8832:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8833:         $function='admin';
                   8834:     }
1.826     bisitz   8835:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8836:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8837:         $function='author';
                   8838:     }
                   8839:     return $function;
1.54      www      8840: }
1.99      www      8841: 
                   8842: ###############################################
                   8843: 
1.233     raeburn  8844: =pod
                   8845: 
1.821     raeburn  8846: =item * &show_course()
                   8847: 
                   8848: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8849: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8850: 
                   8851: Inputs:
                   8852: None
                   8853: 
                   8854: Outputs:
                   8855: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8856: 
                   8857: =cut
                   8858: 
                   8859: ###############################################
                   8860: sub show_course {
                   8861:     my $course = !$env{'user.adv'};
                   8862:     if (!$env{'user.adv'}) {
                   8863:         foreach my $env (keys(%env)) {
                   8864:             next if ($env !~ m/^user\.priv\./);
                   8865:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8866:                 $course = 0;
                   8867:                 last;
                   8868:             }
                   8869:         }
                   8870:     }
                   8871:     return $course;
                   8872: }
                   8873: 
                   8874: ###############################################
                   8875: 
                   8876: =pod
                   8877: 
1.542     raeburn  8878: =item * &check_user_status()
1.274     raeburn  8879: 
                   8880: Determines current status of supplied role for a
                   8881: specific user. Roles can be active, previous or future.
                   8882: 
                   8883: Inputs: 
                   8884: user's domain, user's username, course's domain,
1.375     raeburn  8885: course's number, optional section ID.
1.274     raeburn  8886: 
                   8887: Outputs:
                   8888: role status: active, previous or future. 
                   8889: 
                   8890: =cut
                   8891: 
                   8892: sub check_user_status {
1.412     raeburn  8893:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8894:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  8895:     my @uroles = keys(%userinfo);
1.274     raeburn  8896:     my $srchstr;
                   8897:     my $active_chk = 'none';
1.412     raeburn  8898:     my $now = time;
1.274     raeburn  8899:     if (@uroles > 0) {
1.908     raeburn  8900:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8901:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8902:         } else {
1.412     raeburn  8903:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8904:         }
                   8905:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8906:             my $role_end = 0;
                   8907:             my $role_start = 0;
                   8908:             $active_chk = 'active';
1.412     raeburn  8909:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8910:                 $role_end = $1;
                   8911:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8912:                     $role_start = $1;
1.274     raeburn  8913:                 }
                   8914:             }
                   8915:             if ($role_start > 0) {
1.412     raeburn  8916:                 if ($now < $role_start) {
1.274     raeburn  8917:                     $active_chk = 'future';
                   8918:                 }
                   8919:             }
                   8920:             if ($role_end > 0) {
1.412     raeburn  8921:                 if ($now > $role_end) {
1.274     raeburn  8922:                     $active_chk = 'previous';
                   8923:                 }
                   8924:             }
                   8925:         }
                   8926:     }
                   8927:     return $active_chk;
                   8928: }
                   8929: 
                   8930: ###############################################
                   8931: 
                   8932: =pod
                   8933: 
1.405     albertel 8934: =item * &get_sections()
1.233     raeburn  8935: 
                   8936: Determines all the sections for a course including
                   8937: sections with students and sections containing other roles.
1.419     raeburn  8938: Incoming parameters: 
                   8939: 
                   8940: 1. domain
                   8941: 2. course number 
                   8942: 3. reference to array containing roles for which sections should 
                   8943: be gathered (optional).
                   8944: 4. reference to array containing status types for which sections 
                   8945: should be gathered (optional).
                   8946: 
                   8947: If the third argument is undefined, sections are gathered for any role. 
                   8948: If the fourth argument is undefined, sections are gathered for any status.
                   8949: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8950:  
1.374     raeburn  8951: Returns section hash (keys are section IDs, values are
                   8952: number of users in each section), subject to the
1.419     raeburn  8953: optional roles filter, optional status filter 
1.233     raeburn  8954: 
                   8955: =cut
                   8956: 
                   8957: ###############################################
                   8958: sub get_sections {
1.419     raeburn  8959:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8960:     if (!defined($cdom) || !defined($cnum)) {
                   8961:         my $cid =  $env{'request.course.id'};
                   8962: 
                   8963: 	return if (!defined($cid));
                   8964: 
                   8965:         $cdom = $env{'course.'.$cid.'.domain'};
                   8966:         $cnum = $env{'course.'.$cid.'.num'};
                   8967:     }
                   8968: 
                   8969:     my %sectioncount;
1.419     raeburn  8970:     my $now = time;
1.240     albertel 8971: 
1.1118    raeburn  8972:     my $check_students = 1;
                   8973:     my $only_students = 0;
                   8974:     if (ref($possible_roles) eq 'ARRAY') {
                   8975:         if (grep(/^st$/,@{$possible_roles})) {
                   8976:             if (@{$possible_roles} == 1) {
                   8977:                 $only_students = 1;
                   8978:             }
                   8979:         } else {
                   8980:             $check_students = 0;
                   8981:         }
                   8982:     }
                   8983: 
                   8984:     if ($check_students) { 
1.276     albertel 8985: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8986: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8987: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8988:         my $start_index = &Apache::loncoursedata::CL_START();
                   8989:         my $end_index = &Apache::loncoursedata::CL_END();
                   8990:         my $status;
1.366     albertel 8991: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8992: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8993: 				                     $data->[$status_index],
                   8994:                                                      $data->[$start_index],
                   8995:                                                      $data->[$end_index]);
                   8996:             if ($stu_status eq 'Active') {
                   8997:                 $status = 'active';
                   8998:             } elsif ($end < $now) {
                   8999:                 $status = 'previous';
                   9000:             } elsif ($start > $now) {
                   9001:                 $status = 'future';
                   9002:             } 
                   9003: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9004:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9005:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9006: 		    $sectioncount{$section}++;
                   9007:                 }
1.240     albertel 9008: 	    }
                   9009: 	}
                   9010:     }
1.1118    raeburn  9011:     if ($only_students) {
                   9012:         return %sectioncount;
                   9013:     }
1.240     albertel 9014:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9015:     foreach my $user (sort(keys(%courseroles))) {
                   9016: 	if ($user !~ /^(\w{2})/) { next; }
                   9017: 	my ($role) = ($user =~ /^(\w{2})/);
                   9018: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9019: 	my ($section,$status);
1.240     albertel 9020: 	if ($role eq 'cr' &&
                   9021: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9022: 	    $section=$1;
                   9023: 	}
                   9024: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9025: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9026:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9027:         if ($end == -1 && $start == -1) {
                   9028:             next; #deleted role
                   9029:         }
                   9030:         if (!defined($possible_status)) { 
                   9031:             $sectioncount{$section}++;
                   9032:         } else {
                   9033:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9034:                 $status = 'active';
                   9035:             } elsif ($end < $now) {
                   9036:                 $status = 'future';
                   9037:             } elsif ($start > $now) {
                   9038:                 $status = 'previous';
                   9039:             }
                   9040:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9041:                 $sectioncount{$section}++;
                   9042:             }
                   9043:         }
1.233     raeburn  9044:     }
1.366     albertel 9045:     return %sectioncount;
1.233     raeburn  9046: }
                   9047: 
1.274     raeburn  9048: ###############################################
1.294     raeburn  9049: 
                   9050: =pod
1.405     albertel 9051: 
                   9052: =item * &get_course_users()
                   9053: 
1.275     raeburn  9054: Retrieves usernames:domains for users in the specified course
                   9055: with specific role(s), and access status. 
                   9056: 
                   9057: Incoming parameters:
1.277     albertel 9058: 1. course domain
                   9059: 2. course number
                   9060: 3. access status: users must have - either active, 
1.275     raeburn  9061: previous, future, or all.
1.277     albertel 9062: 4. reference to array of permissible roles
1.288     raeburn  9063: 5. reference to array of section restrictions (optional)
                   9064: 6. reference to results object (hash of hashes).
                   9065: 7. reference to optional userdata hash
1.609     raeburn  9066: 8. reference to optional statushash
1.630     raeburn  9067: 9. flag if privileged users (except those set to unhide in
                   9068:    course settings) should be excluded    
1.609     raeburn  9069: Keys of top level results hash are roles.
1.275     raeburn  9070: Keys of inner hashes are username:domain, with 
                   9071: values set to access type.
1.288     raeburn  9072: Optional userdata hash returns an array with arguments in the 
                   9073: same order as loncoursedata::get_classlist() for student data.
                   9074: 
1.609     raeburn  9075: Optional statushash returns
                   9076: 
1.288     raeburn  9077: Entries for end, start, section and status are blank because
                   9078: of the possibility of multiple values for non-student roles.
                   9079: 
1.275     raeburn  9080: =cut
1.405     albertel 9081: 
1.275     raeburn  9082: ###############################################
1.405     albertel 9083: 
1.275     raeburn  9084: sub get_course_users {
1.630     raeburn  9085:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9086:     my %idx = ();
1.419     raeburn  9087:     my %seclists;
1.288     raeburn  9088: 
                   9089:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9090:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9091:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9092:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9093:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9094:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9095:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9096:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9097: 
1.290     albertel 9098:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9099:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9100:         my $now = time;
1.277     albertel 9101:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9102:             my $match = 0;
1.412     raeburn  9103:             my $secmatch = 0;
1.419     raeburn  9104:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9105:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9106:             if ($section eq '') {
                   9107:                 $section = 'none';
                   9108:             }
1.291     albertel 9109:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9110:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9111:                     $secmatch = 1;
                   9112:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9113:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9114:                         $secmatch = 1;
                   9115:                     }
                   9116:                 } else {  
1.419     raeburn  9117: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9118: 		        $secmatch = 1;
                   9119:                     }
1.290     albertel 9120: 		}
1.412     raeburn  9121:                 if (!$secmatch) {
                   9122:                     next;
                   9123:                 }
1.419     raeburn  9124:             }
1.275     raeburn  9125:             if (defined($$types{'active'})) {
1.288     raeburn  9126:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9127:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9128:                     $match = 1;
1.275     raeburn  9129:                 }
                   9130:             }
                   9131:             if (defined($$types{'previous'})) {
1.609     raeburn  9132:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9133:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9134:                     $match = 1;
1.275     raeburn  9135:                 }
                   9136:             }
                   9137:             if (defined($$types{'future'})) {
1.609     raeburn  9138:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9139:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9140:                     $match = 1;
1.275     raeburn  9141:                 }
                   9142:             }
1.609     raeburn  9143:             if ($match) {
                   9144:                 push(@{$seclists{$student}},$section);
                   9145:                 if (ref($userdata) eq 'HASH') {
                   9146:                     $$userdata{$student} = $$classlist{$student};
                   9147:                 }
                   9148:                 if (ref($statushash) eq 'HASH') {
                   9149:                     $statushash->{$student}{'st'}{$section} = $status;
                   9150:                 }
1.288     raeburn  9151:             }
1.275     raeburn  9152:         }
                   9153:     }
1.412     raeburn  9154:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9155:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9156:         my $now = time;
1.609     raeburn  9157:         my %displaystatus = ( previous => 'Expired',
                   9158:                               active   => 'Active',
                   9159:                               future   => 'Future',
                   9160:                             );
1.1121    raeburn  9161:         my (%nothide,@possdoms);
1.630     raeburn  9162:         if ($hidepriv) {
                   9163:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9164:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9165:                 if ($user !~ /:/) {
                   9166:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9167:                 } else {
                   9168:                     $nothide{$user} = 1;
                   9169:                 }
                   9170:             }
1.1121    raeburn  9171:             my @possdoms = ($cdom);
                   9172:             if ($coursehash{'checkforpriv'}) {
                   9173:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9174:             }
1.630     raeburn  9175:         }
1.439     raeburn  9176:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9177:             my $match = 0;
1.412     raeburn  9178:             my $secmatch = 0;
1.439     raeburn  9179:             my $status;
1.412     raeburn  9180:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9181:             $user =~ s/:$//;
1.439     raeburn  9182:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9183:             if ($end == -1 || $start == -1) {
                   9184:                 next;
                   9185:             }
                   9186:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9187:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9188:                 my ($uname,$udom) = split(/:/,$user);
                   9189:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9190:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9191:                         $secmatch = 1;
                   9192:                     } elsif ($usec eq '') {
1.420     albertel 9193:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9194:                             $secmatch = 1;
                   9195:                         }
                   9196:                     } else {
                   9197:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9198:                             $secmatch = 1;
                   9199:                         }
                   9200:                     }
                   9201:                     if (!$secmatch) {
                   9202:                         next;
                   9203:                     }
1.288     raeburn  9204:                 }
1.419     raeburn  9205:                 if ($usec eq '') {
                   9206:                     $usec = 'none';
                   9207:                 }
1.275     raeburn  9208:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9209:                     if ($hidepriv) {
1.1121    raeburn  9210:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9211:                             (!$nothide{$uname.':'.$udom})) {
                   9212:                             next;
                   9213:                         }
                   9214:                     }
1.503     raeburn  9215:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9216:                         $status = 'previous';
                   9217:                     } elsif ($start > $now) {
                   9218:                         $status = 'future';
                   9219:                     } else {
                   9220:                         $status = 'active';
                   9221:                     }
1.277     albertel 9222:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9223:                         if ($status eq $type) {
1.420     albertel 9224:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9225:                                 push(@{$$users{$role}{$user}},$type);
                   9226:                             }
1.288     raeburn  9227:                             $match = 1;
                   9228:                         }
                   9229:                     }
1.419     raeburn  9230:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9231:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9232: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9233:                         }
1.420     albertel 9234:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9235:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9236:                         }
1.609     raeburn  9237:                         if (ref($statushash) eq 'HASH') {
                   9238:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9239:                         }
1.275     raeburn  9240:                     }
                   9241:                 }
                   9242:             }
                   9243:         }
1.290     albertel 9244:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9245:             if ((defined($cdom)) && (defined($cnum))) {
                   9246:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9247:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9248:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9249:                     next if ($owner eq '');
                   9250:                     my ($ownername,$ownerdom);
                   9251:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9252:                         $ownername = $1;
                   9253:                         $ownerdom = $2;
                   9254:                     } else {
                   9255:                         $ownername = $owner;
                   9256:                         $ownerdom = $cdom;
                   9257:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9258:                     }
                   9259:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9260:                     if (defined($userdata) && 
1.609     raeburn  9261: 			!exists($$userdata{$owner})) {
                   9262: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9263:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9264:                             push(@{$seclists{$owner}},'none');
                   9265:                         }
                   9266:                         if (ref($statushash) eq 'HASH') {
                   9267:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9268:                         }
1.290     albertel 9269: 		    }
1.279     raeburn  9270:                 }
                   9271:             }
                   9272:         }
1.419     raeburn  9273:         foreach my $user (keys(%seclists)) {
                   9274:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9275:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9276:         }
1.275     raeburn  9277:     }
                   9278:     return;
                   9279: }
                   9280: 
1.288     raeburn  9281: sub get_user_info {
                   9282:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9283:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9284: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9285:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9286:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9287:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9288:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9289:     return;
                   9290: }
1.275     raeburn  9291: 
1.472     raeburn  9292: ###############################################
                   9293: 
                   9294: =pod
                   9295: 
                   9296: =item * &get_user_quota()
                   9297: 
1.1134    raeburn  9298: Retrieves quota assigned for storage of user files.
                   9299: Default is to report quota for portfolio files.
1.472     raeburn  9300: 
                   9301: Incoming parameters:
                   9302: 1. user's username
                   9303: 2. user's domain
1.1134    raeburn  9304: 3. quota name - portfolio, author, or course
1.1136    raeburn  9305:    (if no quota name provided, defaults to portfolio).
1.1165    raeburn  9306: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1136    raeburn  9307:    course
1.472     raeburn  9308: 
                   9309: Returns:
1.1163    raeburn  9310: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9311: 2. (Optional) Type of setting: custom or default
                   9312:    (individually assigned or default for user's 
                   9313:    institutional status).
                   9314: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9315:    or student - types as defined in localenroll::inst_usertypes 
                   9316:    for user's domain, which determines default quota for user.
                   9317: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9318: 
                   9319: If a value has been stored in the user's environment, 
1.536     raeburn  9320: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9321: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9322: 
                   9323: =cut
                   9324: 
                   9325: ###############################################
                   9326: 
                   9327: 
                   9328: sub get_user_quota {
1.1136    raeburn  9329:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9330:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9331:     if (!defined($udom)) {
                   9332:         $udom = $env{'user.domain'};
                   9333:     }
                   9334:     if (!defined($uname)) {
                   9335:         $uname = $env{'user.name'};
                   9336:     }
                   9337:     if (($udom eq '' || $uname eq '') ||
                   9338:         ($udom eq 'public') && ($uname eq 'public')) {
                   9339:         $quota = 0;
1.536     raeburn  9340:         $quotatype = 'default';
                   9341:         $defquota = 0; 
1.472     raeburn  9342:     } else {
1.536     raeburn  9343:         my $inststatus;
1.1134    raeburn  9344:         if ($quotaname eq 'course') {
                   9345:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9346:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9347:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9348:             } else {
                   9349:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9350:                 $quota = $cenv{'internal.uploadquota'};
                   9351:             }
1.536     raeburn  9352:         } else {
1.1134    raeburn  9353:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9354:                 if ($quotaname eq 'author') {
                   9355:                     $quota = $env{'environment.authorquota'};
                   9356:                 } else {
                   9357:                     $quota = $env{'environment.portfolioquota'};
                   9358:                 }
                   9359:                 $inststatus = $env{'environment.inststatus'};
                   9360:             } else {
                   9361:                 my %userenv = 
                   9362:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9363:                                          'authorquota','inststatus'],$udom,$uname);
                   9364:                 my ($tmp) = keys(%userenv);
                   9365:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9366:                     if ($quotaname eq 'author') {
                   9367:                         $quota = $userenv{'authorquota'};
                   9368:                     } else {
                   9369:                         $quota = $userenv{'portfolioquota'};
                   9370:                     }
                   9371:                     $inststatus = $userenv{'inststatus'};
                   9372:                 } else {
                   9373:                     undef(%userenv);
                   9374:                 }
                   9375:             }
                   9376:         }
                   9377:         if ($quota eq '' || wantarray) {
                   9378:             if ($quotaname eq 'course') {
                   9379:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9380:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
                   9381:                     ($crstype eq 'community') || ($crstype eq 'textbook')) { 
1.1136    raeburn  9382:                     $defquota = $domdefs{$crstype.'quota'};
                   9383:                 }
                   9384:                 if ($defquota eq '') {
                   9385:                     $defquota = 500;
                   9386:                 }
1.1134    raeburn  9387:             } else {
                   9388:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9389:             }
                   9390:             if ($quota eq '') {
                   9391:                 $quota = $defquota;
                   9392:                 $quotatype = 'default';
                   9393:             } else {
                   9394:                 $quotatype = 'custom';
                   9395:             }
1.472     raeburn  9396:         }
                   9397:     }
1.536     raeburn  9398:     if (wantarray) {
                   9399:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9400:     } else {
                   9401:         return $quota;
                   9402:     }
1.472     raeburn  9403: }
                   9404: 
                   9405: ###############################################
                   9406: 
                   9407: =pod
                   9408: 
                   9409: =item * &default_quota()
                   9410: 
1.536     raeburn  9411: Retrieves default quota assigned for storage of user portfolio files,
                   9412: given an (optional) user's institutional status.
1.472     raeburn  9413: 
                   9414: Incoming parameters:
1.1142    raeburn  9415: 
1.472     raeburn  9416: 1. domain
1.536     raeburn  9417: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9418:    status types (e.g., faculty, staff, student etc.)
                   9419:    which apply to the user for whom the default is being retrieved.
                   9420:    If the institutional status string in undefined, the domain
1.1134    raeburn  9421:    default quota will be returned.
                   9422: 3.  quota name - portfolio, author, or course
                   9423:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9424: 
                   9425: Returns:
1.1142    raeburn  9426: 
1.1163    raeburn  9427: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9428: 2. (Optional) institutional type which determined the value of the
                   9429:    default quota.
1.472     raeburn  9430: 
                   9431: If a value has been stored in the domain's configuration db,
                   9432: it will return that, otherwise it returns 20 (for backwards 
                   9433: compatibility with domains which have not set up a configuration
1.1163    raeburn  9434: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9435: 
1.536     raeburn  9436: If the user's status includes multiple types (e.g., staff and student),
                   9437: the largest default quota which applies to the user determines the
                   9438: default quota returned.
                   9439: 
1.472     raeburn  9440: =cut
                   9441: 
                   9442: ###############################################
                   9443: 
                   9444: 
                   9445: sub default_quota {
1.1134    raeburn  9446:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9447:     my ($defquota,$settingstatus);
                   9448:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9449:                                             ['quotas'],$udom);
1.1134    raeburn  9450:     my $key = 'defaultquota';
                   9451:     if ($quotaname eq 'author') {
                   9452:         $key = 'authorquota';
                   9453:     }
1.622     raeburn  9454:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9455:         if ($inststatus ne '') {
1.765     raeburn  9456:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9457:             foreach my $item (@statuses) {
1.1134    raeburn  9458:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9459:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9460:                         if ($defquota eq '') {
1.1134    raeburn  9461:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9462:                             $settingstatus = $item;
1.1134    raeburn  9463:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9464:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9465:                             $settingstatus = $item;
                   9466:                         }
                   9467:                     }
1.1134    raeburn  9468:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9469:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9470:                         if ($defquota eq '') {
                   9471:                             $defquota = $quotahash{'quotas'}{$item};
                   9472:                             $settingstatus = $item;
                   9473:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9474:                             $defquota = $quotahash{'quotas'}{$item};
                   9475:                             $settingstatus = $item;
                   9476:                         }
1.536     raeburn  9477:                     }
                   9478:                 }
                   9479:             }
                   9480:         }
                   9481:         if ($defquota eq '') {
1.1134    raeburn  9482:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9483:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9484:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9485:                 $defquota = $quotahash{'quotas'}{'default'};
                   9486:             }
1.536     raeburn  9487:             $settingstatus = 'default';
1.1139    raeburn  9488:             if ($defquota eq '') {
                   9489:                 if ($quotaname eq 'author') {
                   9490:                     $defquota = 500;
                   9491:                 }
                   9492:             }
1.536     raeburn  9493:         }
                   9494:     } else {
                   9495:         $settingstatus = 'default';
1.1134    raeburn  9496:         if ($quotaname eq 'author') {
                   9497:             $defquota = 500;
                   9498:         } else {
                   9499:             $defquota = 20;
                   9500:         }
1.536     raeburn  9501:     }
                   9502:     if (wantarray) {
                   9503:         return ($defquota,$settingstatus);
1.472     raeburn  9504:     } else {
1.536     raeburn  9505:         return $defquota;
1.472     raeburn  9506:     }
                   9507: }
                   9508: 
1.1135    raeburn  9509: ###############################################
                   9510: 
                   9511: =pod
                   9512: 
1.1136    raeburn  9513: =item * &excess_filesize_warning()
1.1135    raeburn  9514: 
                   9515: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  9516: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  9517: space to be exceeded.
1.1136    raeburn  9518: 
                   9519: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  9520: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  9521: 
1.1165    raeburn  9522: Inputs: 7 
1.1136    raeburn  9523: 1. username or coursenum
1.1135    raeburn  9524: 2. domain
1.1136    raeburn  9525: 3. context ('author' or 'course')
1.1135    raeburn  9526: 4. filename of file for which action is being requested
                   9527: 5. filesize (kB) of file
                   9528: 6. action being taken: copy or upload.
1.1165    raeburn  9529: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1135    raeburn  9530: 
                   9531: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  9532:          otherwise return null.
                   9533: 
                   9534: =back
1.1135    raeburn  9535: 
                   9536: =cut
                   9537: 
1.1136    raeburn  9538: sub excess_filesize_warning {
1.1165    raeburn  9539:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  9540:     my $current_disk_usage = 0;
1.1165    raeburn  9541:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  9542:     if ($context eq 'author') {
                   9543:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9544:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9545:     } else {
                   9546:         foreach my $subdir ('docs','supplemental') {
                   9547:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9548:         }
                   9549:     }
1.1135    raeburn  9550:     $disk_quota = int($disk_quota * 1000);
                   9551:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   9552:         return '<p class="LC_warning">'.
1.1135    raeburn  9553:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   9554:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9555:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  9556:                             $disk_quota,$current_disk_usage).
                   9557:                '</p>';
                   9558:     }
                   9559:     return;
                   9560: }
                   9561: 
                   9562: ###############################################
                   9563: 
                   9564: 
1.1136    raeburn  9565: 
                   9566: 
1.384     raeburn  9567: sub get_secgrprole_info {
                   9568:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9569:     my %sections_count = &get_sections($cdom,$cnum);
                   9570:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9571:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9572:     my @groups = sort(keys(%curr_groups));
                   9573:     my $allroles = [];
                   9574:     my $rolehash;
                   9575:     my $accesshash = {
                   9576:                      active => 'Currently has access',
                   9577:                      future => 'Will have future access',
                   9578:                      previous => 'Previously had access',
                   9579:                   };
                   9580:     if ($needroles) {
                   9581:         $rolehash = {'all' => 'all'};
1.385     albertel 9582:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9583: 	if (&Apache::lonnet::error(%user_roles)) {
                   9584: 	    undef(%user_roles);
                   9585: 	}
                   9586:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9587:             my ($role)=split(/\:/,$item,2);
                   9588:             if ($role eq 'cr') { next; }
                   9589:             if ($role =~ /^cr/) {
                   9590:                 $$rolehash{$role} = (split('/',$role))[3];
                   9591:             } else {
                   9592:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9593:             }
                   9594:         }
                   9595:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9596:             push(@{$allroles},$key);
                   9597:         }
                   9598:         push (@{$allroles},'st');
                   9599:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9600:     }
                   9601:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9602: }
                   9603: 
1.555     raeburn  9604: sub user_picker {
1.994     raeburn  9605:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9606:     my $currdom = $dom;
                   9607:     my %curr_selected = (
                   9608:                         srchin => 'dom',
1.580     raeburn  9609:                         srchby => 'lastname',
1.555     raeburn  9610:                       );
                   9611:     my $srchterm;
1.625     raeburn  9612:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9613:         if ($srch->{'srchby'} ne '') {
                   9614:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9615:         }
                   9616:         if ($srch->{'srchin'} ne '') {
                   9617:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9618:         }
                   9619:         if ($srch->{'srchtype'} ne '') {
                   9620:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9621:         }
                   9622:         if ($srch->{'srchdomain'} ne '') {
                   9623:             $currdom = $srch->{'srchdomain'};
                   9624:         }
                   9625:         $srchterm = $srch->{'srchterm'};
                   9626:     }
1.1222    damieng  9627:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9628:                     'usr'       => 'Search criteria',
1.563     raeburn  9629:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9630:                     'uname'     => 'username',
                   9631:                     'lastname'  => 'last name',
1.555     raeburn  9632:                     'lastfirst' => 'last name, first name',
1.558     albertel 9633:                     'crs'       => 'in this course',
1.576     raeburn  9634:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9635:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9636:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9637:                     'exact'     => 'is',
                   9638:                     'contains'  => 'contains',
1.569     raeburn  9639:                     'begins'    => 'begins with',
1.1222    damieng  9640:                                        );
                   9641:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9642:                     'youm'      => "You must include some text to search for.",
                   9643:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9644:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9645:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9646:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9647:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9648:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9649:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9650:                                        );
1.1222    damieng  9651:     &html_escape(\%html_lt);
                   9652:     &js_escape(\%js_lt);
1.563     raeburn  9653:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9654:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9655: 
                   9656:     my @srchins = ('crs','dom','alc','instd');
                   9657: 
                   9658:     foreach my $option (@srchins) {
                   9659:         # FIXME 'alc' option unavailable until 
                   9660:         #       loncreateuser::print_user_query_page()
                   9661:         #       has been completed.
                   9662:         next if ($option eq 'alc');
1.880     raeburn  9663:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9664:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9665:         if ($curr_selected{'srchin'} eq $option) {
                   9666:             $srchinsel .= ' 
1.1222    damieng  9667:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9668:         } else {
                   9669:             $srchinsel .= '
1.1222    damieng  9670:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9671:         }
1.555     raeburn  9672:     }
1.563     raeburn  9673:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9674: 
                   9675:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9676:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9677:         if ($curr_selected{'srchby'} eq $option) {
                   9678:             $srchbysel .= '
1.1222    damieng  9679:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9680:         } else {
                   9681:             $srchbysel .= '
1.1222    damieng  9682:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9683:          }
                   9684:     }
                   9685:     $srchbysel .= "\n  </select>\n";
                   9686: 
                   9687:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9688:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9689:         if ($curr_selected{'srchtype'} eq $option) {
                   9690:             $srchtypesel .= '
1.1222    damieng  9691:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9692:         } else {
                   9693:             $srchtypesel .= '
1.1222    damieng  9694:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9695:         }
                   9696:     }
                   9697:     $srchtypesel .= "\n  </select>\n";
                   9698: 
1.558     albertel 9699:     my ($newuserscript,$new_user_create);
1.994     raeburn  9700:     my $context_dom = $env{'request.role.domain'};
                   9701:     if ($context eq 'requestcrs') {
                   9702:         if ($env{'form.coursedom'} ne '') { 
                   9703:             $context_dom = $env{'form.coursedom'};
                   9704:         }
                   9705:     }
1.556     raeburn  9706:     if ($forcenewuser) {
1.576     raeburn  9707:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9708:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9709:                 if ($cancreate) {
                   9710:                     $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>';
                   9711:                 } else {
1.799     bisitz   9712:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9713:                     my %usertypetext = (
                   9714:                         official   => 'institutional',
                   9715:                         unofficial => 'non-institutional',
                   9716:                     );
1.799     bisitz   9717:                     $new_user_create = '<p class="LC_warning">'
                   9718:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9719:                                       .' '
                   9720:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9721:                                           ,'<a href="'.$helplink.'">','</a>')
                   9722:                                       .'</p><br />';
1.627     raeburn  9723:                 }
1.576     raeburn  9724:             }
                   9725:         }
                   9726: 
1.556     raeburn  9727:         $newuserscript = <<"ENDSCRIPT";
                   9728: 
1.570     raeburn  9729: function setSearch(createnew,callingForm) {
1.556     raeburn  9730:     if (createnew == 1) {
1.570     raeburn  9731:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9732:             if (callingForm.srchby.options[i].value == 'uname') {
                   9733:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9734:             }
                   9735:         }
1.570     raeburn  9736:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9737:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9738: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9739:             }
                   9740:         }
1.570     raeburn  9741:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9742:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9743:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9744:             }
                   9745:         }
1.570     raeburn  9746:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9747:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9748:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9749:             }
                   9750:         }
                   9751:     }
                   9752: }
                   9753: ENDSCRIPT
1.558     albertel 9754: 
1.556     raeburn  9755:     }
                   9756: 
1.555     raeburn  9757:     my $output = <<"END_BLOCK";
1.556     raeburn  9758: <script type="text/javascript">
1.824     bisitz   9759: // <![CDATA[
1.570     raeburn  9760: function validateEntry(callingForm) {
1.558     albertel 9761: 
1.556     raeburn  9762:     var checkok = 1;
1.558     albertel 9763:     var srchin;
1.570     raeburn  9764:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9765: 	if ( callingForm.srchin[i].checked ) {
                   9766: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9767: 	}
                   9768:     }
                   9769: 
1.570     raeburn  9770:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9771:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9772:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9773:     var srchterm =  callingForm.srchterm.value;
                   9774:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9775:     var msg = "";
                   9776: 
                   9777:     if (srchterm == "") {
                   9778:         checkok = 0;
1.1222    damieng  9779:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  9780:     }
                   9781: 
1.569     raeburn  9782:     if (srchtype== 'begins') {
                   9783:         if (srchterm.length < 2) {
                   9784:             checkok = 0;
1.1222    damieng  9785:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  9786:         }
                   9787:     }
                   9788: 
1.556     raeburn  9789:     if (srchtype== 'contains') {
                   9790:         if (srchterm.length < 3) {
                   9791:             checkok = 0;
1.1222    damieng  9792:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  9793:         }
                   9794:     }
                   9795:     if (srchin == 'instd') {
                   9796:         if (srchdomain == '') {
                   9797:             checkok = 0;
1.1222    damieng  9798:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  9799:         }
                   9800:     }
                   9801:     if (srchin == 'dom') {
                   9802:         if (srchdomain == '') {
                   9803:             checkok = 0;
1.1222    damieng  9804:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  9805:         }
                   9806:     }
                   9807:     if (srchby == 'lastfirst') {
                   9808:         if (srchterm.indexOf(",") == -1) {
                   9809:             checkok = 0;
1.1222    damieng  9810:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  9811:         }
                   9812:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9813:             checkok = 0;
1.1222    damieng  9814:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  9815:         }
                   9816:     }
                   9817:     if (checkok == 0) {
1.1222    damieng  9818:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  9819:         return;
                   9820:     }
                   9821:     if (checkok == 1) {
1.570     raeburn  9822:         callingForm.submit();
1.556     raeburn  9823:     }
                   9824: }
                   9825: 
                   9826: $newuserscript
                   9827: 
1.824     bisitz   9828: // ]]>
1.556     raeburn  9829: </script>
1.558     albertel 9830: 
                   9831: $new_user_create
                   9832: 
1.555     raeburn  9833: END_BLOCK
1.558     albertel 9834: 
1.876     raeburn  9835:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  9836:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  9837:                $domform.
                   9838:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  9839:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  9840:                $srchbysel.
                   9841:                $srchtypesel. 
                   9842:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9843:                $srchinsel.
                   9844:                &Apache::lonhtmlcommon::row_closure(1). 
                   9845:                &Apache::lonhtmlcommon::end_pick_box().
                   9846:                '<br />';
1.555     raeburn  9847:     return $output;
                   9848: }
                   9849: 
1.612     raeburn  9850: sub user_rule_check {
1.615     raeburn  9851:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  9852:     my ($response,%inst_response);
1.612     raeburn  9853:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  9854:         if (keys(%{$usershash}) > 1) {
                   9855:             my (%by_username,%by_id,%userdoms);
                   9856:             my $checkid; 
                   9857:             if (ref($checks) eq 'HASH') {
                   9858:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   9859:                     $checkid = 1;
                   9860:                 }
                   9861:             }
                   9862:             foreach my $user (keys(%{$usershash})) {
                   9863:                 my ($uname,$udom) = split(/:/,$user);
                   9864:                 if ($checkid) {
                   9865:                     if (ref($usershash->{$user}) eq 'HASH') {
                   9866:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  9867:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  9868:                             $userdoms{$udom} = 1;
1.1227    raeburn  9869:                             if (ref($inst_results) eq 'HASH') {
                   9870:                                 $inst_results->{$uname.':'.$udom} = {};
                   9871:                             }
1.1226    raeburn  9872:                         }
                   9873:                     }
                   9874:                 } else {
                   9875:                     $by_username{$udom}{$uname} = 1;
                   9876:                     $userdoms{$udom} = 1;
1.1227    raeburn  9877:                     if (ref($inst_results) eq 'HASH') {
                   9878:                         $inst_results->{$uname.':'.$udom} = {};
                   9879:                     }
1.1226    raeburn  9880:                 }
                   9881:             }
                   9882:             foreach my $udom (keys(%userdoms)) {
                   9883:                 if (!$got_rules->{$udom}) {
                   9884:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9885:                                                              ['usercreation'],$udom);
                   9886:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9887:                         foreach my $item ('username','id') {
                   9888:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  9889:                                 $$curr_rules{$udom}{$item} =
                   9890:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  9891:                             }
                   9892:                         }
                   9893:                     }
                   9894:                     $got_rules->{$udom} = 1;
                   9895:                 }
1.612     raeburn  9896:             }
1.1226    raeburn  9897:             if ($checkid) {
                   9898:                 foreach my $udom (keys(%by_id)) {
                   9899:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   9900:                     if ($outcome eq 'ok') {
1.1227    raeburn  9901:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   9902:                             my $uname = $by_id{$udom}{$id};
                   9903:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9904:                         }
1.1226    raeburn  9905:                         if (ref($results) eq 'HASH') {
                   9906:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  9907:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   9908:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   9909:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9910:                                 }
1.1226    raeburn  9911:                             }
                   9912:                         }
                   9913:                     }
1.612     raeburn  9914:                 }
1.615     raeburn  9915:             } else {
1.1226    raeburn  9916:                 foreach my $udom (keys(%by_username)) {
                   9917:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   9918:                     if ($outcome eq 'ok') {
1.1227    raeburn  9919:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   9920:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9921:                         }
1.1226    raeburn  9922:                         if (ref($results) eq 'HASH') {
                   9923:                             foreach my $uname (keys(%{$results})) {
                   9924:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9925:                             }
                   9926:                         }
                   9927:                     }
                   9928:                 }
1.612     raeburn  9929:             }
1.1226    raeburn  9930:         } elsif (keys(%{$usershash}) == 1) {
                   9931:             my $user = (keys(%{$usershash}))[0];
                   9932:             my ($uname,$udom) = split(/:/,$user);
                   9933:             if (($udom ne '') && ($uname ne '')) {
                   9934:                 if (ref($usershash->{$user}) eq 'HASH') {
                   9935:                     if (ref($checks) eq 'HASH') {
                   9936:                         if (defined($checks->{'username'})) {
                   9937:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   9938:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   9939:                         } elsif (defined($checks->{'id'})) {
                   9940:                             if ($usershash->{$user}->{'id'} ne '') {
                   9941:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9942:                                     &Apache::lonnet::get_instuser($udom,undef,
                   9943:                                                                   $usershash->{$user}->{'id'});
                   9944:                             } else {
                   9945:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9946:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   9947:                             }
1.585     raeburn  9948:                         }
1.1226    raeburn  9949:                     } else {
                   9950:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   9951:                             &Apache::lonnet::get_instuser($udom,$uname);
                   9952:                        return;
                   9953:                     }
                   9954:                     if (!$got_rules->{$udom}) {
                   9955:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9956:                                                                  ['usercreation'],$udom);
                   9957:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9958:                             foreach my $item ('username','id') {
                   9959:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9960:                                    $$curr_rules{$udom}{$item} = 
                   9961:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   9962:                                 }
                   9963:                             }
                   9964:                         }
                   9965:                         $got_rules->{$udom} = 1;
1.585     raeburn  9966:                     }
                   9967:                 }
1.1226    raeburn  9968:             } else {
                   9969:                 return;
                   9970:             }
                   9971:         } else {
                   9972:             return;
                   9973:         }
                   9974:         foreach my $user (keys(%{$usershash})) {
                   9975:             my ($uname,$udom) = split(/:/,$user);
                   9976:             next if (($udom eq '') || ($uname eq ''));
                   9977:             my $id;
1.1227    raeburn  9978:             if (ref($inst_results) eq 'HASH') {
                   9979:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   9980:                     $id = $inst_results->{$user}->{'id'};
                   9981:                 }
                   9982:             }
                   9983:             if ($id eq '') { 
                   9984:                 if (ref($usershash->{$user})) {
                   9985:                     $id = $usershash->{$user}->{'id'};
                   9986:                 }
1.585     raeburn  9987:             }
1.612     raeburn  9988:             foreach my $item (keys(%{$checks})) {
                   9989:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9990:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9991:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  9992:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   9993:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  9994:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9995:                                 if ($rule_check{$rule}) {
                   9996:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  9997:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  9998:                                         if (ref($inst_results) eq 'HASH') {
                   9999:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10000:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10001:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10002:                                                 } elsif ($item eq 'id') {
                   10003:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10004:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10005:                                                     }
1.615     raeburn  10006:                                                 }
1.612     raeburn  10007:                                             }
                   10008:                                         }
1.615     raeburn  10009:                                     }
                   10010:                                     last;
1.585     raeburn  10011:                                 }
                   10012:                             }
                   10013:                         }
                   10014:                     }
                   10015:                 }
                   10016:             }
                   10017:         }
                   10018:     }
1.612     raeburn  10019:     return;
                   10020: }
                   10021: 
                   10022: sub user_rule_formats {
                   10023:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10024:     my %text = ( 
                   10025:                  'username' => 'Usernames',
                   10026:                  'id'       => 'IDs',
                   10027:                );
                   10028:     my $output;
                   10029:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10030:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10031:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10032:             $output = '<br />'.
                   10033:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10034:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10035:                       ' <ul>';
1.612     raeburn  10036:             foreach my $rule (@{$ruleorder}) {
                   10037:                 if (ref($curr_rules) eq 'ARRAY') {
                   10038:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10039:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10040:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10041:                                         $rules->{$rule}{'desc'}.'</li>';
                   10042:                         }
                   10043:                     }
                   10044:                 }
                   10045:             }
                   10046:             $output .= '</ul>';
                   10047:         }
                   10048:     }
                   10049:     return $output;
                   10050: }
                   10051: 
                   10052: sub instrule_disallow_msg {
1.615     raeburn  10053:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10054:     my $response;
                   10055:     my %text = (
                   10056:                   item   => 'username',
                   10057:                   items  => 'usernames',
                   10058:                   match  => 'matches',
                   10059:                   do     => 'does',
                   10060:                   action => 'a username',
                   10061:                   one    => 'one',
                   10062:                );
                   10063:     if ($count > 1) {
                   10064:         $text{'item'} = 'usernames';
                   10065:         $text{'match'} ='match';
                   10066:         $text{'do'} = 'do';
                   10067:         $text{'action'} = 'usernames',
                   10068:         $text{'one'} = 'ones';
                   10069:     }
                   10070:     if ($checkitem eq 'id') {
                   10071:         $text{'items'} = 'IDs';
                   10072:         $text{'item'} = 'ID';
                   10073:         $text{'action'} = 'an ID';
1.615     raeburn  10074:         if ($count > 1) {
                   10075:             $text{'item'} = 'IDs';
                   10076:             $text{'action'} = 'IDs';
                   10077:         }
1.612     raeburn  10078:     }
1.674     bisitz   10079:     $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  10080:     if ($mode eq 'upload') {
                   10081:         if ($checkitem eq 'username') {
                   10082:             $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'}.");
                   10083:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10084:             $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  10085:         }
1.669     raeburn  10086:     } elsif ($mode eq 'selfcreate') {
                   10087:         if ($checkitem eq 'id') {
                   10088:             $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.");
                   10089:         }
1.615     raeburn  10090:     } else {
                   10091:         if ($checkitem eq 'username') {
                   10092:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10093:         } elsif ($checkitem eq 'id') {
                   10094:             $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.");
                   10095:         }
1.612     raeburn  10096:     }
                   10097:     return $response;
1.585     raeburn  10098: }
                   10099: 
1.624     raeburn  10100: sub personal_data_fieldtitles {
                   10101:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10102:                         id => 'Student/Employee ID',
                   10103:                         permanentemail => 'E-mail address',
                   10104:                         lastname => 'Last Name',
                   10105:                         firstname => 'First Name',
                   10106:                         middlename => 'Middle Name',
                   10107:                         generation => 'Generation',
                   10108:                         gen => 'Generation',
1.765     raeburn  10109:                         inststatus => 'Affiliation',
1.624     raeburn  10110:                    );
                   10111:     return %fieldtitles;
                   10112: }
                   10113: 
1.642     raeburn  10114: sub sorted_inst_types {
                   10115:     my ($dom) = @_;
1.1185    raeburn  10116:     my ($usertypes,$order);
                   10117:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10118:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10119:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10120:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10121:     } else {
                   10122:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10123:     }
1.642     raeburn  10124:     my $othertitle = &mt('All users');
                   10125:     if ($env{'request.course.id'}) {
1.668     raeburn  10126:         $othertitle  = &mt('Any users');
1.642     raeburn  10127:     }
                   10128:     my @types;
                   10129:     if (ref($order) eq 'ARRAY') {
                   10130:         @types = @{$order};
                   10131:     }
                   10132:     if (@types == 0) {
                   10133:         if (ref($usertypes) eq 'HASH') {
                   10134:             @types = sort(keys(%{$usertypes}));
                   10135:         }
                   10136:     }
                   10137:     if (keys(%{$usertypes}) > 0) {
                   10138:         $othertitle = &mt('Other users');
                   10139:     }
                   10140:     return ($othertitle,$usertypes,\@types);
                   10141: }
                   10142: 
1.645     raeburn  10143: sub get_institutional_codes {
                   10144:     my ($settings,$allcourses,$LC_code) = @_;
                   10145: # Get complete list of course sections to update
                   10146:     my @currsections = ();
                   10147:     my @currxlists = ();
                   10148:     my $coursecode = $$settings{'internal.coursecode'};
                   10149: 
                   10150:     if ($$settings{'internal.sectionnums'} ne '') {
                   10151:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10152:     }
                   10153: 
                   10154:     if ($$settings{'internal.crosslistings'} ne '') {
                   10155:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10156:     }
                   10157: 
                   10158:     if (@currxlists > 0) {
                   10159:         foreach (@currxlists) {
                   10160:             if (m/^([^:]+):(\w*)$/) {
                   10161:                 unless (grep/^$1$/,@{$allcourses}) {
                   10162:                     push @{$allcourses},$1;
                   10163:                     $$LC_code{$1} = $2;
                   10164:                 }
                   10165:             }
                   10166:         }
                   10167:     }
                   10168:  
                   10169:     if (@currsections > 0) {
                   10170:         foreach (@currsections) {
                   10171:             if (m/^(\w+):(\w*)$/) {
                   10172:                 my $sec = $coursecode.$1;
                   10173:                 my $lc_sec = $2;
                   10174:                 unless (grep/^$sec$/,@{$allcourses}) {
                   10175:                     push @{$allcourses},$sec;
                   10176:                     $$LC_code{$sec} = $lc_sec;
                   10177:                 }
                   10178:             }
                   10179:         }
                   10180:     }
                   10181:     return;
                   10182: }
                   10183: 
1.971     raeburn  10184: sub get_standard_codeitems {
                   10185:     return ('Year','Semester','Department','Number','Section');
                   10186: }
                   10187: 
1.112     bowersj2 10188: =pod
                   10189: 
1.780     raeburn  10190: =head1 Slot Helpers
                   10191: 
                   10192: =over 4
                   10193: 
                   10194: =item * sorted_slots()
                   10195: 
1.1040    raeburn  10196: Sorts an array of slot names in order of an optional sort key,
                   10197: default sort is by slot start time (earliest first). 
1.780     raeburn  10198: 
                   10199: Inputs:
                   10200: 
                   10201: =over 4
                   10202: 
                   10203: slotsarr  - Reference to array of unsorted slot names.
                   10204: 
                   10205: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10206: 
1.1040    raeburn  10207: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10208: 
1.549     albertel 10209: =back
                   10210: 
1.780     raeburn  10211: Returns:
                   10212: 
                   10213: =over 4
                   10214: 
1.1040    raeburn  10215: sorted   - An array of slot names sorted by a specified sort key 
                   10216:            (default sort key is start time of the slot).
1.780     raeburn  10217: 
                   10218: =back
                   10219: 
                   10220: =cut
                   10221: 
                   10222: 
                   10223: sub sorted_slots {
1.1040    raeburn  10224:     my ($slotsarr,$slots,$sortkey) = @_;
                   10225:     if ($sortkey eq '') {
                   10226:         $sortkey = 'starttime';
                   10227:     }
1.780     raeburn  10228:     my @sorted;
                   10229:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10230:         @sorted =
                   10231:             sort {
                   10232:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10233:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10234:                      }
                   10235:                      if (ref($slots->{$a})) { return -1;}
                   10236:                      if (ref($slots->{$b})) { return 1;}
                   10237:                      return 0;
                   10238:                  } @{$slotsarr};
                   10239:     }
                   10240:     return @sorted;
                   10241: }
                   10242: 
1.1040    raeburn  10243: =pod
                   10244: 
                   10245: =item * get_future_slots()
                   10246: 
                   10247: Inputs:
                   10248: 
                   10249: =over 4
                   10250: 
                   10251: cnum - course number
                   10252: 
                   10253: cdom - course domain
                   10254: 
                   10255: now - current UNIX time
                   10256: 
                   10257: symb - optional symb
                   10258: 
                   10259: =back
                   10260: 
                   10261: Returns:
                   10262: 
                   10263: =over 4
                   10264: 
                   10265: sorted_reservable - ref to array of student_schedulable slots currently 
                   10266:                     reservable, ordered by end date of reservation period.
                   10267: 
                   10268: reservable_now - ref to hash of student_schedulable slots currently
                   10269:                  reservable.
                   10270: 
                   10271:     Keys in inner hash are:
                   10272:     (a) symb: either blank or symb to which slot use is restricted.
                   10273:     (b) endreserve: end date of reservation period. 
                   10274: 
                   10275: sorted_future - ref to array of student_schedulable slots reservable in
                   10276:                 the future, ordered by start date of reservation period.
                   10277: 
                   10278: future_reservable - ref to hash of student_schedulable slots reservable
                   10279:                     in the future.
                   10280: 
                   10281:     Keys in inner hash are:
                   10282:     (a) symb: either blank or symb to which slot use is restricted.
                   10283:     (b) startreserve:  start date of reservation period.
                   10284: 
                   10285: =back
                   10286: 
                   10287: =cut
                   10288: 
                   10289: sub get_future_slots {
                   10290:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  10291:     my $map;
                   10292:     if ($symb) {
                   10293:         ($map) = &Apache::lonnet::decode_symb($symb);
                   10294:     }
1.1040    raeburn  10295:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10296:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10297:     foreach my $slot (keys(%slots)) {
                   10298:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10299:         if ($symb) {
1.1229    raeburn  10300:             if ($slots{$slot}->{'symb'} ne '') {
                   10301:                 my $canuse;
                   10302:                 my %oksymbs;
                   10303:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   10304:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   10305:                 if ($oksymbs{$symb}) {
                   10306:                     $canuse = 1;
                   10307:                 } else {
                   10308:                     foreach my $item (@slotsymbs) {
                   10309:                         if ($item =~ /\.(page|sequence)$/) {
                   10310:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   10311:                             if (($map ne '') && ($map eq $sloturl)) {
                   10312:                                 $canuse = 1;
                   10313:                                 last;
                   10314:                             }
                   10315:                         }
                   10316:                     }
                   10317:                 }
                   10318:                 next unless ($canuse);
                   10319:             }
1.1040    raeburn  10320:         }
                   10321:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10322:             ($slots{$slot}->{'endtime'} > $now)) {
                   10323:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10324:                 my $userallowed = 0;
                   10325:                 if ($slots{$slot}->{'allowedsections'}) {
                   10326:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10327:                     if (!defined($env{'request.role.sec'})
                   10328:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10329:                         $userallowed=1;
                   10330:                     } else {
                   10331:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10332:                             $userallowed=1;
                   10333:                         }
                   10334:                     }
                   10335:                     unless ($userallowed) {
                   10336:                         if (defined($env{'request.course.groups'})) {
                   10337:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10338:                             foreach my $group (@groups) {
                   10339:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10340:                                     $userallowed=1;
                   10341:                                     last;
                   10342:                                 }
                   10343:                             }
                   10344:                         }
                   10345:                     }
                   10346:                 }
                   10347:                 if ($slots{$slot}->{'allowedusers'}) {
                   10348:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10349:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10350:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10351:                         $userallowed = 1;
                   10352:                     }
                   10353:                 }
                   10354:                 next unless($userallowed);
                   10355:             }
                   10356:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10357:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10358:             my $symb = $slots{$slot}->{'symb'};
                   10359:             if (($startreserve < $now) &&
                   10360:                 (!$endreserve || $endreserve > $now)) {
                   10361:                 my $lastres = $endreserve;
                   10362:                 if (!$lastres) {
                   10363:                     $lastres = $slots{$slot}->{'starttime'};
                   10364:                 }
                   10365:                 $reservable_now{$slot} = {
                   10366:                                            symb       => $symb,
                   10367:                                            endreserve => $lastres
                   10368:                                          };
                   10369:             } elsif (($startreserve > $now) &&
                   10370:                      (!$endreserve || $endreserve > $startreserve)) {
                   10371:                 $future_reservable{$slot} = {
                   10372:                                               symb         => $symb,
                   10373:                                               startreserve => $startreserve
                   10374:                                             };
                   10375:             }
                   10376:         }
                   10377:     }
                   10378:     my @unsorted_reservable = keys(%reservable_now);
                   10379:     if (@unsorted_reservable > 0) {
                   10380:         @sorted_reservable = 
                   10381:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10382:     }
                   10383:     my @unsorted_future = keys(%future_reservable);
                   10384:     if (@unsorted_future > 0) {
                   10385:         @sorted_future =
                   10386:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10387:     }
                   10388:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10389: }
1.780     raeburn  10390: 
                   10391: =pod
                   10392: 
1.1057    foxr     10393: =back
                   10394: 
1.549     albertel 10395: =head1 HTTP Helpers
                   10396: 
                   10397: =over 4
                   10398: 
1.648     raeburn  10399: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10400: 
1.258     albertel 10401: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10402: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10403: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10404: 
                   10405: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10406: $possible_names is an ref to an array of form element names.  As an example:
                   10407: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10408: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10409: 
                   10410: =cut
1.1       albertel 10411: 
1.6       albertel 10412: sub get_unprocessed_cgi {
1.25      albertel 10413:   my ($query,$possible_names)= @_;
1.26      matthew  10414:   # $Apache::lonxml::debug=1;
1.356     albertel 10415:   foreach my $pair (split(/&/,$query)) {
                   10416:     my ($name, $value) = split(/=/,$pair);
1.369     www      10417:     $name = &unescape($name);
1.25      albertel 10418:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10419:       $value =~ tr/+/ /;
                   10420:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10421:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10422:     }
1.16      harris41 10423:   }
1.6       albertel 10424: }
                   10425: 
1.112     bowersj2 10426: =pod
                   10427: 
1.648     raeburn  10428: =item * &cacheheader() 
1.112     bowersj2 10429: 
                   10430: returns cache-controlling header code
                   10431: 
                   10432: =cut
                   10433: 
1.7       albertel 10434: sub cacheheader {
1.258     albertel 10435:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10436:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10437:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10438:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10439:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10440:     return $output;
1.7       albertel 10441: }
                   10442: 
1.112     bowersj2 10443: =pod
                   10444: 
1.648     raeburn  10445: =item * &no_cache($r) 
1.112     bowersj2 10446: 
                   10447: specifies header code to not have cache
                   10448: 
                   10449: =cut
                   10450: 
1.9       albertel 10451: sub no_cache {
1.216     albertel 10452:     my ($r) = @_;
                   10453:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10454: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10455:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10456:     $r->no_cache(1);
                   10457:     $r->header_out("Expires" => $date);
                   10458:     $r->header_out("Pragma" => "no-cache");
1.123     www      10459: }
                   10460: 
                   10461: sub content_type {
1.181     albertel 10462:     my ($r,$type,$charset) = @_;
1.299     foxr     10463:     if ($r) {
                   10464: 	#  Note that printout.pl calls this with undef for $r.
                   10465: 	&no_cache($r);
                   10466:     }
1.258     albertel 10467:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10468:     unless ($charset) {
                   10469: 	$charset=&Apache::lonlocal::current_encoding;
                   10470:     }
                   10471:     if ($charset) { $type.='; charset='.$charset; }
                   10472:     if ($r) {
                   10473: 	$r->content_type($type);
                   10474:     } else {
                   10475: 	print("Content-type: $type\n\n");
                   10476:     }
1.9       albertel 10477: }
1.25      albertel 10478: 
1.112     bowersj2 10479: =pod
                   10480: 
1.648     raeburn  10481: =item * &add_to_env($name,$value) 
1.112     bowersj2 10482: 
1.258     albertel 10483: adds $name to the %env hash with value
1.112     bowersj2 10484: $value, if $name already exists, the entry is converted to an array
                   10485: reference and $value is added to the array.
                   10486: 
                   10487: =cut
                   10488: 
1.25      albertel 10489: sub add_to_env {
                   10490:   my ($name,$value)=@_;
1.258     albertel 10491:   if (defined($env{$name})) {
                   10492:     if (ref($env{$name})) {
1.25      albertel 10493:       #already have multiple values
1.258     albertel 10494:       push(@{ $env{$name} },$value);
1.25      albertel 10495:     } else {
                   10496:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10497:       my $first=$env{$name};
                   10498:       undef($env{$name});
                   10499:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10500:     }
                   10501:   } else {
1.258     albertel 10502:     $env{$name}=$value;
1.25      albertel 10503:   }
1.31      albertel 10504: }
1.149     albertel 10505: 
                   10506: =pod
                   10507: 
1.648     raeburn  10508: =item * &get_env_multiple($name) 
1.149     albertel 10509: 
1.258     albertel 10510: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10511: values may be defined and end up as an array ref.
                   10512: 
                   10513: returns an array of values
                   10514: 
                   10515: =cut
                   10516: 
                   10517: sub get_env_multiple {
                   10518:     my ($name) = @_;
                   10519:     my @values;
1.258     albertel 10520:     if (defined($env{$name})) {
1.149     albertel 10521:         # exists is it an array
1.258     albertel 10522:         if (ref($env{$name})) {
                   10523:             @values=@{ $env{$name} };
1.149     albertel 10524:         } else {
1.258     albertel 10525:             $values[0]=$env{$name};
1.149     albertel 10526:         }
                   10527:     }
                   10528:     return(@values);
                   10529: }
                   10530: 
1.660     raeburn  10531: sub ask_for_embedded_content {
                   10532:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10533:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  10534:         %currsubfile,%unused,$rem);
1.1071    raeburn  10535:     my $counter = 0;
                   10536:     my $numnew = 0;
1.987     raeburn  10537:     my $numremref = 0;
                   10538:     my $numinvalid = 0;
                   10539:     my $numpathchg = 0;
                   10540:     my $numexisting = 0;
1.1071    raeburn  10541:     my $numunused = 0;
                   10542:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  10543:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10544:     my $heading = &mt('Upload embedded files');
                   10545:     my $buttontext = &mt('Upload');
                   10546: 
1.1085    raeburn  10547:     if ($env{'request.course.id'}) {
1.1123    raeburn  10548:         if ($actionurl eq '/adm/dependencies') {
                   10549:             $navmap = Apache::lonnavmaps::navmap->new();
                   10550:         }
                   10551:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10552:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  10553:     }
1.1123    raeburn  10554:     if (($actionurl eq '/adm/portfolio') || 
                   10555:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10556:         my $current_path='/';
                   10557:         if ($env{'form.currentpath'}) {
                   10558:             $current_path = $env{'form.currentpath'};
                   10559:         }
                   10560:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  10561:             $udom = $cdom;
                   10562:             $uname = $cnum;
1.984     raeburn  10563:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10564:         } else {
                   10565:             $udom = $env{'user.domain'};
                   10566:             $uname = $env{'user.name'};
                   10567:             $url = '/userfiles/portfolio';
                   10568:         }
1.987     raeburn  10569:         $toplevel = $url.'/';
1.984     raeburn  10570:         $url .= $current_path;
                   10571:         $getpropath = 1;
1.987     raeburn  10572:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10573:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10574:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10575:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10576:         $toplevel = $url;
1.984     raeburn  10577:         if ($rest ne '') {
1.987     raeburn  10578:             $url .= $rest;
                   10579:         }
                   10580:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10581:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10582:             $url = $args->{'docs_url'};
                   10583:             $toplevel = $url;
1.1084    raeburn  10584:             if ($args->{'context'} eq 'paste') {
                   10585:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10586:                 ($path) = 
                   10587:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10588:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10589:                 $fileloc =~ s{^/}{};
                   10590:             }
1.1071    raeburn  10591:         }
1.1084    raeburn  10592:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  10593:         if ($env{'request.course.id'} ne '') {
                   10594:             if (ref($args) eq 'HASH') {
                   10595:                 $url = $args->{'docs_url'};
                   10596:                 $title = $args->{'docs_title'};
1.1126    raeburn  10597:                 $toplevel = $url; 
                   10598:                 unless ($toplevel =~ m{^/}) {
                   10599:                     $toplevel = "/$url";
                   10600:                 }
1.1085    raeburn  10601:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  10602:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10603:                     $path = $1;
                   10604:                 } else {
                   10605:                     ($path) =
                   10606:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10607:                 }
1.1195    raeburn  10608:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10609:                     $fileloc = $toplevel;
                   10610:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10611:                     my ($udom,$uname,$fname) =
                   10612:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10613:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10614:                 } else {
                   10615:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10616:                 }
1.1071    raeburn  10617:                 $fileloc =~ s{^/}{};
                   10618:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10619:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10620:             }
1.987     raeburn  10621:         }
1.1123    raeburn  10622:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10623:         $udom = $cdom;
                   10624:         $uname = $cnum;
                   10625:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10626:         $toplevel = $url;
                   10627:         $path = $url;
                   10628:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10629:         $fileloc =~ s{^/}{};
1.987     raeburn  10630:     }
1.1126    raeburn  10631:     foreach my $file (keys(%{$allfiles})) {
                   10632:         my $embed_file;
                   10633:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10634:             $embed_file = $1;
                   10635:         } else {
                   10636:             $embed_file = $file;
                   10637:         }
1.1158    raeburn  10638:         my ($absolutepath,$cleaned_file);
                   10639:         if ($embed_file =~ m{^\w+://}) {
                   10640:             $cleaned_file = $embed_file;
1.1147    raeburn  10641:             $newfiles{$cleaned_file} = 1;
                   10642:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10643:         } else {
1.1158    raeburn  10644:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10645:             if ($embed_file =~ m{^/}) {
                   10646:                 $absolutepath = $embed_file;
                   10647:             }
1.1147    raeburn  10648:             if ($cleaned_file =~ m{/}) {
                   10649:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10650:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10651:                 my $item = $fname;
                   10652:                 if ($path ne '') {
                   10653:                     $item = $path.'/'.$fname;
                   10654:                     $subdependencies{$path}{$fname} = 1;
                   10655:                 } else {
                   10656:                     $dependencies{$item} = 1;
                   10657:                 }
                   10658:                 if ($absolutepath) {
                   10659:                     $mapping{$item} = $absolutepath;
                   10660:                 } else {
                   10661:                     $mapping{$item} = $embed_file;
                   10662:                 }
                   10663:             } else {
                   10664:                 $dependencies{$embed_file} = 1;
                   10665:                 if ($absolutepath) {
1.1147    raeburn  10666:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10667:                 } else {
1.1147    raeburn  10668:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10669:                 }
                   10670:             }
1.984     raeburn  10671:         }
                   10672:     }
1.1071    raeburn  10673:     my $dirptr = 16384;
1.984     raeburn  10674:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10675:         $currsubfile{$path} = {};
1.1123    raeburn  10676:         if (($actionurl eq '/adm/portfolio') || 
                   10677:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10678:             my ($sublistref,$listerror) =
                   10679:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10680:             if (ref($sublistref) eq 'ARRAY') {
                   10681:                 foreach my $line (@{$sublistref}) {
                   10682:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10683:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10684:                 }
1.984     raeburn  10685:             }
1.987     raeburn  10686:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10687:             if (opendir(my $dir,$url.'/'.$path)) {
                   10688:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10689:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10690:             }
1.1084    raeburn  10691:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10692:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10693:                   ($args->{'context'} eq 'paste')) ||
                   10694:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10695:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  10696:                 my $dir;
                   10697:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10698:                     $dir = $fileloc;
                   10699:                 } else {
                   10700:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10701:                 }
1.1071    raeburn  10702:                 if ($dir ne '') {
                   10703:                     my ($sublistref,$listerror) =
                   10704:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10705:                     if (ref($sublistref) eq 'ARRAY') {
                   10706:                         foreach my $line (@{$sublistref}) {
                   10707:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10708:                                 undef,$mtime)=split(/\&/,$line,12);
                   10709:                             unless (($testdir&$dirptr) ||
                   10710:                                     ($file_name =~ /^\.\.?$/)) {
                   10711:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10712:                             }
                   10713:                         }
                   10714:                     }
                   10715:                 }
1.984     raeburn  10716:             }
                   10717:         }
                   10718:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10719:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10720:                 my $item = $path.'/'.$file;
                   10721:                 unless ($mapping{$item} eq $item) {
                   10722:                     $pathchanges{$item} = 1;
                   10723:                 }
                   10724:                 $existing{$item} = 1;
                   10725:                 $numexisting ++;
                   10726:             } else {
                   10727:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10728:             }
                   10729:         }
1.1071    raeburn  10730:         if ($actionurl eq '/adm/dependencies') {
                   10731:             foreach my $path (keys(%currsubfile)) {
                   10732:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10733:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10734:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  10735:                              next if (($rem ne '') &&
                   10736:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10737:                                        (ref($navmap) &&
                   10738:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10739:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10740:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10741:                              $unused{$path.'/'.$file} = 1; 
                   10742:                          }
                   10743:                     }
                   10744:                 }
                   10745:             }
                   10746:         }
1.984     raeburn  10747:     }
1.987     raeburn  10748:     my %currfile;
1.1123    raeburn  10749:     if (($actionurl eq '/adm/portfolio') ||
                   10750:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10751:         my ($dirlistref,$listerror) =
                   10752:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10753:         if (ref($dirlistref) eq 'ARRAY') {
                   10754:             foreach my $line (@{$dirlistref}) {
                   10755:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10756:                 $currfile{$file_name} = 1;
                   10757:             }
1.984     raeburn  10758:         }
1.987     raeburn  10759:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10760:         if (opendir(my $dir,$url)) {
1.987     raeburn  10761:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10762:             map {$currfile{$_} = 1;} @dir_list;
                   10763:         }
1.1084    raeburn  10764:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10765:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10766:               ($args->{'context'} eq 'paste')) ||
                   10767:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10768:         if ($env{'request.course.id'} ne '') {
                   10769:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10770:             if ($dir ne '') {
                   10771:                 my ($dirlistref,$listerror) =
                   10772:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10773:                 if (ref($dirlistref) eq 'ARRAY') {
                   10774:                     foreach my $line (@{$dirlistref}) {
                   10775:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10776:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10777:                         unless (($testdir&$dirptr) ||
                   10778:                                 ($file_name =~ /^\.\.?$/)) {
                   10779:                             $currfile{$file_name} = [$size,$mtime];
                   10780:                         }
                   10781:                     }
                   10782:                 }
                   10783:             }
                   10784:         }
1.984     raeburn  10785:     }
                   10786:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10787:         if (exists($currfile{$file})) {
1.987     raeburn  10788:             unless ($mapping{$file} eq $file) {
                   10789:                 $pathchanges{$file} = 1;
                   10790:             }
                   10791:             $existing{$file} = 1;
                   10792:             $numexisting ++;
                   10793:         } else {
1.984     raeburn  10794:             $newfiles{$file} = 1;
                   10795:         }
                   10796:     }
1.1071    raeburn  10797:     foreach my $file (keys(%currfile)) {
                   10798:         unless (($file eq $filename) ||
                   10799:                 ($file eq $filename.'.bak') ||
                   10800:                 ($dependencies{$file})) {
1.1085    raeburn  10801:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  10802:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10803:                     next if (($rem ne '') &&
                   10804:                              (($env{"httpref.$rem".$file} ne '') ||
                   10805:                               (ref($navmap) &&
                   10806:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10807:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10808:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10809:                 }
1.1085    raeburn  10810:             }
1.1071    raeburn  10811:             $unused{$file} = 1;
                   10812:         }
                   10813:     }
1.1084    raeburn  10814:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10815:         ($args->{'context'} eq 'paste')) {
                   10816:         $counter = scalar(keys(%existing));
                   10817:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  10818:         return ($output,$counter,$numpathchg,\%existing);
                   10819:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   10820:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10821:         $counter = scalar(keys(%existing));
                   10822:         $numpathchg = scalar(keys(%pathchanges));
                   10823:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  10824:     }
1.984     raeburn  10825:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10826:         if ($actionurl eq '/adm/dependencies') {
                   10827:             next if ($embed_file =~ m{^\w+://});
                   10828:         }
1.660     raeburn  10829:         $upload_output .= &start_data_table_row().
1.1123    raeburn  10830:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10831:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10832:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  10833:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10834:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10835:         }
1.1123    raeburn  10836:         $upload_output .= '</td>';
1.1071    raeburn  10837:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  10838:             $upload_output.='<td align="right">'.
                   10839:                             '<span class="LC_info LC_fontsize_medium">'.
                   10840:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10841:             $numremref++;
1.660     raeburn  10842:         } elsif ($args->{'error_on_invalid_names'}
                   10843:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  10844:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10845:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10846:             $numinvalid++;
1.660     raeburn  10847:         } else {
1.1123    raeburn  10848:             $upload_output .= '<td>'.
                   10849:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10850:                                                      $embed_file,\%mapping,
1.1071    raeburn  10851:                                                      $allfiles,$codebase,'upload');
                   10852:             $counter ++;
                   10853:             $numnew ++;
1.987     raeburn  10854:         }
                   10855:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10856:     }
                   10857:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10858:         if ($actionurl eq '/adm/dependencies') {
                   10859:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10860:             $modify_output .= &start_data_table_row().
                   10861:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10862:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10863:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10864:                               '<td>'.$size.'</td>'.
                   10865:                               '<td>'.$mtime.'</td>'.
                   10866:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10867:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10868:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10869:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10870:                               &embedded_file_element('upload_embedded',$counter,
                   10871:                                                      $embed_file,\%mapping,
                   10872:                                                      $allfiles,$codebase,'modify').
                   10873:                               '</div></td>'.
                   10874:                               &end_data_table_row()."\n";
                   10875:             $counter ++;
                   10876:         } else {
                   10877:             $upload_output .= &start_data_table_row().
1.1123    raeburn  10878:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10879:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10880:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10881:                               &Apache::loncommon::end_data_table_row()."\n";
                   10882:         }
                   10883:     }
                   10884:     my $delidx = $counter;
                   10885:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10886:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10887:         $delete_output .= &start_data_table_row().
                   10888:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10889:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10890:                           '<td>'.$size.'</td>'.
                   10891:                           '<td>'.$mtime.'</td>'.
                   10892:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10893:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10894:                           &embedded_file_element('upload_embedded',$delidx,
                   10895:                                                  $oldfile,\%mapping,$allfiles,
                   10896:                                                  $codebase,'delete').'</td>'.
                   10897:                           &end_data_table_row()."\n"; 
                   10898:         $numunused ++;
                   10899:         $delidx ++;
1.987     raeburn  10900:     }
                   10901:     if ($upload_output) {
                   10902:         $upload_output = &start_data_table().
                   10903:                          $upload_output.
                   10904:                          &end_data_table()."\n";
                   10905:     }
1.1071    raeburn  10906:     if ($modify_output) {
                   10907:         $modify_output = &start_data_table().
                   10908:                          &start_data_table_header_row().
                   10909:                          '<th>'.&mt('File').'</th>'.
                   10910:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10911:                          '<th>'.&mt('Modified').'</th>'.
                   10912:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10913:                          &end_data_table_header_row().
                   10914:                          $modify_output.
                   10915:                          &end_data_table()."\n";
                   10916:     }
                   10917:     if ($delete_output) {
                   10918:         $delete_output = &start_data_table().
                   10919:                          &start_data_table_header_row().
                   10920:                          '<th>'.&mt('File').'</th>'.
                   10921:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10922:                          '<th>'.&mt('Modified').'</th>'.
                   10923:                          '<th>'.&mt('Delete?').'</th>'.
                   10924:                          &end_data_table_header_row().
                   10925:                          $delete_output.
                   10926:                          &end_data_table()."\n";
                   10927:     }
1.987     raeburn  10928:     my $applies = 0;
                   10929:     if ($numremref) {
                   10930:         $applies ++;
                   10931:     }
                   10932:     if ($numinvalid) {
                   10933:         $applies ++;
                   10934:     }
                   10935:     if ($numexisting) {
                   10936:         $applies ++;
                   10937:     }
1.1071    raeburn  10938:     if ($counter || $numunused) {
1.987     raeburn  10939:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10940:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10941:                   $state.'<h3>'.$heading.'</h3>'; 
                   10942:         if ($actionurl eq '/adm/dependencies') {
                   10943:             if ($numnew) {
                   10944:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10945:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10946:                            $upload_output.'<br />'."\n";
                   10947:             }
                   10948:             if ($numexisting) {
                   10949:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10950:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10951:                            $modify_output.'<br />'."\n";
                   10952:                            $buttontext = &mt('Save changes');
                   10953:             }
                   10954:             if ($numunused) {
                   10955:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10956:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10957:                            $delete_output.'<br />'."\n";
                   10958:                            $buttontext = &mt('Save changes');
                   10959:             }
                   10960:         } else {
                   10961:             $output .= $upload_output.'<br />'."\n";
                   10962:         }
                   10963:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10964:                    $counter.'" />'."\n";
                   10965:         if ($actionurl eq '/adm/dependencies') { 
                   10966:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10967:                        $numnew.'" />'."\n";
                   10968:         } elsif ($actionurl eq '') {
1.987     raeburn  10969:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10970:         }
                   10971:     } elsif ($applies) {
                   10972:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10973:         if ($applies > 1) {
                   10974:             $output .=  
1.1123    raeburn  10975:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10976:             if ($numremref) {
                   10977:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10978:             }
                   10979:             if ($numinvalid) {
                   10980:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10981:             }
                   10982:             if ($numexisting) {
                   10983:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10984:             }
                   10985:             $output .= '</ul><br />';
                   10986:         } elsif ($numremref) {
                   10987:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10988:         } elsif ($numinvalid) {
                   10989:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10990:         } elsif ($numexisting) {
                   10991:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10992:         }
                   10993:         $output .= $upload_output.'<br />';
                   10994:     }
                   10995:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10996:     $chgcount = $counter;
1.987     raeburn  10997:     if (keys(%pathchanges) > 0) {
                   10998:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10999:             if ($counter) {
1.987     raeburn  11000:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11001:                                                   $embed_file,\%mapping,
1.1071    raeburn  11002:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11003:             } else {
                   11004:                 $pathchange_output .= 
                   11005:                     &start_data_table_row().
                   11006:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11007:                     $chgcount.'" checked="checked" /></td>'.
                   11008:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11009:                     '<td>'.$embed_file.
                   11010:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11011:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11012:                     '</td>'.&end_data_table_row();
1.660     raeburn  11013:             }
1.987     raeburn  11014:             $numpathchg ++;
                   11015:             $chgcount ++;
1.660     raeburn  11016:         }
                   11017:     }
1.1127    raeburn  11018:     if (($counter) || ($numunused)) {
1.987     raeburn  11019:         if ($numpathchg) {
                   11020:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11021:                        $numpathchg.'" />'."\n";
                   11022:         }
                   11023:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11024:             ($actionurl eq '/adm/imsimport')) {
                   11025:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11026:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11027:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11028:         } elsif ($actionurl eq '/adm/dependencies') {
                   11029:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11030:         }
1.1123    raeburn  11031:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11032:     } elsif ($numpathchg) {
                   11033:         my %pathchange = ();
                   11034:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11035:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11036:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11037:         }
1.987     raeburn  11038:     }
1.1071    raeburn  11039:     return ($output,$counter,$numpathchg);
1.987     raeburn  11040: }
                   11041: 
1.1147    raeburn  11042: =pod
                   11043: 
                   11044: =item * clean_path($name)
                   11045: 
                   11046: Performs clean-up of directories, subdirectories and filename in an
                   11047: embedded object, referenced in an HTML file which is being uploaded
                   11048: to a course or portfolio, where 
                   11049: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11050: checked.
                   11051: 
                   11052: Clean-up is similar to replacements in lonnet::clean_filename()
                   11053: except each / between sub-directory and next level is preserved.
                   11054: 
                   11055: =cut
                   11056: 
                   11057: sub clean_path {
                   11058:     my ($embed_file) = @_;
                   11059:     $embed_file =~s{^/+}{};
                   11060:     my @contents;
                   11061:     if ($embed_file =~ m{/}) {
                   11062:         @contents = split(/\//,$embed_file);
                   11063:     } else {
                   11064:         @contents = ($embed_file);
                   11065:     }
                   11066:     my $lastidx = scalar(@contents)-1;
                   11067:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11068:         $contents[$i]=~s{\\}{/}g;
                   11069:         $contents[$i]=~s/\s+/\_/g;
                   11070:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11071:         if ($i == $lastidx) {
                   11072:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11073:         }
                   11074:     }
                   11075:     if ($lastidx > 0) {
                   11076:         return join('/',@contents);
                   11077:     } else {
                   11078:         return $contents[0];
                   11079:     }
                   11080: }
                   11081: 
1.987     raeburn  11082: sub embedded_file_element {
1.1071    raeburn  11083:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11084:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11085:                    (ref($codebase) eq 'HASH'));
                   11086:     my $output;
1.1071    raeburn  11087:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11088:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11089:     }
                   11090:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11091:                &escape($embed_file).'" />';
                   11092:     unless (($context eq 'upload_embedded') && 
                   11093:             ($mapping->{$embed_file} eq $embed_file)) {
                   11094:         $output .='
                   11095:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11096:     }
                   11097:     my $attrib;
                   11098:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11099:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11100:     }
                   11101:     $output .=
                   11102:         "\n\t\t".
                   11103:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11104:         $attrib.'" />';
                   11105:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11106:         $output .=
                   11107:             "\n\t\t".
                   11108:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11109:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11110:     }
1.987     raeburn  11111:     return $output;
1.660     raeburn  11112: }
                   11113: 
1.1071    raeburn  11114: sub get_dependency_details {
                   11115:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11116:     my ($size,$mtime,$showsize,$showmtime);
                   11117:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11118:         if ($embed_file =~ m{/}) {
                   11119:             my ($path,$fname) = split(/\//,$embed_file);
                   11120:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11121:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11122:             }
                   11123:         } else {
                   11124:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11125:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11126:             }
                   11127:         }
                   11128:         $showsize = $size/1024.0;
                   11129:         $showsize = sprintf("%.1f",$showsize);
                   11130:         if ($mtime > 0) {
                   11131:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11132:         }
                   11133:     }
                   11134:     return ($showsize,$showmtime);
                   11135: }
                   11136: 
                   11137: sub ask_embedded_js {
                   11138:     return <<"END";
                   11139: <script type="text/javascript"">
                   11140: // <![CDATA[
                   11141: function toggleBrowse(counter) {
                   11142:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11143:     var fileid = document.getElementById('embedded_item_'+counter);
                   11144:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11145:     if (chkboxid.checked == true) {
                   11146:         uploaddivid.style.display='block';
                   11147:     } else {
                   11148:         uploaddivid.style.display='none';
                   11149:         fileid.value = '';
                   11150:     }
                   11151: }
                   11152: // ]]>
                   11153: </script>
                   11154: 
                   11155: END
                   11156: }
                   11157: 
1.661     raeburn  11158: sub upload_embedded {
                   11159:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11160:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11161:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11162:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11163:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11164:         my $orig_uploaded_filename =
                   11165:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11166:         foreach my $type ('orig','ref','attrib','codebase') {
                   11167:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11168:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11169:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11170:             }
                   11171:         }
1.661     raeburn  11172:         my ($path,$fname) =
                   11173:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11174:         # no path, whole string is fname
                   11175:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11176:         $fname = &Apache::lonnet::clean_filename($fname);
                   11177:         # See if there is anything left
                   11178:         next if ($fname eq '');
                   11179: 
                   11180:         # Check if file already exists as a file or directory.
                   11181:         my ($state,$msg);
                   11182:         if ($context eq 'portfolio') {
                   11183:             my $port_path = $dirpath;
                   11184:             if ($group ne '') {
                   11185:                 $port_path = "groups/$group/$port_path";
                   11186:             }
1.987     raeburn  11187:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11188:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11189:                                               $dir_root,$port_path,$disk_quota,
                   11190:                                               $current_disk_usage,$uname,$udom);
                   11191:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11192:                 || $state eq 'file_locked') {
1.661     raeburn  11193:                 $output .= $msg;
                   11194:                 next;
                   11195:             }
                   11196:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11197:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11198:             if ($state eq 'exists') {
                   11199:                 $output .= $msg;
                   11200:                 next;
                   11201:             }
                   11202:         }
                   11203:         # Check if extension is valid
                   11204:         if (($fname =~ /\.(\w+)$/) &&
                   11205:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   11206:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11207:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11208:             next;
                   11209:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11210:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11211:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11212:             next;
                   11213:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   11214:             $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  11215:             next;
                   11216:         }
                   11217:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  11218:         my $subdir = $path;
                   11219:         $subdir =~ s{/+$}{};
1.661     raeburn  11220:         if ($context eq 'portfolio') {
1.984     raeburn  11221:             my $result;
                   11222:             if ($state eq 'existingfile') {
                   11223:                 $result=
                   11224:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  11225:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11226:             } else {
1.984     raeburn  11227:                 $result=
                   11228:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11229:                                                     $dirpath.
1.1123    raeburn  11230:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11231:                 if ($result !~ m|^/uploaded/|) {
                   11232:                     $output .= '<span class="LC_error">'
                   11233:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11234:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11235:                                .'</span><br />';
                   11236:                     next;
                   11237:                 } else {
1.987     raeburn  11238:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11239:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11240:                 }
1.661     raeburn  11241:             }
1.1123    raeburn  11242:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  11243:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11244:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11245:             my $result =
1.1126    raeburn  11246:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11247:             if ($result !~ m|^/uploaded/|) {
                   11248:                 $output .= '<span class="LC_error">'
                   11249:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11250:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11251:                            .'</span><br />';
                   11252:                     next;
                   11253:             } else {
                   11254:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11255:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11256:                 if ($context eq 'syllabus') {
                   11257:                     &Apache::lonnet::make_public_indefinitely($result);
                   11258:                 }
1.987     raeburn  11259:             }
1.661     raeburn  11260:         } else {
                   11261: # Save the file
                   11262:             my $target = $env{'form.embedded_item_'.$i};
                   11263:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11264:             my $dest = $fullpath.$fname;
                   11265:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11266:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11267:             my $count;
                   11268:             my $filepath = $dir_root;
1.1027    raeburn  11269:             foreach my $subdir (@parts) {
                   11270:                 $filepath .= "/$subdir";
                   11271:                 if (!-e $filepath) {
1.661     raeburn  11272:                     mkdir($filepath,0770);
                   11273:                 }
                   11274:             }
                   11275:             my $fh;
                   11276:             if (!open($fh,'>'.$dest)) {
                   11277:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11278:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11279:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11280:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11281:                            '</span><br />';
                   11282:             } else {
                   11283:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11284:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11285:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11286:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11287:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11288:                               '</span><br />';
                   11289:                 } else {
1.987     raeburn  11290:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11291:                                $url.'</span>').'<br />';
                   11292:                     unless ($context eq 'testbank') {
                   11293:                         $footer .= &mt('View embedded file: [_1]',
                   11294:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11295:                     }
                   11296:                 }
                   11297:                 close($fh);
                   11298:             }
                   11299:         }
                   11300:         if ($env{'form.embedded_ref_'.$i}) {
                   11301:             $pathchange{$i} = 1;
                   11302:         }
                   11303:     }
                   11304:     if ($output) {
                   11305:         $output = '<p>'.$output.'</p>';
                   11306:     }
                   11307:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11308:     $returnflag = 'ok';
1.1071    raeburn  11309:     my $numpathchgs = scalar(keys(%pathchange));
                   11310:     if ($numpathchgs > 0) {
1.987     raeburn  11311:         if ($context eq 'portfolio') {
                   11312:             $output .= '<p>'.&mt('or').'</p>';
                   11313:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11314:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11315:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11316:             $returnflag = 'modify_orightml';
                   11317:         }
                   11318:     }
1.1071    raeburn  11319:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11320: }
                   11321: 
                   11322: sub modify_html_form {
                   11323:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11324:     my $end = 0;
                   11325:     my $modifyform;
                   11326:     if ($context eq 'upload_embedded') {
                   11327:         return unless (ref($pathchange) eq 'HASH');
                   11328:         if ($env{'form.number_embedded_items'}) {
                   11329:             $end += $env{'form.number_embedded_items'};
                   11330:         }
                   11331:         if ($env{'form.number_pathchange_items'}) {
                   11332:             $end += $env{'form.number_pathchange_items'};
                   11333:         }
                   11334:         if ($end) {
                   11335:             for (my $i=0; $i<$end; $i++) {
                   11336:                 if ($i < $env{'form.number_embedded_items'}) {
                   11337:                     next unless($pathchange->{$i});
                   11338:                 }
                   11339:                 $modifyform .=
                   11340:                     &start_data_table_row().
                   11341:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11342:                     'checked="checked" /></td>'.
                   11343:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11344:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11345:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11346:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11347:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11348:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11349:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11350:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11351:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11352:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11353:                     &end_data_table_row();
1.1071    raeburn  11354:             }
1.987     raeburn  11355:         }
                   11356:     } else {
                   11357:         $modifyform = $pathchgtable;
                   11358:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11359:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11360:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11361:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11362:         }
                   11363:     }
                   11364:     if ($modifyform) {
1.1071    raeburn  11365:         if ($actionurl eq '/adm/dependencies') {
                   11366:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11367:         }
1.987     raeburn  11368:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11369:                '<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".
                   11370:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11371:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11372:                '</ol></p>'."\n".'<p>'.
                   11373:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11374:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11375:                &start_data_table()."\n".
                   11376:                &start_data_table_header_row().
                   11377:                '<th>'.&mt('Change?').'</th>'.
                   11378:                '<th>'.&mt('Current reference').'</th>'.
                   11379:                '<th>'.&mt('Required reference').'</th>'.
                   11380:                &end_data_table_header_row()."\n".
                   11381:                $modifyform.
                   11382:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11383:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11384:                '</form>'."\n";
                   11385:     }
                   11386:     return;
                   11387: }
                   11388: 
                   11389: sub modify_html_refs {
1.1123    raeburn  11390:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11391:     my $container;
                   11392:     if ($context eq 'portfolio') {
                   11393:         $container = $env{'form.container'};
                   11394:     } elsif ($context eq 'coursedoc') {
                   11395:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11396:     } elsif ($context eq 'manage_dependencies') {
                   11397:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11398:         $container = "/$container";
1.1123    raeburn  11399:     } elsif ($context eq 'syllabus') {
                   11400:         $container = $url;
1.987     raeburn  11401:     } else {
1.1027    raeburn  11402:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11403:     }
                   11404:     my (%allfiles,%codebase,$output,$content);
                   11405:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  11406:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  11407:         if (wantarray) {
                   11408:             return ('',0,0); 
                   11409:         } else {
                   11410:             return;
                   11411:         }
                   11412:     }
                   11413:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11414:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11415:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11416:             if (wantarray) {
                   11417:                 return ('',0,0);
                   11418:             } else {
                   11419:                 return;
                   11420:             }
                   11421:         } 
1.987     raeburn  11422:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11423:         if ($content eq '-1') {
                   11424:             if (wantarray) {
                   11425:                 return ('',0,0);
                   11426:             } else {
                   11427:                 return;
                   11428:             }
                   11429:         }
1.987     raeburn  11430:     } else {
1.1071    raeburn  11431:         unless ($container =~ /^\Q$dir_root\E/) {
                   11432:             if (wantarray) {
                   11433:                 return ('',0,0);
                   11434:             } else {
                   11435:                 return;
                   11436:             }
                   11437:         } 
1.987     raeburn  11438:         if (open(my $fh,"<$container")) {
                   11439:             $content = join('', <$fh>);
                   11440:             close($fh);
                   11441:         } else {
1.1071    raeburn  11442:             if (wantarray) {
                   11443:                 return ('',0,0);
                   11444:             } else {
                   11445:                 return;
                   11446:             }
1.987     raeburn  11447:         }
                   11448:     }
                   11449:     my ($count,$codebasecount) = (0,0);
                   11450:     my $mm = new File::MMagic;
                   11451:     my $mime_type = $mm->checktype_contents($content);
                   11452:     if ($mime_type eq 'text/html') {
                   11453:         my $parse_result = 
                   11454:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11455:                                                     \%codebase,\$content);
                   11456:         if ($parse_result eq 'ok') {
                   11457:             foreach my $i (@changes) {
                   11458:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11459:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11460:                 if ($allfiles{$ref}) {
                   11461:                     my $newname =  $orig;
                   11462:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11463:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11464:                     if ($attrib_regexp =~ /:/) {
                   11465:                         $attrib_regexp =~ s/\:/|/g;
                   11466:                     }
                   11467:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11468:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11469:                         $count += $numchg;
1.1123    raeburn  11470:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  11471:                         delete($allfiles{$ref});
1.987     raeburn  11472:                     }
                   11473:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11474:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11475:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11476:                         $codebasecount ++;
                   11477:                     }
                   11478:                 }
                   11479:             }
1.1123    raeburn  11480:             my $skiprewrites;
1.987     raeburn  11481:             if ($count || $codebasecount) {
                   11482:                 my $saveresult;
1.1071    raeburn  11483:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11484:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11485:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11486:                     if ($url eq $container) {
                   11487:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11488:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11489:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11490:                                             $fname.'</span>').'</p>';
1.987     raeburn  11491:                     } else {
                   11492:                          $output = '<p class="LC_error">'.
                   11493:                                    &mt('Error: update failed for: [_1].',
                   11494:                                    '<span class="LC_filename">'.
                   11495:                                    $container.'</span>').'</p>';
                   11496:                     }
1.1123    raeburn  11497:                     if ($context eq 'syllabus') {
                   11498:                         unless ($saveresult eq 'ok') {
                   11499:                             $skiprewrites = 1;
                   11500:                         }
                   11501:                     }
1.987     raeburn  11502:                 } else {
                   11503:                     if (open(my $fh,">$container")) {
                   11504:                         print $fh $content;
                   11505:                         close($fh);
                   11506:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11507:                                   $count,'<span class="LC_filename">'.
                   11508:                                   $container.'</span>').'</p>';
1.661     raeburn  11509:                     } else {
1.987     raeburn  11510:                          $output = '<p class="LC_error">'.
                   11511:                                    &mt('Error: could not update [_1].',
                   11512:                                    '<span class="LC_filename">'.
                   11513:                                    $container.'</span>').'</p>';
1.661     raeburn  11514:                     }
                   11515:                 }
                   11516:             }
1.1123    raeburn  11517:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11518:                 my ($actionurl,$state);
                   11519:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11520:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11521:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11522:                                               \%codebase,
                   11523:                                               {'context' => 'rewrites',
                   11524:                                                'ignore_remote_references' => 1,});
                   11525:                 if (ref($mapping) eq 'HASH') {
                   11526:                     my $rewrites = 0;
                   11527:                     foreach my $key (keys(%{$mapping})) {
                   11528:                         next if ($key =~ m{^https?://});
                   11529:                         my $ref = $mapping->{$key};
                   11530:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11531:                         my $attrib;
                   11532:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11533:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11534:                         }
                   11535:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11536:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11537:                             $rewrites += $numchg;
                   11538:                         }
                   11539:                     }
                   11540:                     if ($rewrites) {
                   11541:                         my $saveresult; 
                   11542:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11543:                         if ($url eq $container) {
                   11544:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11545:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11546:                                             $count,'<span class="LC_filename">'.
                   11547:                                             $fname.'</span>').'</p>';
                   11548:                         } else {
                   11549:                             $output .= '<p class="LC_error">'.
                   11550:                                        &mt('Error: could not update links in [_1].',
                   11551:                                        '<span class="LC_filename">'.
                   11552:                                        $container.'</span>').'</p>';
                   11553: 
                   11554:                         }
                   11555:                     }
                   11556:                 }
                   11557:             }
1.987     raeburn  11558:         } else {
                   11559:             &logthis('Failed to parse '.$container.
                   11560:                      ' to modify references: '.$parse_result);
1.661     raeburn  11561:         }
                   11562:     }
1.1071    raeburn  11563:     if (wantarray) {
                   11564:         return ($output,$count,$codebasecount);
                   11565:     } else {
                   11566:         return $output;
                   11567:     }
1.661     raeburn  11568: }
                   11569: 
                   11570: sub check_for_existing {
                   11571:     my ($path,$fname,$element) = @_;
                   11572:     my ($state,$msg);
                   11573:     if (-d $path.'/'.$fname) {
                   11574:         $state = 'exists';
                   11575:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11576:     } elsif (-e $path.'/'.$fname) {
                   11577:         $state = 'exists';
                   11578:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11579:     }
                   11580:     if ($state eq 'exists') {
                   11581:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11582:     }
                   11583:     return ($state,$msg);
                   11584: }
                   11585: 
                   11586: sub check_for_upload {
                   11587:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11588:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11589:     my $filesize = length($env{'form.'.$element});
                   11590:     if (!$filesize) {
                   11591:         my $msg = '<span class="LC_error">'.
                   11592:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11593:                       '<span class="LC_filename">'.$fname.'</span>',
                   11594:                       $filesize).'<br />'.
1.1007    raeburn  11595:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11596:                   '</span>';
                   11597:         return ('zero_bytes',$msg);
                   11598:     }
                   11599:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11600:     my $getpropath = 1;
1.1021    raeburn  11601:     my ($dirlistref,$listerror) =
                   11602:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11603:     my $found_file = 0;
                   11604:     my $locked_file = 0;
1.991     raeburn  11605:     my @lockers;
                   11606:     my $navmap;
                   11607:     if ($env{'request.course.id'}) {
                   11608:         $navmap = Apache::lonnavmaps::navmap->new();
                   11609:     }
1.1021    raeburn  11610:     if (ref($dirlistref) eq 'ARRAY') {
                   11611:         foreach my $line (@{$dirlistref}) {
                   11612:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11613:             if ($file_name eq $fname){
                   11614:                 $file_name = $path.$file_name;
                   11615:                 if ($group ne '') {
                   11616:                     $file_name = $group.$file_name;
                   11617:                 }
                   11618:                 $found_file = 1;
                   11619:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11620:                     foreach my $lock (@lockers) {
                   11621:                         if (ref($lock) eq 'ARRAY') {
                   11622:                             my ($symb,$crsid) = @{$lock};
                   11623:                             if ($crsid eq $env{'request.course.id'}) {
                   11624:                                 if (ref($navmap)) {
                   11625:                                     my $res = $navmap->getBySymb($symb);
                   11626:                                     foreach my $part (@{$res->parts()}) { 
                   11627:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11628:                                         unless (($slot_status == $res->RESERVED) ||
                   11629:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11630:                                             $locked_file = 1;
                   11631:                                         }
1.991     raeburn  11632:                                     }
1.1021    raeburn  11633:                                 } else {
                   11634:                                     $locked_file = 1;
1.991     raeburn  11635:                                 }
                   11636:                             } else {
                   11637:                                 $locked_file = 1;
                   11638:                             }
                   11639:                         }
1.1021    raeburn  11640:                    }
                   11641:                 } else {
                   11642:                     my @info = split(/\&/,$rest);
                   11643:                     my $currsize = $info[6]/1000;
                   11644:                     if ($currsize < $filesize) {
                   11645:                         my $extra = $filesize - $currsize;
                   11646:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   11647:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11648:                                       &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   11649:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11650:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11651:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11652:                             return ('will_exceed_quota',$msg);
                   11653:                         }
1.984     raeburn  11654:                     }
                   11655:                 }
1.661     raeburn  11656:             }
                   11657:         }
                   11658:     }
                   11659:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   11660:         my $msg = '<p class="LC_warning">'.
                   11661:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  11662:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11663:         return ('will_exceed_quota',$msg);
                   11664:     } elsif ($found_file) {
                   11665:         if ($locked_file) {
1.1179    bisitz   11666:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11667:             $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   11668:             $msg .= '</p>';
1.661     raeburn  11669:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11670:             return ('file_locked',$msg);
                   11671:         } else {
1.1179    bisitz   11672:             my $msg = '<p class="LC_error">';
1.984     raeburn  11673:             $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   11674:             $msg .= '</p>';
1.984     raeburn  11675:             return ('existingfile',$msg);
1.661     raeburn  11676:         }
                   11677:     }
                   11678: }
                   11679: 
1.987     raeburn  11680: sub check_for_traversal {
                   11681:     my ($path,$url,$toplevel) = @_;
                   11682:     my @parts=split(/\//,$path);
                   11683:     my $cleanpath;
                   11684:     my $fullpath = $url;
                   11685:     for (my $i=0;$i<@parts;$i++) {
                   11686:         next if ($parts[$i] eq '.');
                   11687:         if ($parts[$i] eq '..') {
                   11688:             $fullpath =~ s{([^/]+/)$}{};
                   11689:         } else {
                   11690:             $fullpath .= $parts[$i].'/';
                   11691:         }
                   11692:     }
                   11693:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11694:         $cleanpath = $1;
                   11695:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11696:         my $curr_toprel = $1;
                   11697:         my @parts = split(/\//,$curr_toprel);
                   11698:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11699:         my @urlparts = split(/\//,$url_toprel);
                   11700:         my $doubledots;
                   11701:         my $startdiff = -1;
                   11702:         for (my $i=0; $i<@urlparts; $i++) {
                   11703:             if ($startdiff == -1) {
                   11704:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11705:                     $startdiff = $i;
                   11706:                     $doubledots .= '../';
                   11707:                 }
                   11708:             } else {
                   11709:                 $doubledots .= '../';
                   11710:             }
                   11711:         }
                   11712:         if ($startdiff > -1) {
                   11713:             $cleanpath = $doubledots;
                   11714:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11715:                 $cleanpath .= $parts[$i].'/';
                   11716:             }
                   11717:         }
                   11718:     }
                   11719:     $cleanpath =~ s{(/)$}{};
                   11720:     return $cleanpath;
                   11721: }
1.31      albertel 11722: 
1.1053    raeburn  11723: sub is_archive_file {
                   11724:     my ($mimetype) = @_;
                   11725:     if (($mimetype eq 'application/octet-stream') ||
                   11726:         ($mimetype eq 'application/x-stuffit') ||
                   11727:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11728:         return 1;
                   11729:     }
                   11730:     return;
                   11731: }
                   11732: 
                   11733: sub decompress_form {
1.1065    raeburn  11734:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11735:     my %lt = &Apache::lonlocal::texthash (
                   11736:         this => 'This file is an archive file.',
1.1067    raeburn  11737:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11738:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11739:         youm => 'You may wish to extract its contents.',
                   11740:         extr => 'Extract contents',
1.1067    raeburn  11741:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11742:         proa => 'Process automatically?',
1.1053    raeburn  11743:         yes  => 'Yes',
                   11744:         no   => 'No',
1.1067    raeburn  11745:         fold => 'Title for folder containing movie',
                   11746:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11747:     );
1.1065    raeburn  11748:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11749:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11750:     my $info = &list_archive_contents($fileloc,\@paths);
                   11751:     if (@paths) {
                   11752:         foreach my $path (@paths) {
                   11753:             $path =~ s{^/}{};
1.1067    raeburn  11754:             if ($path =~ m{^([^/]+)/$}) {
                   11755:                 $topdir = $1;
                   11756:             }
1.1065    raeburn  11757:             if ($path =~ m{^([^/]+)/}) {
                   11758:                 $toplevel{$1} = $path;
                   11759:             } else {
                   11760:                 $toplevel{$path} = $path;
                   11761:             }
                   11762:         }
                   11763:     }
1.1067    raeburn  11764:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  11765:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11766:                         "$topdir/media/",
                   11767:                         "$topdir/media/$topdir.mp4",
                   11768:                         "$topdir/media/FirstFrame.png",
                   11769:                         "$topdir/media/player.swf",
                   11770:                         "$topdir/media/swfobject.js",
                   11771:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  11772:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  11773:                          "$topdir/$topdir.mp4",
                   11774:                          "$topdir/$topdir\_config.xml",
                   11775:                          "$topdir/$topdir\_controller.swf",
                   11776:                          "$topdir/$topdir\_embed.css",
                   11777:                          "$topdir/$topdir\_First_Frame.png",
                   11778:                          "$topdir/$topdir\_player.html",
                   11779:                          "$topdir/$topdir\_Thumbnails.png",
                   11780:                          "$topdir/playerProductInstall.swf",
                   11781:                          "$topdir/scripts/",
                   11782:                          "$topdir/scripts/config_xml.js",
                   11783:                          "$topdir/scripts/handlebars.js",
                   11784:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11785:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11786:                          "$topdir/scripts/modernizr.js",
                   11787:                          "$topdir/scripts/player-min.js",
                   11788:                          "$topdir/scripts/swfobject.js",
                   11789:                          "$topdir/skins/",
                   11790:                          "$topdir/skins/configuration_express.xml",
                   11791:                          "$topdir/skins/express_show/",
                   11792:                          "$topdir/skins/express_show/player-min.css",
                   11793:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  11794:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11795:                          "$topdir/$topdir.mp4",
                   11796:                          "$topdir/$topdir\_config.xml",
                   11797:                          "$topdir/$topdir\_controller.swf",
                   11798:                          "$topdir/$topdir\_embed.css",
                   11799:                          "$topdir/$topdir\_First_Frame.png",
                   11800:                          "$topdir/$topdir\_player.html",
                   11801:                          "$topdir/$topdir\_Thumbnails.png",
                   11802:                          "$topdir/playerProductInstall.swf",
                   11803:                          "$topdir/scripts/",
                   11804:                          "$topdir/scripts/config_xml.js",
                   11805:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11806:                          "$topdir/skins/",
                   11807:                          "$topdir/skins/configuration_express.xml",
                   11808:                          "$topdir/skins/express_show/",
                   11809:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11810:                          "$topdir/skins/express_show/spritesheet.png",
                   11811:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  11812:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11813:         if (@diffs == 0) {
1.1164    raeburn  11814:             $is_camtasia = 6;
                   11815:         } else {
1.1197    raeburn  11816:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  11817:             if (@diffs == 0) {
                   11818:                 $is_camtasia = 8;
1.1197    raeburn  11819:             } else {
                   11820:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11821:                 if (@diffs == 0) {
                   11822:                     $is_camtasia = 8;
                   11823:                 }
1.1164    raeburn  11824:             }
1.1067    raeburn  11825:         }
                   11826:     }
                   11827:     my $output;
                   11828:     if ($is_camtasia) {
                   11829:         $output = <<"ENDCAM";
                   11830: <script type="text/javascript" language="Javascript">
                   11831: // <![CDATA[
                   11832: 
                   11833: function camtasiaToggle() {
                   11834:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11835:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  11836:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11837:                 document.getElementById('camtasia_titles').style.display='block';
                   11838:             } else {
                   11839:                 document.getElementById('camtasia_titles').style.display='none';
                   11840:             }
                   11841:         }
                   11842:     }
                   11843:     return;
                   11844: }
                   11845: 
                   11846: // ]]>
                   11847: </script>
                   11848: <p>$lt{'camt'}</p>
                   11849: ENDCAM
1.1065    raeburn  11850:     } else {
1.1067    raeburn  11851:         $output = '<p>'.$lt{'this'};
                   11852:         if ($info eq '') {
                   11853:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11854:         } else {
                   11855:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11856:                        '<div><pre>'.$info.'</pre></div>';
                   11857:         }
1.1065    raeburn  11858:     }
1.1067    raeburn  11859:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11860:     my $duplicates;
                   11861:     my $num = 0;
                   11862:     if (ref($dirlist) eq 'ARRAY') {
                   11863:         foreach my $item (@{$dirlist}) {
                   11864:             if (ref($item) eq 'ARRAY') {
                   11865:                 if (exists($toplevel{$item->[0]})) {
                   11866:                     $duplicates .= 
                   11867:                         &start_data_table_row().
                   11868:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11869:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11870:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11871:                         'value="1" />'.&mt('Yes').'</label>'.
                   11872:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11873:                         '<td>'.$item->[0].'</td>';
                   11874:                     if ($item->[2]) {
                   11875:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11876:                     } else {
                   11877:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11878:                     }
                   11879:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11880:                                    '<td>'.
                   11881:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11882:                                    '</td>'.
                   11883:                                    &end_data_table_row();
                   11884:                     $num ++;
                   11885:                 }
                   11886:             }
                   11887:         }
                   11888:     }
                   11889:     my $itemcount;
                   11890:     if (@paths > 0) {
                   11891:         $itemcount = scalar(@paths);
                   11892:     } else {
                   11893:         $itemcount = 1;
                   11894:     }
1.1067    raeburn  11895:     if ($is_camtasia) {
                   11896:         $output .= $lt{'auto'}.'<br />'.
                   11897:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  11898:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11899:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11900:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11901:                    $lt{'no'}.'</label></span><br />'.
                   11902:                    '<div id="camtasia_titles" style="display:block">'.
                   11903:                    &Apache::lonhtmlcommon::start_pick_box().
                   11904:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11905:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11906:                    &Apache::lonhtmlcommon::row_closure().
                   11907:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11908:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11909:                    &Apache::lonhtmlcommon::row_closure(1).
                   11910:                    &Apache::lonhtmlcommon::end_pick_box().
                   11911:                    '</div>';
                   11912:     }
1.1065    raeburn  11913:     $output .= 
                   11914:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11915:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11916:         "\n";
1.1065    raeburn  11917:     if ($duplicates ne '') {
                   11918:         $output .= '<p><span class="LC_warning">'.
                   11919:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11920:                    &start_data_table().
                   11921:                    &start_data_table_header_row().
                   11922:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11923:                    '<th>'.&mt('Name').'</th>'.
                   11924:                    '<th>'.&mt('Type').'</th>'.
                   11925:                    '<th>'.&mt('Size').'</th>'.
                   11926:                    '<th>'.&mt('Last modified').'</th>'.
                   11927:                    &end_data_table_header_row().
                   11928:                    $duplicates.
                   11929:                    &end_data_table().
                   11930:                    '</p>';
                   11931:     }
1.1067    raeburn  11932:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11933:     if (ref($hiddenelements) eq 'HASH') {
                   11934:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11935:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11936:         }
                   11937:     }
                   11938:     $output .= <<"END";
1.1067    raeburn  11939: <br />
1.1053    raeburn  11940: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11941: </form>
                   11942: $noextract
                   11943: END
                   11944:     return $output;
                   11945: }
                   11946: 
1.1065    raeburn  11947: sub decompression_utility {
                   11948:     my ($program) = @_;
                   11949:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11950:     my $location;
                   11951:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11952:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11953:                          '/usr/sbin/') {
                   11954:             if (-x $dir.$program) {
                   11955:                 $location = $dir.$program;
                   11956:                 last;
                   11957:             }
                   11958:         }
                   11959:     }
                   11960:     return $location;
                   11961: }
                   11962: 
                   11963: sub list_archive_contents {
                   11964:     my ($file,$pathsref) = @_;
                   11965:     my (@cmd,$output);
                   11966:     my $needsregexp;
                   11967:     if ($file =~ /\.zip$/) {
                   11968:         @cmd = (&decompression_utility('unzip'),"-l");
                   11969:         $needsregexp = 1;
                   11970:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11971:              ($file =~ /\.tgz$/)) {
                   11972:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11973:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11974:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11975:     } elsif ($file =~ m|\.tar$|) {
                   11976:         @cmd = (&decompression_utility('tar'),"-tf");
                   11977:     }
                   11978:     if (@cmd) {
                   11979:         undef($!);
                   11980:         undef($@);
                   11981:         if (open(my $fh,"-|", @cmd, $file)) {
                   11982:             while (my $line = <$fh>) {
                   11983:                 $output .= $line;
                   11984:                 chomp($line);
                   11985:                 my $item;
                   11986:                 if ($needsregexp) {
                   11987:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11988:                 } else {
                   11989:                     $item = $line;
                   11990:                 }
                   11991:                 if ($item ne '') {
                   11992:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11993:                         push(@{$pathsref},$item);
                   11994:                     } 
                   11995:                 }
                   11996:             }
                   11997:             close($fh);
                   11998:         }
                   11999:     }
                   12000:     return $output;
                   12001: }
                   12002: 
1.1053    raeburn  12003: sub decompress_uploaded_file {
                   12004:     my ($file,$dir) = @_;
                   12005:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12006:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12007:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12008:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12009:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12010:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12011:     my $decompressed = $env{'cgi.decompressed'};
                   12012:     &Apache::lonnet::delenv('cgi.file');
                   12013:     &Apache::lonnet::delenv('cgi.dir');
                   12014:     &Apache::lonnet::delenv('cgi.decompressed');
                   12015:     return ($decompressed,$result);
                   12016: }
                   12017: 
1.1055    raeburn  12018: sub process_decompression {
                   12019:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   12020:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12021:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12022:         $error = &mt('Filename not a supported archive file type.').
                   12023:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12024:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12025:     } else {
                   12026:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12027:         if ($docuhome eq 'no_host') {
                   12028:             $error = &mt('Could not determine home server for course.');
                   12029:         } else {
                   12030:             my @ids=&Apache::lonnet::current_machine_ids();
                   12031:             my $currdir = "$dir_root/$destination";
                   12032:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12033:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12034:                        "$dir_root/$destination";
                   12035:             } else {
                   12036:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12037:                        "$dir_root/$docudom/$docuname/$destination";
                   12038:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12039:                     $error = &mt('Archive file not found.');
                   12040:                 }
                   12041:             }
1.1065    raeburn  12042:             my (@to_overwrite,@to_skip);
                   12043:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12044:                 my $total = $env{'form.archive_overwrite_total'};
                   12045:                 for (my $i=0; $i<$total; $i++) {
                   12046:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12047:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12048:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12049:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12050:                     }
                   12051:                 }
                   12052:             }
                   12053:             my $numskip = scalar(@to_skip);
                   12054:             if (($numskip > 0) && 
                   12055:                 ($numskip == $env{'form.archive_itemcount'})) {
                   12056:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12057:             } elsif ($dir eq '') {
1.1055    raeburn  12058:                 $error = &mt('Directory containing archive file unavailable.');
                   12059:             } elsif (!$error) {
1.1065    raeburn  12060:                 my ($decompressed,$display);
                   12061:                 if ($numskip > 0) {
                   12062:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12063:                     mkdir("$dir/$tempdir",0755);
                   12064:                     system("mv $dir/$file $dir/$tempdir/$file");
                   12065:                     ($decompressed,$display) = 
                   12066:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   12067:                     foreach my $item (@to_skip) {
                   12068:                         if (($item ne '') && ($item !~ /\.\./)) {
                   12069:                             if (-f "$dir/$tempdir/$item") { 
                   12070:                                 unlink("$dir/$tempdir/$item");
                   12071:                             } elsif (-d "$dir/$tempdir/$item") {
                   12072:                                 system("rm -rf $dir/$tempdir/$item");
                   12073:                             }
                   12074:                         }
                   12075:                     }
                   12076:                     system("mv $dir/$tempdir/* $dir");
                   12077:                     rmdir("$dir/$tempdir");   
                   12078:                 } else {
                   12079:                     ($decompressed,$display) = 
                   12080:                         &decompress_uploaded_file($file,$dir);
                   12081:                 }
1.1055    raeburn  12082:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12083:                     $output = '<p class="LC_info">'.
                   12084:                               &mt('Files extracted successfully from archive.').
                   12085:                               '</p>'."\n";
1.1055    raeburn  12086:                     my ($warning,$result,@contents);
                   12087:                     my ($newdirlistref,$newlisterror) =
                   12088:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12089:                                                  $docuname,1);
                   12090:                     my (%is_dir,%changes,@newitems);
                   12091:                     my $dirptr = 16384;
1.1065    raeburn  12092:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12093:                         foreach my $dir_line (@{$newdirlistref}) {
                   12094:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  12095:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   12096:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  12097:                                 push(@newitems,$item);
                   12098:                                 if ($dirptr&$testdir) {
                   12099:                                     $is_dir{$item} = 1;
                   12100:                                 }
                   12101:                                 $changes{$item} = 1;
                   12102:                             }
                   12103:                         }
                   12104:                     }
                   12105:                     if (keys(%changes) > 0) {
                   12106:                         foreach my $item (sort(@newitems)) {
                   12107:                             if ($changes{$item}) {
                   12108:                                 push(@contents,$item);
                   12109:                             }
                   12110:                         }
                   12111:                     }
                   12112:                     if (@contents > 0) {
1.1067    raeburn  12113:                         my $wantform;
                   12114:                         unless ($env{'form.autoextract_camtasia'}) {
                   12115:                             $wantform = 1;
                   12116:                         }
1.1056    raeburn  12117:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12118:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12119:                                                                 $currdir,\%is_dir,
                   12120:                                                                 \%children,\%parent,
1.1056    raeburn  12121:                                                                 \@contents,\%dirorder,
                   12122:                                                                 \%titles,$wantform);
1.1055    raeburn  12123:                         if ($datatable ne '') {
                   12124:                             $output .= &archive_options_form('decompressed',$datatable,
                   12125:                                                              $count,$hiddenelem);
1.1065    raeburn  12126:                             my $startcount = 6;
1.1055    raeburn  12127:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12128:                                                            \%titles,\%children);
1.1055    raeburn  12129:                         }
1.1067    raeburn  12130:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  12131:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12132:                             my %displayed;
                   12133:                             my $total = 1;
                   12134:                             $env{'form.archive_directory'} = [];
                   12135:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12136:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12137:                                 $path =~ s{/$}{};
                   12138:                                 my $item;
                   12139:                                 if ($path ne '') {
                   12140:                                     $item = "$path/$titles{$i}";
                   12141:                                 } else {
                   12142:                                     $item = $titles{$i};
                   12143:                                 }
                   12144:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12145:                                 if ($item eq $contents[0]) {
                   12146:                                     push(@{$env{'form.archive_directory'}},$i);
                   12147:                                     $env{'form.archive_'.$i} = 'display';
                   12148:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12149:                                     $displayed{'folder'} = $i;
1.1164    raeburn  12150:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12151:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  12152:                                     $env{'form.archive_'.$i} = 'display';
                   12153:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12154:                                     $displayed{'web'} = $i;
                   12155:                                 } else {
1.1164    raeburn  12156:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12157:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12158:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12159:                                         push(@{$env{'form.archive_directory'}},$i);
                   12160:                                     }
                   12161:                                     $env{'form.archive_'.$i} = 'dependency';
                   12162:                                 }
                   12163:                                 $total ++;
                   12164:                             }
                   12165:                             for (my $i=1; $i<$total; $i++) {
                   12166:                                 next if ($i == $displayed{'web'});
                   12167:                                 next if ($i == $displayed{'folder'});
                   12168:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12169:                             }
                   12170:                             $env{'form.phase'} = 'decompress_cleanup';
                   12171:                             $env{'form.archivedelete'} = 1;
                   12172:                             $env{'form.archive_count'} = $total-1;
                   12173:                             $output .=
                   12174:                                 &process_extracted_files('coursedocs',$docudom,
                   12175:                                                          $docuname,$destination,
                   12176:                                                          $dir_root,$hiddenelem);
                   12177:                         }
1.1055    raeburn  12178:                     } else {
                   12179:                         $warning = &mt('No new items extracted from archive file.');
                   12180:                     }
                   12181:                 } else {
                   12182:                     $output = $display;
                   12183:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12184:                 }
                   12185:             }
                   12186:         }
                   12187:     }
                   12188:     if ($error) {
                   12189:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12190:                    $error.'</p>'."\n";
                   12191:     }
                   12192:     if ($warning) {
                   12193:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12194:     }
                   12195:     return $output;
                   12196: }
                   12197: 
                   12198: sub get_extracted {
1.1056    raeburn  12199:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12200:         $titles,$wantform) = @_;
1.1055    raeburn  12201:     my $count = 0;
                   12202:     my $depth = 0;
                   12203:     my $datatable;
1.1056    raeburn  12204:     my @hierarchy;
1.1055    raeburn  12205:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12206:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12207:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12208:     foreach my $item (@{$contents}) {
                   12209:         $count ++;
1.1056    raeburn  12210:         @{$dirorder->{$count}} = @hierarchy;
                   12211:         $titles->{$count} = $item;
1.1055    raeburn  12212:         &archive_hierarchy($depth,$count,$parent,$children);
                   12213:         if ($wantform) {
                   12214:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12215:                                        $currdir,$depth,$count);
                   12216:         }
                   12217:         if ($is_dir->{$item}) {
                   12218:             $depth ++;
1.1056    raeburn  12219:             push(@hierarchy,$count);
                   12220:             $parent->{$depth} = $count;
1.1055    raeburn  12221:             $datatable .=
                   12222:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12223:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12224:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12225:             $depth --;
1.1056    raeburn  12226:             pop(@hierarchy);
1.1055    raeburn  12227:         }
                   12228:     }
                   12229:     return ($count,$datatable);
                   12230: }
                   12231: 
                   12232: sub recurse_extracted_archive {
1.1056    raeburn  12233:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12234:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12235:     my $result='';
1.1056    raeburn  12236:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12237:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12238:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12239:         return $result;
                   12240:     }
                   12241:     my $dirptr = 16384;
                   12242:     my ($newdirlistref,$newlisterror) =
                   12243:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12244:     if (ref($newdirlistref) eq 'ARRAY') {
                   12245:         foreach my $dir_line (@{$newdirlistref}) {
                   12246:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12247:             unless ($item =~ /^\.+$/) {
                   12248:                 $$count ++;
1.1056    raeburn  12249:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12250:                 $titles->{$$count} = $item;
1.1055    raeburn  12251:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12252: 
1.1055    raeburn  12253:                 my $is_dir;
                   12254:                 if ($dirptr&$testdir) {
                   12255:                     $is_dir = 1;
                   12256:                 }
                   12257:                 if ($wantform) {
                   12258:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12259:                 }
                   12260:                 if ($is_dir) {
                   12261:                     $$depth ++;
1.1056    raeburn  12262:                     push(@{$hierarchy},$$count);
                   12263:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12264:                     $result .=
                   12265:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12266:                                                    $docuname,$depth,$count,
1.1056    raeburn  12267:                                                    $hierarchy,$dirorder,$children,
                   12268:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12269:                     $$depth --;
1.1056    raeburn  12270:                     pop(@{$hierarchy});
1.1055    raeburn  12271:                 }
                   12272:             }
                   12273:         }
                   12274:     }
                   12275:     return $result;
                   12276: }
                   12277: 
                   12278: sub archive_hierarchy {
                   12279:     my ($depth,$count,$parent,$children) =@_;
                   12280:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12281:         if (exists($parent->{$depth})) {
                   12282:              $children->{$parent->{$depth}} .= $count.':';
                   12283:         }
                   12284:     }
                   12285:     return;
                   12286: }
                   12287: 
                   12288: sub archive_row {
                   12289:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12290:     my ($name) = ($item =~ m{([^/]+)$});
                   12291:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12292:                                        'display'    => 'Add as file',
1.1055    raeburn  12293:                                        'dependency' => 'Include as dependency',
                   12294:                                        'discard'    => 'Discard',
                   12295:                                       );
                   12296:     if ($is_dir) {
1.1059    raeburn  12297:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12298:     }
1.1056    raeburn  12299:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12300:     my $offset = 0;
1.1055    raeburn  12301:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12302:         $offset ++;
1.1065    raeburn  12303:         if ($action ne 'display') {
                   12304:             $offset ++;
                   12305:         }  
1.1055    raeburn  12306:         $output .= '<td><span class="LC_nobreak">'.
                   12307:                    '<label><input type="radio" name="archive_'.$count.
                   12308:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12309:         my $text = $choices{$action};
                   12310:         if ($is_dir) {
                   12311:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12312:             if ($action eq 'display') {
1.1059    raeburn  12313:                 $text = &mt('Add as folder');
1.1055    raeburn  12314:             }
1.1056    raeburn  12315:         } else {
                   12316:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12317: 
                   12318:         }
                   12319:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12320:         if ($action eq 'dependency') {
                   12321:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12322:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12323:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12324:                        '<option value=""></option>'."\n".
                   12325:                        '</select>'."\n".
                   12326:                        '</div>';
1.1059    raeburn  12327:         } elsif ($action eq 'display') {
                   12328:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12329:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12330:                        '</div>';
1.1055    raeburn  12331:         }
1.1056    raeburn  12332:         $output .= '</td>';
1.1055    raeburn  12333:     }
                   12334:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12335:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12336:     for (my $i=0; $i<$depth; $i++) {
                   12337:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12338:     }
                   12339:     if ($is_dir) {
                   12340:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12341:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12342:     } else {
                   12343:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12344:     }
                   12345:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12346:                &end_data_table_row();
                   12347:     return $output;
                   12348: }
                   12349: 
                   12350: sub archive_options_form {
1.1065    raeburn  12351:     my ($form,$display,$count,$hiddenelem) = @_;
                   12352:     my %lt = &Apache::lonlocal::texthash(
                   12353:                perm => 'Permanently remove archive file?',
                   12354:                hows => 'How should each extracted item be incorporated in the course?',
                   12355:                cont => 'Content actions for all',
                   12356:                addf => 'Add as folder/file',
                   12357:                incd => 'Include as dependency for a displayed file',
                   12358:                disc => 'Discard',
                   12359:                no   => 'No',
                   12360:                yes  => 'Yes',
                   12361:                save => 'Save',
                   12362:     );
                   12363:     my $output = <<"END";
                   12364: <form name="$form" method="post" action="">
                   12365: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12366: <label>
                   12367:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12368: </label>
                   12369: &nbsp;
                   12370: <label>
                   12371:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12372: </span>
                   12373: </p>
                   12374: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12375: <br />$lt{'hows'}
                   12376: <div class="LC_columnSection">
                   12377:   <fieldset>
                   12378:     <legend>$lt{'cont'}</legend>
                   12379:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12380:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12381:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12382:   </fieldset>
                   12383: </div>
                   12384: END
                   12385:     return $output.
1.1055    raeburn  12386:            &start_data_table()."\n".
1.1065    raeburn  12387:            $display."\n".
1.1055    raeburn  12388:            &end_data_table()."\n".
                   12389:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12390:            $hiddenelem.
1.1065    raeburn  12391:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12392:            '</form>';
                   12393: }
                   12394: 
                   12395: sub archive_javascript {
1.1056    raeburn  12396:     my ($startcount,$numitems,$titles,$children) = @_;
                   12397:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12398:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12399:     my $scripttag = <<START;
                   12400: <script type="text/javascript">
                   12401: // <![CDATA[
                   12402: 
                   12403: function checkAll(form,prefix) {
                   12404:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12405:     for (var i=0; i < form.elements.length; i++) {
                   12406:         var id = form.elements[i].id;
                   12407:         if ((id != '') && (id != undefined)) {
                   12408:             if (idstr.test(id)) {
                   12409:                 if (form.elements[i].type == 'radio') {
                   12410:                     form.elements[i].checked = true;
1.1056    raeburn  12411:                     var nostart = i-$startcount;
1.1059    raeburn  12412:                     var offset = nostart%7;
                   12413:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12414:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12415:                 }
                   12416:             }
                   12417:         }
                   12418:     }
                   12419: }
                   12420: 
                   12421: function propagateCheck(form,count) {
                   12422:     if (count > 0) {
1.1059    raeburn  12423:         var startelement = $startcount + ((count-1) * 7);
                   12424:         for (var j=1; j<6; j++) {
                   12425:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12426:                 var item = startelement + j; 
                   12427:                 if (form.elements[item].type == 'radio') {
                   12428:                     if (form.elements[item].checked) {
                   12429:                         containerCheck(form,count,j);
                   12430:                         break;
                   12431:                     }
1.1055    raeburn  12432:                 }
                   12433:             }
                   12434:         }
                   12435:     }
                   12436: }
                   12437: 
                   12438: numitems = $numitems
1.1056    raeburn  12439: var titles = new Array(numitems);
                   12440: var parents = new Array(numitems);
1.1055    raeburn  12441: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12442:     parents[i] = new Array;
1.1055    raeburn  12443: }
1.1059    raeburn  12444: var maintitle = '$maintitle';
1.1055    raeburn  12445: 
                   12446: START
                   12447: 
1.1056    raeburn  12448:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12449:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12450:         for (my $i=0; $i<@contents; $i ++) {
                   12451:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12452:         }
                   12453:     }
                   12454: 
1.1056    raeburn  12455:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12456:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12457:     }
                   12458: 
1.1055    raeburn  12459:     $scripttag .= <<END;
                   12460: 
                   12461: function containerCheck(form,count,offset) {
                   12462:     if (count > 0) {
1.1056    raeburn  12463:         dependencyCheck(form,count,offset);
1.1059    raeburn  12464:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12465:         form.elements[item].checked = true;
                   12466:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12467:             if (parents[count].length > 0) {
                   12468:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12469:                     containerCheck(form,parents[count][j],offset);
                   12470:                 }
                   12471:             }
                   12472:         }
                   12473:     }
                   12474: }
                   12475: 
                   12476: function dependencyCheck(form,count,offset) {
                   12477:     if (count > 0) {
1.1059    raeburn  12478:         var chosen = (offset+$startcount)+7*(count-1);
                   12479:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12480:         var currtype = form.elements[depitem].type;
                   12481:         if (form.elements[chosen].value == 'dependency') {
                   12482:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12483:             form.elements[depitem].options.length = 0;
                   12484:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  12485:             for (var i=1; i<=numitems; i++) {
                   12486:                 if (i == count) {
                   12487:                     continue;
                   12488:                 }
1.1059    raeburn  12489:                 var startelement = $startcount + (i-1) * 7;
                   12490:                 for (var j=1; j<6; j++) {
                   12491:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12492:                         var item = startelement + j;
                   12493:                         if (form.elements[item].type == 'radio') {
                   12494:                             if (form.elements[item].checked) {
                   12495:                                 if (form.elements[item].value == 'display') {
                   12496:                                     var n = form.elements[depitem].options.length;
                   12497:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12498:                                 }
                   12499:                             }
                   12500:                         }
                   12501:                     }
                   12502:                 }
                   12503:             }
                   12504:         } else {
                   12505:             document.getElementById('arc_depon_'+count).style.display='none';
                   12506:             form.elements[depitem].options.length = 0;
                   12507:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12508:         }
1.1059    raeburn  12509:         titleCheck(form,count,offset);
1.1056    raeburn  12510:     }
                   12511: }
                   12512: 
                   12513: function propagateSelect(form,count,offset) {
                   12514:     if (count > 0) {
1.1065    raeburn  12515:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12516:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12517:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12518:             if (parents[count].length > 0) {
                   12519:                 for (var j=0; j<parents[count].length; j++) {
                   12520:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12521:                 }
                   12522:             }
                   12523:         }
                   12524:     }
                   12525: }
1.1056    raeburn  12526: 
                   12527: function containerSelect(form,count,offset,picked) {
                   12528:     if (count > 0) {
1.1065    raeburn  12529:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12530:         if (form.elements[item].type == 'radio') {
                   12531:             if (form.elements[item].value == 'dependency') {
                   12532:                 if (form.elements[item+1].type == 'select-one') {
                   12533:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12534:                         if (form.elements[item+1].options[i].value == picked) {
                   12535:                             form.elements[item+1].selectedIndex = i;
                   12536:                             break;
                   12537:                         }
                   12538:                     }
                   12539:                 }
                   12540:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12541:                     if (parents[count].length > 0) {
                   12542:                         for (var j=0; j<parents[count].length; j++) {
                   12543:                             containerSelect(form,parents[count][j],offset,picked);
                   12544:                         }
                   12545:                     }
                   12546:                 }
                   12547:             }
                   12548:         }
                   12549:     }
                   12550: }
                   12551: 
1.1059    raeburn  12552: function titleCheck(form,count,offset) {
                   12553:     if (count > 0) {
                   12554:         var chosen = (offset+$startcount)+7*(count-1);
                   12555:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12556:         var currtype = form.elements[depitem].type;
                   12557:         if (form.elements[chosen].value == 'display') {
                   12558:             document.getElementById('arc_title_'+count).style.display='block';
                   12559:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12560:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12561:             }
                   12562:         } else {
                   12563:             document.getElementById('arc_title_'+count).style.display='none';
                   12564:             if (currtype == 'text') { 
                   12565:                 document.getElementById('archive_title_'+count).value='';
                   12566:             }
                   12567:         }
                   12568:     }
                   12569:     return;
                   12570: }
                   12571: 
1.1055    raeburn  12572: // ]]>
                   12573: </script>
                   12574: END
                   12575:     return $scripttag;
                   12576: }
                   12577: 
                   12578: sub process_extracted_files {
1.1067    raeburn  12579:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12580:     my $numitems = $env{'form.archive_count'};
                   12581:     return unless ($numitems);
                   12582:     my @ids=&Apache::lonnet::current_machine_ids();
                   12583:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12584:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12585:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12586:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12587:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12588:         $pathtocheck = "$dir_root/$destination";
                   12589:         $dir = $dir_root;
                   12590:         $ishome = 1;
                   12591:     } else {
                   12592:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12593:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12594:         $dir = "$dir_root/$docudom/$docuname";    
                   12595:     }
                   12596:     my $currdir = "$dir_root/$destination";
                   12597:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12598:     if ($env{'form.folderpath'}) {
                   12599:         my @items = split('&',$env{'form.folderpath'});
                   12600:         $folders{'0'} = $items[-2];
1.1099    raeburn  12601:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12602:             $containers{'0'}='page';
                   12603:         } else {  
                   12604:             $containers{'0'}='sequence';
                   12605:         }
1.1055    raeburn  12606:     }
                   12607:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12608:     if ($numitems) {
                   12609:         for (my $i=1; $i<=$numitems; $i++) {
                   12610:             my $path = $env{'form.archive_content_'.$i};
                   12611:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12612:                 my $item = $1;
                   12613:                 $toplevelitems{$item} = $i;
                   12614:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12615:                     $is_dir{$item} = 1;
                   12616:                 }
                   12617:             }
                   12618:         }
                   12619:     }
1.1067    raeburn  12620:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12621:     if (keys(%toplevelitems) > 0) {
                   12622:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12623:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12624:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12625:     }
1.1066    raeburn  12626:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12627:     if ($numitems) {
                   12628:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  12629:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12630:             my $path = $env{'form.archive_content_'.$i};
                   12631:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12632:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12633:                     if ($prefix ne '' && $path ne '') {
                   12634:                         if (-e $prefix.$path) {
1.1066    raeburn  12635:                             if ((@archdirs > 0) && 
                   12636:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12637:                                 $todeletedir{$prefix.$path} = 1;
                   12638:                             } else {
                   12639:                                 $todelete{$prefix.$path} = 1;
                   12640:                             }
1.1055    raeburn  12641:                         }
                   12642:                     }
                   12643:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12644:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12645:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12646:                     $docstitle = $env{'form.archive_title_'.$i};
                   12647:                     if ($docstitle eq '') {
                   12648:                         $docstitle = $title;
                   12649:                     }
1.1055    raeburn  12650:                     $outer = 0;
1.1056    raeburn  12651:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12652:                         if (@{$dirorder{$i}} > 0) {
                   12653:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12654:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12655:                                     $outer = $item;
                   12656:                                     last;
                   12657:                                 }
                   12658:                             }
                   12659:                         }
                   12660:                     }
                   12661:                     my ($errtext,$fatal) = 
                   12662:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12663:                                                '/'.$folders{$outer}.'.'.
                   12664:                                                $containers{$outer});
                   12665:                     next if ($fatal);
                   12666:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12667:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12668:                             $mapinner{$i} = time;
1.1055    raeburn  12669:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12670:                             $containers{$i} = 'sequence';
                   12671:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12672:                                       $folders{$i}.'.'.$containers{$i};
                   12673:                             my $newidx = &LONCAPA::map::getresidx();
                   12674:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12675:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12676:                             push(@LONCAPA::map::order,$newidx);
                   12677:                             my ($outtext,$errtext) =
                   12678:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12679:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12680:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12681:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12682:                             unless ($errtext) {
                   12683:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12684:                             }
1.1055    raeburn  12685:                         }
                   12686:                     } else {
                   12687:                         if ($context eq 'coursedocs') {
                   12688:                             my $newidx=&LONCAPA::map::getresidx();
                   12689:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12690:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12691:                                       $title;
                   12692:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12693:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12694:                             }
                   12695:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12696:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12697:                             }
                   12698:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12699:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12700:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12701:                                 unless ($ishome) {
                   12702:                                     my $fetch = "$newdest{$i}/$title";
                   12703:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12704:                                     $prompttofetch{$fetch} = 1;
                   12705:                                 }
1.1055    raeburn  12706:                             }
                   12707:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12708:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12709:                             push(@LONCAPA::map::order, $newidx);
                   12710:                             my ($outtext,$errtext)=
                   12711:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12712:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12713:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12714:                             unless ($errtext) {
                   12715:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12716:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12717:                                 }
                   12718:                             }
1.1055    raeburn  12719:                         }
                   12720:                     }
1.1086    raeburn  12721:                 }
                   12722:             } else {
                   12723:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12724:             }
                   12725:         }
                   12726:         for (my $i=1; $i<=$numitems; $i++) {
                   12727:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12728:             my $path = $env{'form.archive_content_'.$i};
                   12729:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12730:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12731:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12732:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12733:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12734:                         my ($itemidx,$fullpath,$relpath);
                   12735:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12736:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12737:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  12738:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12739:                                     $itemidx = $j;
1.1056    raeburn  12740:                                 }
                   12741:                             }
1.1086    raeburn  12742:                         }
                   12743:                         if ($itemidx eq '') {
                   12744:                             $itemidx =  0;
                   12745:                         } 
                   12746:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12747:                             if ($mapinner{$referrer{$i}}) {
                   12748:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12749:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12750:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12751:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12752:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12753:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12754:                                             if (!-e $fullpath) {
                   12755:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12756:                                             }
                   12757:                                         }
1.1086    raeburn  12758:                                     } else {
                   12759:                                         last;
1.1056    raeburn  12760:                                     }
1.1086    raeburn  12761:                                 }
                   12762:                             }
                   12763:                         } elsif ($newdest{$referrer{$i}}) {
                   12764:                             $fullpath = $newdest{$referrer{$i}};
                   12765:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12766:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12767:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12768:                                     last;
                   12769:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12770:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12771:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12772:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12773:                                         if (!-e $fullpath) {
                   12774:                                             mkdir($fullpath,0755);
1.1056    raeburn  12775:                                         }
                   12776:                                     }
1.1086    raeburn  12777:                                 } else {
                   12778:                                     last;
1.1056    raeburn  12779:                                 }
1.1055    raeburn  12780:                             }
                   12781:                         }
1.1086    raeburn  12782:                         if ($fullpath ne '') {
                   12783:                             if (-e "$prefix$path") {
                   12784:                                 system("mv $prefix$path $fullpath/$title");
                   12785:                             }
                   12786:                             if (-e "$fullpath/$title") {
                   12787:                                 my $showpath;
                   12788:                                 if ($relpath ne '') {
                   12789:                                     $showpath = "$relpath/$title";
                   12790:                                 } else {
                   12791:                                     $showpath = "/$title";
                   12792:                                 } 
                   12793:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12794:                             } 
                   12795:                             unless ($ishome) {
                   12796:                                 my $fetch = "$fullpath/$title";
                   12797:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   12798:                                 $prompttofetch{$fetch} = 1;
                   12799:                             }
                   12800:                         }
1.1055    raeburn  12801:                     }
1.1086    raeburn  12802:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12803:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12804:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12805:                 }
                   12806:             } else {
                   12807:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12808:             }
                   12809:         }
                   12810:         if (keys(%todelete)) {
                   12811:             foreach my $key (keys(%todelete)) {
                   12812:                 unlink($key);
1.1066    raeburn  12813:             }
                   12814:         }
                   12815:         if (keys(%todeletedir)) {
                   12816:             foreach my $key (keys(%todeletedir)) {
                   12817:                 rmdir($key);
                   12818:             }
                   12819:         }
                   12820:         foreach my $dir (sort(keys(%is_dir))) {
                   12821:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12822:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12823:             }
                   12824:         }
1.1067    raeburn  12825:         if ($result ne '') {
                   12826:             $output .= '<ul>'."\n".
                   12827:                        $result."\n".
                   12828:                        '</ul>';
                   12829:         }
                   12830:         unless ($ishome) {
                   12831:             my $replicationfail;
                   12832:             foreach my $item (keys(%prompttofetch)) {
                   12833:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12834:                 unless ($fetchresult eq 'ok') {
                   12835:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12836:                 }
                   12837:             }
                   12838:             if ($replicationfail) {
                   12839:                 $output .= '<p class="LC_error">'.
                   12840:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12841:                            $replicationfail.
                   12842:                            '</ul></p>';
                   12843:             }
                   12844:         }
1.1055    raeburn  12845:     } else {
                   12846:         $warning = &mt('No items found in archive.');
                   12847:     }
                   12848:     if ($error) {
                   12849:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12850:                    $error.'</p>'."\n";
                   12851:     }
                   12852:     if ($warning) {
                   12853:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12854:     }
                   12855:     return $output;
                   12856: }
                   12857: 
1.1066    raeburn  12858: sub cleanup_empty_dirs {
                   12859:     my ($path) = @_;
                   12860:     if (($path ne '') && (-d $path)) {
                   12861:         if (opendir(my $dirh,$path)) {
                   12862:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12863:             my $numitems = 0;
                   12864:             foreach my $item (@dircontents) {
                   12865:                 if (-d "$path/$item") {
1.1111    raeburn  12866:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12867:                     if (-e "$path/$item") {
                   12868:                         $numitems ++;
                   12869:                     }
                   12870:                 } else {
                   12871:                     $numitems ++;
                   12872:                 }
                   12873:             }
                   12874:             if ($numitems == 0) {
                   12875:                 rmdir($path);
                   12876:             }
                   12877:             closedir($dirh);
                   12878:         }
                   12879:     }
                   12880:     return;
                   12881: }
                   12882: 
1.41      ng       12883: =pod
1.45      matthew  12884: 
1.1162    raeburn  12885: =item * &get_folder_hierarchy()
1.1068    raeburn  12886: 
                   12887: Provides hierarchy of names of folders/sub-folders containing the current
                   12888: item,
                   12889: 
                   12890: Inputs: 3
                   12891:      - $navmap - navmaps object
                   12892: 
                   12893:      - $map - url for map (either the trigger itself, or map containing
                   12894:                            the resource, which is the trigger).
                   12895: 
                   12896:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12897: 
                   12898: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12899: 
                   12900: =cut
                   12901: 
                   12902: sub get_folder_hierarchy {
                   12903:     my ($navmap,$map,$showitem) = @_;
                   12904:     my @pathitems;
                   12905:     if (ref($navmap)) {
                   12906:         my $mapres = $navmap->getResourceByUrl($map);
                   12907:         if (ref($mapres)) {
                   12908:             my $pcslist = $mapres->map_hierarchy();
                   12909:             if ($pcslist ne '') {
                   12910:                 my @pcs = split(/,/,$pcslist);
                   12911:                 foreach my $pc (@pcs) {
                   12912:                     if ($pc == 1) {
1.1129    raeburn  12913:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12914:                     } else {
                   12915:                         my $res = $navmap->getByMapPc($pc);
                   12916:                         if (ref($res)) {
                   12917:                             my $title = $res->compTitle();
                   12918:                             $title =~ s/\W+/_/g;
                   12919:                             if ($title ne '') {
                   12920:                                 push(@pathitems,$title);
                   12921:                             }
                   12922:                         }
                   12923:                     }
                   12924:                 }
                   12925:             }
1.1071    raeburn  12926:             if ($showitem) {
                   12927:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  12928:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12929:                 } else {
                   12930:                     my $maptitle = $mapres->compTitle();
                   12931:                     $maptitle =~ s/\W+/_/g;
                   12932:                     if ($maptitle ne '') {
                   12933:                         push(@pathitems,$maptitle);
                   12934:                     }
1.1068    raeburn  12935:                 }
                   12936:             }
                   12937:         }
                   12938:     }
                   12939:     return @pathitems;
                   12940: }
                   12941: 
                   12942: =pod
                   12943: 
1.1015    raeburn  12944: =item * &get_turnedin_filepath()
                   12945: 
                   12946: Determines path in a user's portfolio file for storage of files uploaded
                   12947: to a specific essayresponse or dropbox item.
                   12948: 
                   12949: Inputs: 3 required + 1 optional.
                   12950: $symb is symb for resource, $uname and $udom are for current user (required).
                   12951: $caller is optional (can be "submission", if routine is called when storing
                   12952: an upoaded file when "Submit Answer" button was pressed).
                   12953: 
                   12954: Returns array containing $path and $multiresp. 
                   12955: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12956: than one file upload item.  Callers of routine should append partid as a 
                   12957: subdirectory to $path in cases where $multiresp is 1.
                   12958: 
                   12959: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12960: 
                   12961: =cut
                   12962: 
                   12963: sub get_turnedin_filepath {
                   12964:     my ($symb,$uname,$udom,$caller) = @_;
                   12965:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12966:     my $turnindir;
                   12967:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12968:     $turnindir = $userhash{'turnindir'};
                   12969:     my ($path,$multiresp);
                   12970:     if ($turnindir eq '') {
                   12971:         if ($caller eq 'submission') {
                   12972:             $turnindir = &mt('turned in');
                   12973:             $turnindir =~ s/\W+/_/g;
                   12974:             my %newhash = (
                   12975:                             'turnindir' => $turnindir,
                   12976:                           );
                   12977:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12978:         }
                   12979:     }
                   12980:     if ($turnindir ne '') {
                   12981:         $path = '/'.$turnindir.'/';
                   12982:         my ($multipart,$turnin,@pathitems);
                   12983:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12984:         if (defined($navmap)) {
                   12985:             my $mapres = $navmap->getResourceByUrl($map);
                   12986:             if (ref($mapres)) {
                   12987:                 my $pcslist = $mapres->map_hierarchy();
                   12988:                 if ($pcslist ne '') {
                   12989:                     foreach my $pc (split(/,/,$pcslist)) {
                   12990:                         my $res = $navmap->getByMapPc($pc);
                   12991:                         if (ref($res)) {
                   12992:                             my $title = $res->compTitle();
                   12993:                             $title =~ s/\W+/_/g;
                   12994:                             if ($title ne '') {
1.1149    raeburn  12995:                                 if (($pc > 1) && (length($title) > 12)) {
                   12996:                                     $title = substr($title,0,12);
                   12997:                                 }
1.1015    raeburn  12998:                                 push(@pathitems,$title);
                   12999:                             }
                   13000:                         }
                   13001:                     }
                   13002:                 }
                   13003:                 my $maptitle = $mapres->compTitle();
                   13004:                 $maptitle =~ s/\W+/_/g;
                   13005:                 if ($maptitle ne '') {
1.1149    raeburn  13006:                     if (length($maptitle) > 12) {
                   13007:                         $maptitle = substr($maptitle,0,12);
                   13008:                     }
1.1015    raeburn  13009:                     push(@pathitems,$maptitle);
                   13010:                 }
                   13011:                 unless ($env{'request.state'} eq 'construct') {
                   13012:                     my $res = $navmap->getBySymb($symb);
                   13013:                     if (ref($res)) {
                   13014:                         my $partlist = $res->parts();
                   13015:                         my $totaluploads = 0;
                   13016:                         if (ref($partlist) eq 'ARRAY') {
                   13017:                             foreach my $part (@{$partlist}) {
                   13018:                                 my @types = $res->responseType($part);
                   13019:                                 my @ids = $res->responseIds($part);
                   13020:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13021:                                     if ($types[$i] eq 'essay') {
                   13022:                                         my $partid = $part.'_'.$ids[$i];
                   13023:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13024:                                             $totaluploads ++;
                   13025:                                         }
                   13026:                                     }
                   13027:                                 }
                   13028:                             }
                   13029:                             if ($totaluploads > 1) {
                   13030:                                 $multiresp = 1;
                   13031:                             }
                   13032:                         }
                   13033:                     }
                   13034:                 }
                   13035:             } else {
                   13036:                 return;
                   13037:             }
                   13038:         } else {
                   13039:             return;
                   13040:         }
                   13041:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13042:         $restitle =~ s/\W+/_/g;
                   13043:         if ($restitle eq '') {
                   13044:             $restitle = ($resurl =~ m{/[^/]+$});
                   13045:             if ($restitle eq '') {
                   13046:                 $restitle = time;
                   13047:             }
                   13048:         }
1.1149    raeburn  13049:         if (length($restitle) > 12) {
                   13050:             $restitle = substr($restitle,0,12);
                   13051:         }
1.1015    raeburn  13052:         push(@pathitems,$restitle);
                   13053:         $path .= join('/',@pathitems);
                   13054:     }
                   13055:     return ($path,$multiresp);
                   13056: }
                   13057: 
                   13058: =pod
                   13059: 
1.464     albertel 13060: =back
1.41      ng       13061: 
1.112     bowersj2 13062: =head1 CSV Upload/Handling functions
1.38      albertel 13063: 
1.41      ng       13064: =over 4
                   13065: 
1.648     raeburn  13066: =item * &upfile_store($r)
1.41      ng       13067: 
                   13068: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13069: needs $env{'form.upfile'}
1.41      ng       13070: returns $datatoken to be put into hidden field
                   13071: 
                   13072: =cut
1.31      albertel 13073: 
                   13074: sub upfile_store {
                   13075:     my $r=shift;
1.258     albertel 13076:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13077:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13078:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13079:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13080: 
1.258     albertel 13081:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   13082: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 13083:     {
1.158     raeburn  13084:         my $datafile = $r->dir_config('lonDaemons').
                   13085:                            '/tmp/'.$datatoken.'.tmp';
                   13086:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13087:             print $fh $env{'form.upfile'};
1.158     raeburn  13088:             close($fh);
                   13089:         }
1.31      albertel 13090:     }
                   13091:     return $datatoken;
                   13092: }
                   13093: 
1.56      matthew  13094: =pod
                   13095: 
1.648     raeburn  13096: =item * &load_tmp_file($r)
1.41      ng       13097: 
                   13098: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 13099: needs $env{'form.datatoken'},
                   13100: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13101: 
                   13102: =cut
1.31      albertel 13103: 
                   13104: sub load_tmp_file {
                   13105:     my $r=shift;
                   13106:     my @studentdata=();
                   13107:     {
1.158     raeburn  13108:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13109:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13110:         if ( open(my $fh,"<$studentfile") ) {
                   13111:             @studentdata=<$fh>;
                   13112:             close($fh);
                   13113:         }
1.31      albertel 13114:     }
1.258     albertel 13115:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13116: }
                   13117: 
1.56      matthew  13118: =pod
                   13119: 
1.648     raeburn  13120: =item * &upfile_record_sep()
1.41      ng       13121: 
                   13122: Separate uploaded file into records
                   13123: returns array of records,
1.258     albertel 13124: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13125: 
                   13126: =cut
1.31      albertel 13127: 
                   13128: sub upfile_record_sep {
1.258     albertel 13129:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13130:     } else {
1.248     albertel 13131: 	my @records;
1.258     albertel 13132: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13133: 	    if ($line=~/^\s*$/) { next; }
                   13134: 	    push(@records,$line);
                   13135: 	}
                   13136: 	return @records;
1.31      albertel 13137:     }
                   13138: }
                   13139: 
1.56      matthew  13140: =pod
                   13141: 
1.648     raeburn  13142: =item * &record_sep($record)
1.41      ng       13143: 
1.258     albertel 13144: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13145: 
                   13146: =cut
                   13147: 
1.263     www      13148: sub takeleft {
                   13149:     my $index=shift;
                   13150:     return substr('0000'.$index,-4,4);
                   13151: }
                   13152: 
1.31      albertel 13153: sub record_sep {
                   13154:     my $record=shift;
                   13155:     my %components=();
1.258     albertel 13156:     if ($env{'form.upfiletype'} eq 'xml') {
                   13157:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13158:         my $i=0;
1.356     albertel 13159:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13160:             $field=~s/^(\"|\')//;
                   13161:             $field=~s/(\"|\')$//;
1.263     www      13162:             $components{&takeleft($i)}=$field;
1.31      albertel 13163:             $i++;
                   13164:         }
1.258     albertel 13165:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13166:         my $i=0;
1.356     albertel 13167:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13168:             $field=~s/^(\"|\')//;
                   13169:             $field=~s/(\"|\')$//;
1.263     www      13170:             $components{&takeleft($i)}=$field;
1.31      albertel 13171:             $i++;
                   13172:         }
                   13173:     } else {
1.561     www      13174:         my $separator=',';
1.480     banghart 13175:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13176:             $separator=';';
1.480     banghart 13177:         }
1.31      albertel 13178:         my $i=0;
1.561     www      13179: # the character we are looking for to indicate the end of a quote or a record 
                   13180:         my $looking_for=$separator;
                   13181: # do not add the characters to the fields
                   13182:         my $ignore=0;
                   13183: # we just encountered a separator (or the beginning of the record)
                   13184:         my $just_found_separator=1;
                   13185: # store the field we are working on here
                   13186:         my $field='';
                   13187: # work our way through all characters in record
                   13188:         foreach my $character ($record=~/(.)/g) {
                   13189:             if ($character eq $looking_for) {
                   13190:                if ($character ne $separator) {
                   13191: # Found the end of a quote, again looking for separator
                   13192:                   $looking_for=$separator;
                   13193:                   $ignore=1;
                   13194:                } else {
                   13195: # Found a separator, store away what we got
                   13196:                   $components{&takeleft($i)}=$field;
                   13197: 	          $i++;
                   13198:                   $just_found_separator=1;
                   13199:                   $ignore=0;
                   13200:                   $field='';
                   13201:                }
                   13202:                next;
                   13203:             }
                   13204: # single or double quotation marks after a separator indicate beginning of a quote
                   13205: # we are now looking for the end of the quote and need to ignore separators
                   13206:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13207:                $looking_for=$character;
                   13208:                next;
                   13209:             }
                   13210: # ignore would be true after we reached the end of a quote
                   13211:             if ($ignore) { next; }
                   13212:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13213:             $field.=$character;
                   13214:             $just_found_separator=0; 
1.31      albertel 13215:         }
1.561     www      13216: # catch the very last entry, since we never encountered the separator
                   13217:         $components{&takeleft($i)}=$field;
1.31      albertel 13218:     }
                   13219:     return %components;
                   13220: }
                   13221: 
1.144     matthew  13222: ######################################################
                   13223: ######################################################
                   13224: 
1.56      matthew  13225: =pod
                   13226: 
1.648     raeburn  13227: =item * &upfile_select_html()
1.41      ng       13228: 
1.144     matthew  13229: Return HTML code to select a file from the users machine and specify 
                   13230: the file type.
1.41      ng       13231: 
                   13232: =cut
                   13233: 
1.144     matthew  13234: ######################################################
                   13235: ######################################################
1.31      albertel 13236: sub upfile_select_html {
1.144     matthew  13237:     my %Types = (
                   13238:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13239:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13240:                  space => &mt('Space separated'),
                   13241:                  tab   => &mt('Tabulator separated'),
                   13242: #                 xml   => &mt('HTML/XML'),
                   13243:                  );
                   13244:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13245:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13246:     foreach my $type (sort(keys(%Types))) {
                   13247:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13248:     }
                   13249:     $Str .= "</select>\n";
                   13250:     return $Str;
1.31      albertel 13251: }
                   13252: 
1.301     albertel 13253: sub get_samples {
                   13254:     my ($records,$toget) = @_;
                   13255:     my @samples=({});
                   13256:     my $got=0;
                   13257:     foreach my $rec (@$records) {
                   13258: 	my %temp = &record_sep($rec);
                   13259: 	if (! grep(/\S/, values(%temp))) { next; }
                   13260: 	if (%temp) {
                   13261: 	    $samples[$got]=\%temp;
                   13262: 	    $got++;
                   13263: 	    if ($got == $toget) { last; }
                   13264: 	}
                   13265:     }
                   13266:     return \@samples;
                   13267: }
                   13268: 
1.144     matthew  13269: ######################################################
                   13270: ######################################################
                   13271: 
1.56      matthew  13272: =pod
                   13273: 
1.648     raeburn  13274: =item * &csv_print_samples($r,$records)
1.41      ng       13275: 
                   13276: Prints a table of sample values from each column uploaded $r is an
                   13277: Apache Request ref, $records is an arrayref from
                   13278: &Apache::loncommon::upfile_record_sep
                   13279: 
                   13280: =cut
                   13281: 
1.144     matthew  13282: ######################################################
                   13283: ######################################################
1.31      albertel 13284: sub csv_print_samples {
                   13285:     my ($r,$records) = @_;
1.662     bisitz   13286:     my $samples = &get_samples($records,5);
1.301     albertel 13287: 
1.594     raeburn  13288:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13289:               &start_data_table_header_row());
1.356     albertel 13290:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13291:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13292:     $r->print(&end_data_table_header_row());
1.301     albertel 13293:     foreach my $hash (@$samples) {
1.594     raeburn  13294: 	$r->print(&start_data_table_row());
1.356     albertel 13295: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13296: 	    $r->print('<td>');
1.356     albertel 13297: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13298: 	    $r->print('</td>');
                   13299: 	}
1.594     raeburn  13300: 	$r->print(&end_data_table_row());
1.31      albertel 13301:     }
1.594     raeburn  13302:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13303: }
                   13304: 
1.144     matthew  13305: ######################################################
                   13306: ######################################################
                   13307: 
1.56      matthew  13308: =pod
                   13309: 
1.648     raeburn  13310: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13311: 
                   13312: Prints a table to create associations between values and table columns.
1.144     matthew  13313: 
1.41      ng       13314: $r is an Apache Request ref,
                   13315: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13316: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13317: 
                   13318: =cut
                   13319: 
1.144     matthew  13320: ######################################################
                   13321: ######################################################
1.31      albertel 13322: sub csv_print_select_table {
                   13323:     my ($r,$records,$d) = @_;
1.301     albertel 13324:     my $i=0;
                   13325:     my $samples = &get_samples($records,1);
1.144     matthew  13326:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13327: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13328:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13329:               '<th>'.&mt('Column').'</th>'.
                   13330:               &end_data_table_header_row()."\n");
1.356     albertel 13331:     foreach my $array_ref (@$d) {
                   13332: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13333: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13334: 
1.875     bisitz   13335: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13336: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13337: 	$r->print('<option value="none"></option>');
1.356     albertel 13338: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13339: 	    $r->print('<option value="'.$sample.'"'.
                   13340:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13341:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13342: 	}
1.594     raeburn  13343: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13344: 	$i++;
                   13345:     }
1.594     raeburn  13346:     $r->print(&end_data_table());
1.31      albertel 13347:     $i--;
                   13348:     return $i;
                   13349: }
1.56      matthew  13350: 
1.144     matthew  13351: ######################################################
                   13352: ######################################################
                   13353: 
1.56      matthew  13354: =pod
1.31      albertel 13355: 
1.648     raeburn  13356: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13357: 
                   13358: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13359: 
                   13360: $r is an Apache Request ref,
                   13361: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13362: $d is an array of 2 element arrays (internal name, displayed name)
                   13363: 
                   13364: =cut
                   13365: 
1.144     matthew  13366: ######################################################
                   13367: ######################################################
1.31      albertel 13368: sub csv_samples_select_table {
                   13369:     my ($r,$records,$d) = @_;
                   13370:     my $i=0;
1.144     matthew  13371:     #
1.662     bisitz   13372:     my $max_samples = 5;
                   13373:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13374:     $r->print(&start_data_table().
                   13375:               &start_data_table_header_row().'<th>'.
                   13376:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13377:               &end_data_table_header_row());
1.301     albertel 13378: 
                   13379:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13380: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13381: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13382: 	foreach my $option (@$d) {
                   13383: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13384: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13385:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13386:                       $display.'</option>');
1.31      albertel 13387: 	}
                   13388: 	$r->print('</select></td><td>');
1.662     bisitz   13389: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13390: 	    if (defined($samples->[$line]{$key})) { 
                   13391: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13392: 	    }
                   13393: 	}
1.594     raeburn  13394: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13395: 	$i++;
                   13396:     }
1.594     raeburn  13397:     $r->print(&end_data_table());
1.31      albertel 13398:     $i--;
                   13399:     return($i);
1.115     matthew  13400: }
                   13401: 
1.144     matthew  13402: ######################################################
                   13403: ######################################################
                   13404: 
1.115     matthew  13405: =pod
                   13406: 
1.648     raeburn  13407: =item * &clean_excel_name($name)
1.115     matthew  13408: 
                   13409: Returns a replacement for $name which does not contain any illegal characters.
                   13410: 
                   13411: =cut
                   13412: 
1.144     matthew  13413: ######################################################
                   13414: ######################################################
1.115     matthew  13415: sub clean_excel_name {
                   13416:     my ($name) = @_;
                   13417:     $name =~ s/[:\*\?\/\\]//g;
                   13418:     if (length($name) > 31) {
                   13419:         $name = substr($name,0,31);
                   13420:     }
                   13421:     return $name;
1.25      albertel 13422: }
1.84      albertel 13423: 
1.85      albertel 13424: =pod
                   13425: 
1.648     raeburn  13426: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13427: 
                   13428: Returns either 1 or undef
                   13429: 
                   13430: 1 if the part is to be hidden, undef if it is to be shown
                   13431: 
                   13432: Arguments are:
                   13433: 
                   13434: $id the id of the part to be checked
                   13435: $symb, optional the symb of the resource to check
                   13436: $udom, optional the domain of the user to check for
                   13437: $uname, optional the username of the user to check for
                   13438: 
                   13439: =cut
1.84      albertel 13440: 
                   13441: sub check_if_partid_hidden {
                   13442:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13443:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13444: 					 $symb,$udom,$uname);
1.141     albertel 13445:     my $truth=1;
                   13446:     #if the string starts with !, then the list is the list to show not hide
                   13447:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13448:     my @hiddenlist=split(/,/,$hiddenparts);
                   13449:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13450: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13451:     }
1.141     albertel 13452:     return !$truth;
1.84      albertel 13453: }
1.127     matthew  13454: 
1.138     matthew  13455: 
                   13456: ############################################################
                   13457: ############################################################
                   13458: 
                   13459: =pod
                   13460: 
1.157     matthew  13461: =back 
                   13462: 
1.138     matthew  13463: =head1 cgi-bin script and graphing routines
                   13464: 
1.157     matthew  13465: =over 4
                   13466: 
1.648     raeburn  13467: =item * &get_cgi_id()
1.138     matthew  13468: 
                   13469: Inputs: none
                   13470: 
                   13471: Returns an id which can be used to pass environment variables
                   13472: to various cgi-bin scripts.  These environment variables will
                   13473: be removed from the users environment after a given time by
                   13474: the routine &Apache::lonnet::transfer_profile_to_env.
                   13475: 
                   13476: =cut
                   13477: 
                   13478: ############################################################
                   13479: ############################################################
1.152     albertel 13480: my $uniq=0;
1.136     matthew  13481: sub get_cgi_id {
1.154     albertel 13482:     $uniq=($uniq+1)%100000;
1.280     albertel 13483:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13484: }
                   13485: 
1.127     matthew  13486: ############################################################
                   13487: ############################################################
                   13488: 
                   13489: =pod
                   13490: 
1.648     raeburn  13491: =item * &DrawBarGraph()
1.127     matthew  13492: 
1.138     matthew  13493: Facilitates the plotting of data in a (stacked) bar graph.
                   13494: Puts plot definition data into the users environment in order for 
                   13495: graph.png to plot it.  Returns an <img> tag for the plot.
                   13496: The bars on the plot are labeled '1','2',...,'n'.
                   13497: 
                   13498: Inputs:
                   13499: 
                   13500: =over 4
                   13501: 
                   13502: =item $Title: string, the title of the plot
                   13503: 
                   13504: =item $xlabel: string, text describing the X-axis of the plot
                   13505: 
                   13506: =item $ylabel: string, text describing the Y-axis of the plot
                   13507: 
                   13508: =item $Max: scalar, the maximum Y value to use in the plot
                   13509: If $Max is < any data point, the graph will not be rendered.
                   13510: 
1.140     matthew  13511: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13512: they are plotted.  If undefined, default values will be used.
                   13513: 
1.178     matthew  13514: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13515: 
1.138     matthew  13516: =item @Values: An array of array references.  Each array reference holds data
                   13517: to be plotted in a stacked bar chart.
                   13518: 
1.239     matthew  13519: =item If the final element of @Values is a hash reference the key/value
                   13520: pairs will be added to the graph definition.
                   13521: 
1.138     matthew  13522: =back
                   13523: 
                   13524: Returns:
                   13525: 
                   13526: An <img> tag which references graph.png and the appropriate identifying
                   13527: information for the plot.
                   13528: 
1.127     matthew  13529: =cut
                   13530: 
                   13531: ############################################################
                   13532: ############################################################
1.134     matthew  13533: sub DrawBarGraph {
1.178     matthew  13534:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13535:     #
                   13536:     if (! defined($colors)) {
                   13537:         $colors = ['#33ff00', 
                   13538:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13539:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13540:                   ]; 
                   13541:     }
1.228     matthew  13542:     my $extra_settings = {};
                   13543:     if (ref($Values[-1]) eq 'HASH') {
                   13544:         $extra_settings = pop(@Values);
                   13545:     }
1.127     matthew  13546:     #
1.136     matthew  13547:     my $identifier = &get_cgi_id();
                   13548:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13549:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13550:         return '';
                   13551:     }
1.225     matthew  13552:     #
                   13553:     my @Labels;
                   13554:     if (defined($labels)) {
                   13555:         @Labels = @$labels;
                   13556:     } else {
                   13557:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13558:             push (@Labels,$i+1);
                   13559:         }
                   13560:     }
                   13561:     #
1.129     matthew  13562:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13563:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13564:     my %ValuesHash;
                   13565:     my $NumSets=1;
                   13566:     foreach my $array (@Values) {
                   13567:         next if (! ref($array));
1.136     matthew  13568:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13569:             join(',',@$array);
1.129     matthew  13570:     }
1.127     matthew  13571:     #
1.136     matthew  13572:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13573:     if ($NumBars < 3) {
                   13574:         $width = 120+$NumBars*32;
1.220     matthew  13575:         $xskip = 1;
1.225     matthew  13576:         $bar_width = 30;
                   13577:     } elsif ($NumBars < 5) {
                   13578:         $width = 120+$NumBars*20;
                   13579:         $xskip = 1;
                   13580:         $bar_width = 20;
1.220     matthew  13581:     } elsif ($NumBars < 10) {
1.136     matthew  13582:         $width = 120+$NumBars*15;
                   13583:         $xskip = 1;
                   13584:         $bar_width = 15;
                   13585:     } elsif ($NumBars <= 25) {
                   13586:         $width = 120+$NumBars*11;
                   13587:         $xskip = 5;
                   13588:         $bar_width = 8;
                   13589:     } elsif ($NumBars <= 50) {
                   13590:         $width = 120+$NumBars*8;
                   13591:         $xskip = 5;
                   13592:         $bar_width = 4;
                   13593:     } else {
                   13594:         $width = 120+$NumBars*8;
                   13595:         $xskip = 5;
                   13596:         $bar_width = 4;
                   13597:     }
                   13598:     #
1.137     matthew  13599:     $Max = 1 if ($Max < 1);
                   13600:     if ( int($Max) < $Max ) {
                   13601:         $Max++;
                   13602:         $Max = int($Max);
                   13603:     }
1.127     matthew  13604:     $Title  = '' if (! defined($Title));
                   13605:     $xlabel = '' if (! defined($xlabel));
                   13606:     $ylabel = '' if (! defined($ylabel));
1.369     www      13607:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13608:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13609:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13610:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13611:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13612:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13613:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13614:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13615:     $ValuesHash{$id.'.height'}   = $height;
                   13616:     $ValuesHash{$id.'.width'}    = $width;
                   13617:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13618:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13619:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13620:     #
1.228     matthew  13621:     # Deal with other parameters
                   13622:     while (my ($key,$value) = each(%$extra_settings)) {
                   13623:         $ValuesHash{$id.'.'.$key} = $value;
                   13624:     }
                   13625:     #
1.646     raeburn  13626:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13627:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13628: }
                   13629: 
                   13630: ############################################################
                   13631: ############################################################
                   13632: 
                   13633: =pod
                   13634: 
1.648     raeburn  13635: =item * &DrawXYGraph()
1.137     matthew  13636: 
1.138     matthew  13637: Facilitates the plotting of data in an XY graph.
                   13638: Puts plot definition data into the users environment in order for 
                   13639: graph.png to plot it.  Returns an <img> tag for the plot.
                   13640: 
                   13641: Inputs:
                   13642: 
                   13643: =over 4
                   13644: 
                   13645: =item $Title: string, the title of the plot
                   13646: 
                   13647: =item $xlabel: string, text describing the X-axis of the plot
                   13648: 
                   13649: =item $ylabel: string, text describing the Y-axis of the plot
                   13650: 
                   13651: =item $Max: scalar, the maximum Y value to use in the plot
                   13652: If $Max is < any data point, the graph will not be rendered.
                   13653: 
                   13654: =item $colors: Array ref containing the hex color codes for the data to be 
                   13655: plotted in.  If undefined, default values will be used.
                   13656: 
                   13657: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13658: 
                   13659: =item $Ydata: Array ref containing Array refs.  
1.185     www      13660: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13661: 
                   13662: =item %Values: hash indicating or overriding any default values which are 
                   13663: passed to graph.png.  
                   13664: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13665: 
                   13666: =back
                   13667: 
                   13668: Returns:
                   13669: 
                   13670: An <img> tag which references graph.png and the appropriate identifying
                   13671: information for the plot.
                   13672: 
1.137     matthew  13673: =cut
                   13674: 
                   13675: ############################################################
                   13676: ############################################################
                   13677: sub DrawXYGraph {
                   13678:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13679:     #
                   13680:     # Create the identifier for the graph
                   13681:     my $identifier = &get_cgi_id();
                   13682:     my $id = 'cgi.'.$identifier;
                   13683:     #
                   13684:     $Title  = '' if (! defined($Title));
                   13685:     $xlabel = '' if (! defined($xlabel));
                   13686:     $ylabel = '' if (! defined($ylabel));
                   13687:     my %ValuesHash = 
                   13688:         (
1.369     www      13689:          $id.'.title'  => &escape($Title),
                   13690:          $id.'.xlabel' => &escape($xlabel),
                   13691:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13692:          $id.'.y_max_value'=> $Max,
                   13693:          $id.'.labels'     => join(',',@$Xlabels),
                   13694:          $id.'.PlotType'   => 'XY',
                   13695:          );
                   13696:     #
                   13697:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13698:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13699:     }
                   13700:     #
                   13701:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13702:         return '';
                   13703:     }
                   13704:     my $NumSets=1;
1.138     matthew  13705:     foreach my $array (@{$Ydata}){
1.137     matthew  13706:         next if (! ref($array));
                   13707:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13708:     }
1.138     matthew  13709:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13710:     #
                   13711:     # Deal with other parameters
                   13712:     while (my ($key,$value) = each(%Values)) {
                   13713:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13714:     }
                   13715:     #
1.646     raeburn  13716:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13717:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13718: }
                   13719: 
                   13720: ############################################################
                   13721: ############################################################
                   13722: 
                   13723: =pod
                   13724: 
1.648     raeburn  13725: =item * &DrawXYYGraph()
1.138     matthew  13726: 
                   13727: Facilitates the plotting of data in an XY graph with two Y axes.
                   13728: Puts plot definition data into the users environment in order for 
                   13729: graph.png to plot it.  Returns an <img> tag for the plot.
                   13730: 
                   13731: Inputs:
                   13732: 
                   13733: =over 4
                   13734: 
                   13735: =item $Title: string, the title of the plot
                   13736: 
                   13737: =item $xlabel: string, text describing the X-axis of the plot
                   13738: 
                   13739: =item $ylabel: string, text describing the Y-axis of the plot
                   13740: 
                   13741: =item $colors: Array ref containing the hex color codes for the data to be 
                   13742: plotted in.  If undefined, default values will be used.
                   13743: 
                   13744: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13745: 
                   13746: =item $Ydata1: The first data set
                   13747: 
                   13748: =item $Min1: The minimum value of the left Y-axis
                   13749: 
                   13750: =item $Max1: The maximum value of the left Y-axis
                   13751: 
                   13752: =item $Ydata2: The second data set
                   13753: 
                   13754: =item $Min2: The minimum value of the right Y-axis
                   13755: 
                   13756: =item $Max2: The maximum value of the left Y-axis
                   13757: 
                   13758: =item %Values: hash indicating or overriding any default values which are 
                   13759: passed to graph.png.  
                   13760: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13761: 
                   13762: =back
                   13763: 
                   13764: Returns:
                   13765: 
                   13766: An <img> tag which references graph.png and the appropriate identifying
                   13767: information for the plot.
1.136     matthew  13768: 
                   13769: =cut
                   13770: 
                   13771: ############################################################
                   13772: ############################################################
1.137     matthew  13773: sub DrawXYYGraph {
                   13774:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13775:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13776:     #
                   13777:     # Create the identifier for the graph
                   13778:     my $identifier = &get_cgi_id();
                   13779:     my $id = 'cgi.'.$identifier;
                   13780:     #
                   13781:     $Title  = '' if (! defined($Title));
                   13782:     $xlabel = '' if (! defined($xlabel));
                   13783:     $ylabel = '' if (! defined($ylabel));
                   13784:     my %ValuesHash = 
                   13785:         (
1.369     www      13786:          $id.'.title'  => &escape($Title),
                   13787:          $id.'.xlabel' => &escape($xlabel),
                   13788:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13789:          $id.'.labels' => join(',',@$Xlabels),
                   13790:          $id.'.PlotType' => 'XY',
                   13791:          $id.'.NumSets' => 2,
1.137     matthew  13792:          $id.'.two_axes' => 1,
                   13793:          $id.'.y1_max_value' => $Max1,
                   13794:          $id.'.y1_min_value' => $Min1,
                   13795:          $id.'.y2_max_value' => $Max2,
                   13796:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13797:          );
                   13798:     #
1.137     matthew  13799:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13800:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13801:     }
                   13802:     #
                   13803:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13804:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13805:         return '';
                   13806:     }
                   13807:     my $NumSets=1;
1.137     matthew  13808:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13809:         next if (! ref($array));
                   13810:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13811:     }
                   13812:     #
                   13813:     # Deal with other parameters
                   13814:     while (my ($key,$value) = each(%Values)) {
                   13815:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13816:     }
                   13817:     #
1.646     raeburn  13818:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13819:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13820: }
                   13821: 
                   13822: ############################################################
                   13823: ############################################################
                   13824: 
                   13825: =pod
                   13826: 
1.157     matthew  13827: =back 
                   13828: 
1.139     matthew  13829: =head1 Statistics helper routines?  
                   13830: 
                   13831: Bad place for them but what the hell.
                   13832: 
1.157     matthew  13833: =over 4
                   13834: 
1.648     raeburn  13835: =item * &chartlink()
1.139     matthew  13836: 
                   13837: Returns a link to the chart for a specific student.  
                   13838: 
                   13839: Inputs:
                   13840: 
                   13841: =over 4
                   13842: 
                   13843: =item $linktext: The text of the link
                   13844: 
                   13845: =item $sname: The students username
                   13846: 
                   13847: =item $sdomain: The students domain
                   13848: 
                   13849: =back
                   13850: 
1.157     matthew  13851: =back
                   13852: 
1.139     matthew  13853: =cut
                   13854: 
                   13855: ############################################################
                   13856: ############################################################
                   13857: sub chartlink {
                   13858:     my ($linktext, $sname, $sdomain) = @_;
                   13859:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13860:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13861:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13862:        '">'.$linktext.'</a>';
1.153     matthew  13863: }
                   13864: 
                   13865: #######################################################
                   13866: #######################################################
                   13867: 
                   13868: =pod
                   13869: 
                   13870: =head1 Course Environment Routines
1.157     matthew  13871: 
                   13872: =over 4
1.153     matthew  13873: 
1.648     raeburn  13874: =item * &restore_course_settings()
1.153     matthew  13875: 
1.648     raeburn  13876: =item * &store_course_settings()
1.153     matthew  13877: 
                   13878: Restores/Store indicated form parameters from the course environment.
                   13879: Will not overwrite existing values of the form parameters.
                   13880: 
                   13881: Inputs: 
                   13882: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13883: 
                   13884: a hash ref describing the data to be stored.  For example:
                   13885:    
                   13886: %Save_Parameters = ('Status' => 'scalar',
                   13887:     'chartoutputmode' => 'scalar',
                   13888:     'chartoutputdata' => 'scalar',
                   13889:     'Section' => 'array',
1.373     raeburn  13890:     'Group' => 'array',
1.153     matthew  13891:     'StudentData' => 'array',
                   13892:     'Maps' => 'array');
                   13893: 
                   13894: Returns: both routines return nothing
                   13895: 
1.631     raeburn  13896: =back
                   13897: 
1.153     matthew  13898: =cut
                   13899: 
                   13900: #######################################################
                   13901: #######################################################
                   13902: sub store_course_settings {
1.496     albertel 13903:     return &store_settings($env{'request.course.id'},@_);
                   13904: }
                   13905: 
                   13906: sub store_settings {
1.153     matthew  13907:     # save to the environment
                   13908:     # appenv the same items, just to be safe
1.300     albertel 13909:     my $udom  = $env{'user.domain'};
                   13910:     my $uname = $env{'user.name'};
1.496     albertel 13911:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13912:     my %SaveHash;
                   13913:     my %AppHash;
                   13914:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13915:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13916:         my $envname = 'environment.'.$basename;
1.258     albertel 13917:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13918:             # Save this value away
                   13919:             if ($type eq 'scalar' &&
1.258     albertel 13920:                 (! exists($env{$envname}) || 
                   13921:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13922:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13923:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13924:             } elsif ($type eq 'array') {
                   13925:                 my $stored_form;
1.258     albertel 13926:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13927:                     $stored_form = join(',',
                   13928:                                         map {
1.369     www      13929:                                             &escape($_);
1.258     albertel 13930:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13931:                 } else {
                   13932:                     $stored_form = 
1.369     www      13933:                         &escape($env{'form.'.$setting});
1.153     matthew  13934:                 }
                   13935:                 # Determine if the array contents are the same.
1.258     albertel 13936:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13937:                     $SaveHash{$basename} = $stored_form;
                   13938:                     $AppHash{$envname}   = $stored_form;
                   13939:                 }
                   13940:             }
                   13941:         }
                   13942:     }
                   13943:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13944:                                           $udom,$uname);
1.153     matthew  13945:     if ($put_result !~ /^(ok|delayed)/) {
                   13946:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13947:                                  'got error:'.$put_result);
                   13948:     }
                   13949:     # Make sure these settings stick around in this session, too
1.646     raeburn  13950:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13951:     return;
                   13952: }
                   13953: 
                   13954: sub restore_course_settings {
1.499     albertel 13955:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13956: }
                   13957: 
                   13958: sub restore_settings {
                   13959:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13960:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13961:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13962:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13963:             '.'.$setting;
1.258     albertel 13964:         if (exists($env{$envname})) {
1.153     matthew  13965:             if ($type eq 'scalar') {
1.258     albertel 13966:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13967:             } elsif ($type eq 'array') {
1.258     albertel 13968:                 $env{'form.'.$setting} = [ 
1.153     matthew  13969:                                            map { 
1.369     www      13970:                                                &unescape($_); 
1.258     albertel 13971:                                            } split(',',$env{$envname})
1.153     matthew  13972:                                            ];
                   13973:             }
                   13974:         }
                   13975:     }
1.127     matthew  13976: }
                   13977: 
1.618     raeburn  13978: #######################################################
                   13979: #######################################################
                   13980: 
                   13981: =pod
                   13982: 
                   13983: =head1 Domain E-mail Routines  
                   13984: 
                   13985: =over 4
                   13986: 
1.648     raeburn  13987: =item * &build_recipient_list()
1.618     raeburn  13988: 
1.1144    raeburn  13989: Build recipient lists for following types of e-mail:
1.766     raeburn  13990: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  13991: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13992: module change checking, student/employee ID conflict checks, as
                   13993: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13994: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13995: 
                   13996: Inputs:
1.619     raeburn  13997: defmail (scalar - email address of default recipient), 
1.1144    raeburn  13998: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13999: requestsmail, updatesmail, or idconflictsmail).
                   14000: 
1.619     raeburn  14001: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14002: 
1.619     raeburn  14003: origmail (scalar - email address of recipient from loncapa.conf, 
                   14004: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  14005: 
1.655     raeburn  14006: Returns: comma separated list of addresses to which to send e-mail.
                   14007: 
                   14008: =back
1.618     raeburn  14009: 
                   14010: =cut
                   14011: 
                   14012: ############################################################
                   14013: ############################################################
                   14014: sub build_recipient_list {
1.619     raeburn  14015:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  14016:     my @recipients;
                   14017:     my $otheremails;
                   14018:     my %domconfig =
                   14019:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   14020:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14021:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14022:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14023:                 my @contacts = ('adminemail','supportemail');
                   14024:                 foreach my $item (@contacts) {
                   14025:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14026:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14027:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14028:                             push(@recipients,$addr);
                   14029:                         }
1.619     raeburn  14030:                     }
1.766     raeburn  14031:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  14032:                 }
                   14033:             }
1.766     raeburn  14034:         } elsif ($origmail ne '') {
                   14035:             push(@recipients,$origmail);
1.618     raeburn  14036:         }
1.619     raeburn  14037:     } elsif ($origmail ne '') {
                   14038:         push(@recipients,$origmail);
1.618     raeburn  14039:     }
1.688     raeburn  14040:     if (defined($defmail)) {
                   14041:         if ($defmail ne '') {
                   14042:             push(@recipients,$defmail);
                   14043:         }
1.618     raeburn  14044:     }
                   14045:     if ($otheremails) {
1.619     raeburn  14046:         my @others;
                   14047:         if ($otheremails =~ /,/) {
                   14048:             @others = split(/,/,$otheremails);
1.618     raeburn  14049:         } else {
1.619     raeburn  14050:             push(@others,$otheremails);
                   14051:         }
                   14052:         foreach my $addr (@others) {
                   14053:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14054:                 push(@recipients,$addr);
                   14055:             }
1.618     raeburn  14056:         }
                   14057:     }
1.619     raeburn  14058:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  14059:     return $recipientlist;
                   14060: }
                   14061: 
1.127     matthew  14062: ############################################################
                   14063: ############################################################
1.154     albertel 14064: 
1.655     raeburn  14065: =pod
                   14066: 
1.1224    musolffc 14067: =over 4
                   14068: 
1.1223    musolffc 14069: =item * &mime_email()
                   14070: 
                   14071: Sends an email with a possible attachment
                   14072: 
                   14073: Inputs:
                   14074: 
                   14075: =over 4
                   14076: 
                   14077: from -              Sender's email address
                   14078: 
                   14079: to -                Email address of recipient
                   14080: 
                   14081: subject -           Subject of email
                   14082: 
                   14083: body -              Body of email
                   14084: 
                   14085: cc_string -         Carbon copy email address
                   14086: 
                   14087: bcc -               Blind carbon copy email address
                   14088: 
                   14089: type -              File type of attachment
                   14090: 
                   14091: attachment_path -   Path of file to be attached
                   14092: 
                   14093: file_name -         Name of file to be attached
                   14094: 
                   14095: attachment_text -   The body of an attachment of type "TEXT"
                   14096: 
                   14097: =back
                   14098: 
                   14099: =back
                   14100: 
                   14101: =cut
                   14102: 
                   14103: ############################################################
                   14104: ############################################################
                   14105: 
                   14106: sub mime_email {
                   14107:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   14108:         $file_name, $attachment_text) = @_;
                   14109:     my $msg = MIME::Lite->new(
                   14110:              From    => $from,
                   14111:              To      => $to,
                   14112:              Subject => $subject,
                   14113:              Type    =>'TEXT',
                   14114:              Data    => $body,
                   14115:              );
                   14116:     if ($cc_string ne '') {
                   14117:         $msg->add("Cc" => $cc_string);
                   14118:     }
                   14119:     if ($bcc ne '') {
                   14120:         $msg->add("Bcc" => $bcc);
                   14121:     }
                   14122:     $msg->attr("content-type"         => "text/plain");
                   14123:     $msg->attr("content-type.charset" => "UTF-8");
                   14124:     # Attach file if given
                   14125:     if ($attachment_path) {
                   14126:         unless ($file_name) {
                   14127:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   14128:         }
                   14129:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   14130:         $msg->attach(Type     => $type,
                   14131:                      Path     => $attachment_path,
                   14132:                      Filename => $file_name
                   14133:                      );
                   14134:     # Otherwise attach text if given
                   14135:     } elsif ($attachment_text) {
                   14136:         $msg->attach(Type => 'TEXT',
                   14137:                      Data => $attachment_text);
                   14138:     }
                   14139:     # Send it
                   14140:     $msg->send('sendmail');
                   14141: }
                   14142: 
                   14143: ############################################################
                   14144: ############################################################
                   14145: 
                   14146: =pod
                   14147: 
1.655     raeburn  14148: =head1 Course Catalog Routines
                   14149: 
                   14150: =over 4
                   14151: 
                   14152: =item * &gather_categories()
                   14153: 
                   14154: Converts category definitions - keys of categories hash stored in  
                   14155: coursecategories in configuration.db on the primary library server in a 
                   14156: domain - to an array.  Also generates javascript and idx hash used to 
                   14157: generate Domain Coordinator interface for editing Course Categories.
                   14158: 
                   14159: Inputs:
1.663     raeburn  14160: 
1.655     raeburn  14161: categories (reference to hash of category definitions).
1.663     raeburn  14162: 
1.655     raeburn  14163: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14164:       categories and subcategories).
1.663     raeburn  14165: 
1.655     raeburn  14166: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14167:       editing Course Categories).
1.663     raeburn  14168: 
1.655     raeburn  14169: jsarray (reference to array of categories used to create Javascript arrays for
                   14170:          Domain Coordinator interface for editing Course Categories).
                   14171: 
                   14172: Returns: nothing
                   14173: 
                   14174: Side effects: populates cats, idx and jsarray. 
                   14175: 
                   14176: =cut
                   14177: 
                   14178: sub gather_categories {
                   14179:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14180:     my %counters;
                   14181:     my $num = 0;
                   14182:     foreach my $item (keys(%{$categories})) {
                   14183:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14184:         if ($container eq '' && $depth == 0) {
                   14185:             $cats->[$depth][$categories->{$item}] = $cat;
                   14186:         } else {
                   14187:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14188:         }
                   14189:         my ($escitem,$tail) = split(/:/,$item,2);
                   14190:         if ($counters{$tail} eq '') {
                   14191:             $counters{$tail} = $num;
                   14192:             $num ++;
                   14193:         }
                   14194:         if (ref($idx) eq 'HASH') {
                   14195:             $idx->{$item} = $counters{$tail};
                   14196:         }
                   14197:         if (ref($jsarray) eq 'ARRAY') {
                   14198:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14199:         }
                   14200:     }
                   14201:     return;
                   14202: }
                   14203: 
                   14204: =pod
                   14205: 
                   14206: =item * &extract_categories()
                   14207: 
                   14208: Used to generate breadcrumb trails for course categories.
                   14209: 
                   14210: Inputs:
1.663     raeburn  14211: 
1.655     raeburn  14212: categories (reference to hash of category definitions).
1.663     raeburn  14213: 
1.655     raeburn  14214: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14215:       categories and subcategories).
1.663     raeburn  14216: 
1.655     raeburn  14217: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14218: 
1.655     raeburn  14219: allitems (reference to hash - key is category key 
                   14220:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14221: 
1.655     raeburn  14222: idx (reference to hash of counters used in Domain Coordinator interface for
                   14223:       editing Course Categories).
1.663     raeburn  14224: 
1.655     raeburn  14225: jsarray (reference to array of categories used to create Javascript arrays for
                   14226:          Domain Coordinator interface for editing Course Categories).
                   14227: 
1.665     raeburn  14228: subcats (reference to hash of arrays containing all subcategories within each 
                   14229:          category, -recursive)
                   14230: 
1.655     raeburn  14231: Returns: nothing
                   14232: 
                   14233: Side effects: populates trails and allitems hash references.
                   14234: 
                   14235: =cut
                   14236: 
                   14237: sub extract_categories {
1.665     raeburn  14238:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14239:     if (ref($categories) eq 'HASH') {
                   14240:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14241:         if (ref($cats->[0]) eq 'ARRAY') {
                   14242:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14243:                 my $name = $cats->[0][$i];
                   14244:                 my $item = &escape($name).'::0';
                   14245:                 my $trailstr;
                   14246:                 if ($name eq 'instcode') {
                   14247:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14248:                 } elsif ($name eq 'communities') {
                   14249:                     $trailstr = &mt('Communities');
1.655     raeburn  14250:                 } else {
                   14251:                     $trailstr = $name;
                   14252:                 }
                   14253:                 if ($allitems->{$item} eq '') {
                   14254:                     push(@{$trails},$trailstr);
                   14255:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14256:                 }
                   14257:                 my @parents = ($name);
                   14258:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14259:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14260:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14261:                         if (ref($subcats) eq 'HASH') {
                   14262:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14263:                         }
                   14264:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14265:                     }
                   14266:                 } else {
                   14267:                     if (ref($subcats) eq 'HASH') {
                   14268:                         $subcats->{$item} = [];
1.655     raeburn  14269:                     }
                   14270:                 }
                   14271:             }
                   14272:         }
                   14273:     }
                   14274:     return;
                   14275: }
                   14276: 
                   14277: =pod
                   14278: 
1.1162    raeburn  14279: =item * &recurse_categories()
1.655     raeburn  14280: 
                   14281: Recursively used to generate breadcrumb trails for course categories.
                   14282: 
                   14283: Inputs:
1.663     raeburn  14284: 
1.655     raeburn  14285: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14286:       categories and subcategories).
1.663     raeburn  14287: 
1.655     raeburn  14288: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14289: 
                   14290: category (current course category, for which breadcrumb trail is being generated).
                   14291: 
                   14292: trails (reference to array of breadcrumb trails for each category).
                   14293: 
1.655     raeburn  14294: allitems (reference to hash - key is category key
                   14295:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14296: 
1.655     raeburn  14297: parents (array containing containers directories for current category, 
                   14298:          back to top level). 
                   14299: 
                   14300: Returns: nothing
                   14301: 
                   14302: Side effects: populates trails and allitems hash references
                   14303: 
                   14304: =cut
                   14305: 
                   14306: sub recurse_categories {
1.665     raeburn  14307:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14308:     my $shallower = $depth - 1;
                   14309:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14310:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14311:             my $name = $cats->[$depth]{$category}[$k];
                   14312:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14313:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14314:             if ($allitems->{$item} eq '') {
                   14315:                 push(@{$trails},$trailstr);
                   14316:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14317:             }
                   14318:             my $deeper = $depth+1;
                   14319:             push(@{$parents},$category);
1.665     raeburn  14320:             if (ref($subcats) eq 'HASH') {
                   14321:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14322:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14323:                     my $higher;
                   14324:                     if ($j > 0) {
                   14325:                         $higher = &escape($parents->[$j]).':'.
                   14326:                                   &escape($parents->[$j-1]).':'.$j;
                   14327:                     } else {
                   14328:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14329:                     }
                   14330:                     push(@{$subcats->{$higher}},$subcat);
                   14331:                 }
                   14332:             }
                   14333:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14334:                                 $subcats);
1.655     raeburn  14335:             pop(@{$parents});
                   14336:         }
                   14337:     } else {
                   14338:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14339:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14340:         if ($allitems->{$item} eq '') {
                   14341:             push(@{$trails},$trailstr);
                   14342:             $allitems->{$item} = scalar(@{$trails})-1;
                   14343:         }
                   14344:     }
                   14345:     return;
                   14346: }
                   14347: 
1.663     raeburn  14348: =pod
                   14349: 
1.1162    raeburn  14350: =item * &assign_categories_table()
1.663     raeburn  14351: 
                   14352: Create a datatable for display of hierarchical categories in a domain,
                   14353: with checkboxes to allow a course to be categorized. 
                   14354: 
                   14355: Inputs:
                   14356: 
                   14357: cathash - reference to hash of categories defined for the domain (from
                   14358:           configuration.db)
                   14359: 
                   14360: currcat - scalar with an & separated list of categories assigned to a course. 
                   14361: 
1.919     raeburn  14362: type    - scalar contains course type (Course or Community).
                   14363: 
1.663     raeburn  14364: Returns: $output (markup to be displayed) 
                   14365: 
                   14366: =cut
                   14367: 
                   14368: sub assign_categories_table {
1.919     raeburn  14369:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  14370:     my $output;
                   14371:     if (ref($cathash) eq 'HASH') {
                   14372:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14373:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14374:         $maxdepth = scalar(@cats);
                   14375:         if (@cats > 0) {
                   14376:             my $itemcount = 0;
                   14377:             if (ref($cats[0]) eq 'ARRAY') {
                   14378:                 my @currcategories;
                   14379:                 if ($currcat ne '') {
                   14380:                     @currcategories = split('&',$currcat);
                   14381:                 }
1.919     raeburn  14382:                 my $table;
1.663     raeburn  14383:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14384:                     my $parent = $cats[0][$i];
1.919     raeburn  14385:                     next if ($parent eq 'instcode');
                   14386:                     if ($type eq 'Community') {
                   14387:                         next unless ($parent eq 'communities');
                   14388:                     } else {
                   14389:                         next if ($parent eq 'communities');
                   14390:                     }
1.663     raeburn  14391:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14392:                     my $item = &escape($parent).'::0';
                   14393:                     my $checked = '';
                   14394:                     if (@currcategories > 0) {
                   14395:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14396:                             $checked = ' checked="checked"';
1.663     raeburn  14397:                         }
                   14398:                     }
1.919     raeburn  14399:                     my $parent_title = $parent;
                   14400:                     if ($parent eq 'communities') {
                   14401:                         $parent_title = &mt('Communities');
                   14402:                     }
                   14403:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14404:                               '<input type="checkbox" name="usecategory" value="'.
                   14405:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   14406:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14407:                     my $depth = 1;
                   14408:                     push(@path,$parent);
1.919     raeburn  14409:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  14410:                     pop(@path);
1.919     raeburn  14411:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14412:                     $itemcount ++;
                   14413:                 }
1.919     raeburn  14414:                 if ($itemcount) {
                   14415:                     $output = &Apache::loncommon::start_data_table().
                   14416:                               $table.
                   14417:                               &Apache::loncommon::end_data_table();
                   14418:                 }
1.663     raeburn  14419:             }
                   14420:         }
                   14421:     }
                   14422:     return $output;
                   14423: }
                   14424: 
                   14425: =pod
                   14426: 
1.1162    raeburn  14427: =item * &assign_category_rows()
1.663     raeburn  14428: 
                   14429: Create a datatable row for display of nested categories in a domain,
                   14430: with checkboxes to allow a course to be categorized,called recursively.
                   14431: 
                   14432: Inputs:
                   14433: 
                   14434: itemcount - track row number for alternating colors
                   14435: 
                   14436: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14437:       categories and subcategories.
                   14438: 
                   14439: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14440: 
                   14441: parent - parent of current category item
                   14442: 
                   14443: path - Array containing all categories back up through the hierarchy from the
                   14444:        current category to the top level.
                   14445: 
                   14446: currcategories - reference to array of current categories assigned to the course
                   14447: 
                   14448: Returns: $output (markup to be displayed).
                   14449: 
                   14450: =cut
                   14451: 
                   14452: sub assign_category_rows {
                   14453:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   14454:     my ($text,$name,$item,$chgstr);
                   14455:     if (ref($cats) eq 'ARRAY') {
                   14456:         my $maxdepth = scalar(@{$cats});
                   14457:         if (ref($cats->[$depth]) eq 'HASH') {
                   14458:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14459:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14460:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  14461:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14462:                 for (my $j=0; $j<$numchildren; $j++) {
                   14463:                     $name = $cats->[$depth]{$parent}[$j];
                   14464:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14465:                     my $deeper = $depth+1;
                   14466:                     my $checked = '';
                   14467:                     if (ref($currcategories) eq 'ARRAY') {
                   14468:                         if (@{$currcategories} > 0) {
                   14469:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14470:                                 $checked = ' checked="checked"';
1.663     raeburn  14471:                             }
                   14472:                         }
                   14473:                     }
1.664     raeburn  14474:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14475:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  14476:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   14477:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14478:                              '</td><td>';
1.663     raeburn  14479:                     if (ref($path) eq 'ARRAY') {
                   14480:                         push(@{$path},$name);
                   14481:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   14482:                         pop(@{$path});
                   14483:                     }
                   14484:                     $text .= '</td></tr>';
                   14485:                 }
                   14486:                 $text .= '</table></td>';
                   14487:             }
                   14488:         }
                   14489:     }
                   14490:     return $text;
                   14491: }
                   14492: 
1.1181    raeburn  14493: =pod
                   14494: 
                   14495: =back
                   14496: 
                   14497: =cut
                   14498: 
1.655     raeburn  14499: ############################################################
                   14500: ############################################################
                   14501: 
                   14502: 
1.443     albertel 14503: sub commit_customrole {
1.664     raeburn  14504:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14505:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14506:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14507:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14508:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14509:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14510:                  '</b><br />';
                   14511:     return $output;
                   14512: }
                   14513: 
                   14514: sub commit_standardrole {
1.1116    raeburn  14515:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14516:     my ($output,$logmsg,$linefeed);
                   14517:     if ($context eq 'auto') {
                   14518:         $linefeed = "\n";
                   14519:     } else {
                   14520:         $linefeed = "<br />\n";
                   14521:     }  
1.443     albertel 14522:     if ($three eq 'st') {
1.541     raeburn  14523:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  14524:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14525:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14526:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14527:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14528:         } else {
1.541     raeburn  14529:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14530:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14531:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14532:             if ($context eq 'auto') {
                   14533:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14534:             } else {
                   14535:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14536:                &mt('Add to classlist').': <b>ok</b>';
                   14537:             }
                   14538:             $output .= $linefeed;
1.443     albertel 14539:         }
                   14540:     } else {
                   14541:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14542:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14543:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14544:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14545:         if ($context eq 'auto') {
                   14546:             $output .= $result.$linefeed;
                   14547:         } else {
                   14548:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14549:         }
1.443     albertel 14550:     }
                   14551:     return $output;
                   14552: }
                   14553: 
                   14554: sub commit_studentrole {
1.1116    raeburn  14555:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14556:         $credits) = @_;
1.626     raeburn  14557:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14558:     if ($context eq 'auto') {
                   14559:         $linefeed = "\n";
                   14560:     } else {
                   14561:         $linefeed = '<br />'."\n";
                   14562:     }
1.443     albertel 14563:     if (defined($one) && defined($two)) {
                   14564:         my $cid=$one.'_'.$two;
                   14565:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14566:         my $secchange = 0;
                   14567:         my $expire_role_result;
                   14568:         my $modify_section_result;
1.628     raeburn  14569:         if ($oldsec ne '-1') { 
                   14570:             if ($oldsec ne $sec) {
1.443     albertel 14571:                 $secchange = 1;
1.628     raeburn  14572:                 my $now = time;
1.443     albertel 14573:                 my $uurl='/'.$cid;
                   14574:                 $uurl=~s/\_/\//g;
                   14575:                 if ($oldsec) {
                   14576:                     $uurl.='/'.$oldsec;
                   14577:                 }
1.626     raeburn  14578:                 $oldsecurl = $uurl;
1.628     raeburn  14579:                 $expire_role_result = 
1.652     raeburn  14580:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14581:                 if ($env{'request.course.sec'} ne '') { 
                   14582:                     if ($expire_role_result eq 'refused') {
                   14583:                         my @roles = ('st');
                   14584:                         my @statuses = ('previous');
                   14585:                         my @roledoms = ($one);
                   14586:                         my $withsec = 1;
                   14587:                         my %roleshash = 
                   14588:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14589:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14590:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14591:                             my ($oldstart,$oldend) = 
                   14592:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14593:                             if ($oldend > 0 && $oldend <= $now) {
                   14594:                                 $expire_role_result = 'ok';
                   14595:                             }
                   14596:                         }
                   14597:                     }
                   14598:                 }
1.443     albertel 14599:                 $result = $expire_role_result;
                   14600:             }
                   14601:         }
                   14602:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  14603:             $modify_section_result = 
                   14604:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14605:                                                            undef,undef,undef,$sec,
                   14606:                                                            $end,$start,'','',$cid,
                   14607:                                                            '',$context,$credits);
1.443     albertel 14608:             if ($modify_section_result =~ /^ok/) {
                   14609:                 if ($secchange == 1) {
1.628     raeburn  14610:                     if ($sec eq '') {
                   14611:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14612:                     } else {
                   14613:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14614:                     }
1.443     albertel 14615:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14616:                     if ($sec eq '') {
                   14617:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14618:                     } else {
                   14619:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14620:                     }
1.443     albertel 14621:                 } else {
1.628     raeburn  14622:                     if ($sec eq '') {
                   14623:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14624:                     } else {
                   14625:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14626:                     }
1.443     albertel 14627:                 }
                   14628:             } else {
1.1115    raeburn  14629:                 if ($secchange) { 
1.628     raeburn  14630:                     $$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;
                   14631:                 } else {
                   14632:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14633:                 }
1.443     albertel 14634:             }
                   14635:             $result = $modify_section_result;
                   14636:         } elsif ($secchange == 1) {
1.628     raeburn  14637:             if ($oldsec eq '') {
1.1103    raeburn  14638:                 $$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  14639:             } else {
                   14640:                 $$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;
                   14641:             }
1.626     raeburn  14642:             if ($expire_role_result eq 'refused') {
                   14643:                 my $newsecurl = '/'.$cid;
                   14644:                 $newsecurl =~ s/\_/\//g;
                   14645:                 if ($sec ne '') {
                   14646:                     $newsecurl.='/'.$sec;
                   14647:                 }
                   14648:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14649:                     if ($sec eq '') {
                   14650:                         $$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;
                   14651:                     } else {
                   14652:                         $$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;
                   14653:                     }
                   14654:                 }
                   14655:             }
1.443     albertel 14656:         }
                   14657:     } else {
1.626     raeburn  14658:         $$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 14659:         $result = "error: incomplete course id\n";
                   14660:     }
                   14661:     return $result;
                   14662: }
                   14663: 
1.1108    raeburn  14664: sub show_role_extent {
                   14665:     my ($scope,$context,$role) = @_;
                   14666:     $scope =~ s{^/}{};
                   14667:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14668:     push(@courseroles,'co');
                   14669:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14670:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14671:         $scope =~ s{/}{_};
                   14672:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14673:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14674:         my ($audom,$auname) = split(/\//,$scope);
                   14675:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14676:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14677:     } else {
                   14678:         $scope =~ s{/$}{};
                   14679:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14680:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14681:     }
                   14682: }
                   14683: 
1.443     albertel 14684: ############################################################
                   14685: ############################################################
                   14686: 
1.566     albertel 14687: sub check_clone {
1.578     raeburn  14688:     my ($args,$linefeed) = @_;
1.566     albertel 14689:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14690:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14691:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14692:     my $clonemsg;
                   14693:     my $can_clone = 0;
1.944     raeburn  14694:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14695:     if ($lctype ne 'community') {
                   14696:         $lctype = 'course';
                   14697:     }
1.566     albertel 14698:     if ($clonehome eq 'no_host') {
1.944     raeburn  14699:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14700:             $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'});
                   14701:         } else {
                   14702:             $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'});
                   14703:         }     
1.566     albertel 14704:     } else {
                   14705: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14706:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14707:             if ($clonedesc{'type'} ne 'Community') {
                   14708:                  $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'});
                   14709:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14710:             }
                   14711:         }
1.882     raeburn  14712: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   14713:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14714: 	    $can_clone = 1;
                   14715: 	} else {
1.1221    raeburn  14716: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 14717: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  14718:             if ($clonehash{'cloners'} eq '') {
                   14719:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   14720:                 if ($domdefs{'canclone'}) {
                   14721:                     unless ($domdefs{'canclone'} eq 'none') {
                   14722:                         if ($domdefs{'canclone'} eq 'domain') {
                   14723:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   14724:                                 $can_clone = 1;
                   14725:                             }
                   14726:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   14727:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   14728:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   14729:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   14730:                                 $can_clone = 1;
                   14731:                             }
                   14732:                         }
                   14733:                     }
                   14734:                 }
1.578     raeburn  14735:             } else {
1.1221    raeburn  14736: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   14737:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  14738:                     $can_clone = 1;
1.1221    raeburn  14739:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  14740:                     $can_clone = 1;
1.1225    raeburn  14741:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14742:                     $can_clone = 1;
1.1221    raeburn  14743:                 }
                   14744:                 unless ($can_clone) {
1.1225    raeburn  14745:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   14746:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  14747:                         my (%gotdomdefaults,%gotcodedefaults);
                   14748:                         foreach my $cloner (@cloners) {
                   14749:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   14750:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   14751:                                 my (%codedefaults,@code_order);
                   14752:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   14753:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   14754:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   14755:                                     }
                   14756:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   14757:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   14758:                                     }
                   14759:                                 } else {
                   14760:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   14761:                                                                             \%codedefaults,
                   14762:                                                                             \@code_order);
                   14763:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   14764:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   14765:                                 }
                   14766:                                 if (@code_order > 0) {
                   14767:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   14768:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   14769:                                                                                 $args->{'crscode'})) {
                   14770:                                         $can_clone = 1;
                   14771:                                         last;
                   14772:                                     }
                   14773:                                 }
                   14774:                             }
                   14775:                         }
                   14776:                     }
1.1225    raeburn  14777:                 }
                   14778:             }
                   14779:             unless ($can_clone) {
                   14780:                 my $ccrole = 'cc';
                   14781:                 if ($args->{'crstype'} eq 'Community') {
                   14782:                     $ccrole = 'co';
                   14783:                 }
                   14784: 	        my %roleshash =
                   14785: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14786: 					          $args->{'ccdomain'},
                   14787:                                                   'userroles',['active'],[$ccrole],
                   14788: 					          [$args->{'clonedomain'}]);
                   14789: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   14790:                     $can_clone = 1;
                   14791:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   14792:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   14793:                     $can_clone = 1;
1.1221    raeburn  14794:                 }
                   14795:             }
                   14796:             unless ($can_clone) {
                   14797:                 if ($args->{'crstype'} eq 'Community') {
                   14798:                     $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  14799:                 } else {
1.1221    raeburn  14800:                     $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'});
                   14801:                 }
1.566     albertel 14802: 	    }
1.578     raeburn  14803:         }
1.566     albertel 14804:     }
                   14805:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14806: }
                   14807: 
1.444     albertel 14808: sub construct_course {
1.1166    raeburn  14809:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 14810:     my $outcome;
1.541     raeburn  14811:     my $linefeed =  '<br />'."\n";
                   14812:     if ($context eq 'auto') {
                   14813:         $linefeed = "\n";
                   14814:     }
1.566     albertel 14815: 
                   14816: #
                   14817: # Are we cloning?
                   14818: #
                   14819:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14820:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14821: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14822: 	if ($context ne 'auto') {
1.578     raeburn  14823:             if ($clonemsg ne '') {
                   14824: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14825:             }
1.566     albertel 14826: 	}
                   14827: 	$outcome .= $clonemsg.$linefeed;
                   14828: 
                   14829:         if (!$can_clone) {
                   14830: 	    return (0,$outcome);
                   14831: 	}
                   14832:     }
                   14833: 
1.444     albertel 14834: #
                   14835: # Open course
                   14836: #
                   14837:     my $crstype = lc($args->{'crstype'});
                   14838:     my %cenv=();
                   14839:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14840:                                              $args->{'cdescr'},
                   14841:                                              $args->{'curl'},
                   14842:                                              $args->{'course_home'},
                   14843:                                              $args->{'nonstandard'},
                   14844:                                              $args->{'crscode'},
                   14845:                                              $args->{'ccuname'}.':'.
                   14846:                                              $args->{'ccdomain'},
1.882     raeburn  14847:                                              $args->{'crstype'},
1.885     raeburn  14848:                                              $cnum,$context,$category);
1.444     albertel 14849: 
                   14850:     # Note: The testing routines depend on this being output; see 
                   14851:     # Utils::Course. This needs to at least be output as a comment
                   14852:     # if anyone ever decides to not show this, and Utils::Course::new
                   14853:     # will need to be suitably modified.
1.541     raeburn  14854:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14855:     if ($$courseid =~ /^error:/) {
                   14856:         return (0,$outcome);
                   14857:     }
                   14858: 
1.444     albertel 14859: #
                   14860: # Check if created correctly
                   14861: #
1.479     albertel 14862:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14863:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14864:     if ($crsuhome eq 'no_host') {
                   14865:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14866:         return (0,$outcome);
                   14867:     }
1.541     raeburn  14868:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14869: 
1.444     albertel 14870: #
1.566     albertel 14871: # Do the cloning
                   14872: #   
                   14873:     if ($can_clone && $cloneid) {
                   14874: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14875: 	if ($context ne 'auto') {
                   14876: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14877: 	}
                   14878: 	$outcome .= $clonemsg.$linefeed;
                   14879: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14880: # Copy all files
1.637     www      14881: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14882: # Restore URL
1.566     albertel 14883: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14884: # Restore title
1.566     albertel 14885: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14886: # Restore creation date, creator and creation context.
                   14887:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14888:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14889:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14890: # Mark as cloned
1.566     albertel 14891: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14892: # Need to clone grading mode
                   14893:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14894:         $cenv{'grading'}=$newenv{'grading'};
                   14895: # Do not clone these environment entries
                   14896:         &Apache::lonnet::del('environment',
                   14897:                   ['default_enrollment_start_date',
                   14898:                    'default_enrollment_end_date',
                   14899:                    'question.email',
                   14900:                    'policy.email',
                   14901:                    'comment.email',
                   14902:                    'pch.users.denied',
1.725     raeburn  14903:                    'plc.users.denied',
                   14904:                    'hidefromcat',
1.1121    raeburn  14905:                    'checkforpriv',
1.1166    raeburn  14906:                    'categories',
                   14907:                    'internal.uniquecode'],
1.638     www      14908:                    $$crsudom,$$crsunum);
1.1170    raeburn  14909:         if ($args->{'textbook'}) {
                   14910:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14911:         }
1.444     albertel 14912:     }
1.566     albertel 14913: 
1.444     albertel 14914: #
                   14915: # Set environment (will override cloned, if existing)
                   14916: #
                   14917:     my @sections = ();
                   14918:     my @xlists = ();
                   14919:     if ($args->{'crstype'}) {
                   14920:         $cenv{'type'}=$args->{'crstype'};
                   14921:     }
                   14922:     if ($args->{'crsid'}) {
                   14923:         $cenv{'courseid'}=$args->{'crsid'};
                   14924:     }
                   14925:     if ($args->{'crscode'}) {
                   14926:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14927:     }
                   14928:     if ($args->{'crsquota'} ne '') {
                   14929:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14930:     } else {
                   14931:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14932:     }
                   14933:     if ($args->{'ccuname'}) {
                   14934:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14935:                                         ':'.$args->{'ccdomain'};
                   14936:     } else {
                   14937:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14938:     }
1.1116    raeburn  14939:     if ($args->{'defaultcredits'}) {
                   14940:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14941:     }
1.444     albertel 14942:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14943:     if ($args->{'crssections'}) {
                   14944:         $cenv{'internal.sectionnums'} = '';
                   14945:         if ($args->{'crssections'} =~ m/,/) {
                   14946:             @sections = split/,/,$args->{'crssections'};
                   14947:         } else {
                   14948:             $sections[0] = $args->{'crssections'};
                   14949:         }
                   14950:         if (@sections > 0) {
                   14951:             foreach my $item (@sections) {
                   14952:                 my ($sec,$gp) = split/:/,$item;
                   14953:                 my $class = $args->{'crscode'}.$sec;
                   14954:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14955:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14956:                 unless ($addcheck eq 'ok') {
                   14957:                     push @badclasses, $class;
                   14958:                 }
                   14959:             }
                   14960:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14961:         }
                   14962:     }
                   14963: # do not hide course coordinator from staff listing, 
                   14964: # even if privileged
                   14965:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  14966: # add course coordinator's domain to domains to check for privileged users
                   14967: # if different to course domain
                   14968:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14969:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14970:     }
1.444     albertel 14971: # add crosslistings
                   14972:     if ($args->{'crsxlist'}) {
                   14973:         $cenv{'internal.crosslistings'}='';
                   14974:         if ($args->{'crsxlist'} =~ m/,/) {
                   14975:             @xlists = split/,/,$args->{'crsxlist'};
                   14976:         } else {
                   14977:             $xlists[0] = $args->{'crsxlist'};
                   14978:         }
                   14979:         if (@xlists > 0) {
                   14980:             foreach my $item (@xlists) {
                   14981:                 my ($xl,$gp) = split/:/,$item;
                   14982:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14983:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14984:                 unless ($addcheck eq 'ok') {
                   14985:                     push @badclasses, $xl;
                   14986:                 }
                   14987:             }
                   14988:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14989:         }
                   14990:     }
                   14991:     if ($args->{'autoadds'}) {
                   14992:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14993:     }
                   14994:     if ($args->{'autodrops'}) {
                   14995:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14996:     }
                   14997: # check for notification of enrollment changes
                   14998:     my @notified = ();
                   14999:     if ($args->{'notify_owner'}) {
                   15000:         if ($args->{'ccuname'} ne '') {
                   15001:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15002:         }
                   15003:     }
                   15004:     if ($args->{'notify_dc'}) {
                   15005:         if ($uname ne '') { 
1.630     raeburn  15006:             push(@notified,$uname.':'.$udom);
1.444     albertel 15007:         }
                   15008:     }
                   15009:     if (@notified > 0) {
                   15010:         my $notifylist;
                   15011:         if (@notified > 1) {
                   15012:             $notifylist = join(',',@notified);
                   15013:         } else {
                   15014:             $notifylist = $notified[0];
                   15015:         }
                   15016:         $cenv{'internal.notifylist'} = $notifylist;
                   15017:     }
                   15018:     if (@badclasses > 0) {
                   15019:         my %lt=&Apache::lonlocal::texthash(
                   15020:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
                   15021:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   15022:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   15023:         );
1.541     raeburn  15024:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   15025:                            ' ('.$lt{'adby'}.')';
                   15026:         if ($context eq 'auto') {
                   15027:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 15028:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  15029:             foreach my $item (@badclasses) {
                   15030:                 if ($context eq 'auto') {
                   15031:                     $outcome .= " - $item\n";
                   15032:                 } else {
                   15033:                     $outcome .= "<li>$item</li>\n";
                   15034:                 }
                   15035:             }
                   15036:             if ($context eq 'auto') {
                   15037:                 $outcome .= $linefeed;
                   15038:             } else {
1.566     albertel 15039:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  15040:             }
                   15041:         } 
1.444     albertel 15042:     }
                   15043:     if ($args->{'no_end_date'}) {
                   15044:         $args->{'endaccess'} = 0;
                   15045:     }
                   15046:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15047:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15048:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15049:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15050:     if ($args->{'showphotos'}) {
                   15051:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15052:     }
                   15053:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15054:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15055:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15056:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15057:             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'); 
                   15058:             if ($context eq 'auto') {
                   15059:                 $outcome .= $krb_msg;
                   15060:             } else {
1.566     albertel 15061:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15062:             }
                   15063:             $outcome .= $linefeed;
1.444     albertel 15064:         }
                   15065:     }
                   15066:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15067:        if ($args->{'setpolicy'}) {
                   15068:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15069:        }
                   15070:        if ($args->{'setcontent'}) {
                   15071:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15072:        }
                   15073:     }
                   15074:     if ($args->{'reshome'}) {
                   15075: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15076: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15077:     }
                   15078: #
                   15079: # course has keyed access
                   15080: #
                   15081:     if ($args->{'setkeys'}) {
                   15082:        $cenv{'keyaccess'}='yes';
                   15083:     }
                   15084: # if specified, key authority is not course, but user
                   15085: # only active if keyaccess is yes
                   15086:     if ($args->{'keyauth'}) {
1.487     albertel 15087: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15088: 	$user = &LONCAPA::clean_username($user);
                   15089: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15090: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15091: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15092: 	}
                   15093:     }
                   15094: 
1.1166    raeburn  15095: #
1.1167    raeburn  15096: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  15097: #
                   15098:     if ($args->{'uniquecode'}) {
                   15099:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15100:         if ($code) {
                   15101:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  15102:             my %crsinfo =
                   15103:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15104:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15105:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15106:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15107:             } 
1.1166    raeburn  15108:             if (ref($coderef)) {
                   15109:                 $$coderef = $code;
                   15110:             }
                   15111:         }
                   15112:     }
                   15113: 
1.444     albertel 15114:     if ($args->{'disresdis'}) {
                   15115:         $cenv{'pch.roles.denied'}='st';
                   15116:     }
                   15117:     if ($args->{'disablechat'}) {
                   15118:         $cenv{'plc.roles.denied'}='st';
                   15119:     }
                   15120: 
                   15121:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15122:     # course
                   15123:     $cenv{'course.helper.not.run'} = 1;
                   15124:     #
                   15125:     # Use new Randomseed
                   15126:     #
                   15127:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15128:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15129:     #
                   15130:     # The encryption code and receipt prefix for this course
                   15131:     #
                   15132:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15133:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15134:     #
                   15135:     # By default, use standard grading
                   15136:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15137: 
1.541     raeburn  15138:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15139:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15140: #
                   15141: # Open all assignments
                   15142: #
                   15143:     if ($args->{'openall'}) {
                   15144:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15145:        my %storecontent = ($storeunder         => time,
                   15146:                            $storeunder.'.type' => 'date_start');
                   15147:        
                   15148:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15149:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15150:    }
                   15151: #
                   15152: # Set first page
                   15153: #
                   15154:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15155: 	    || ($cloneid)) {
1.445     albertel 15156: 	use LONCAPA::map;
1.444     albertel 15157: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15158: 
                   15159: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15160:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15161: 
1.444     albertel 15162:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15163:         my $title; my $url;
                   15164:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15165: 	    $title=&mt('Syllabus');
1.444     albertel 15166:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15167:         } else {
1.963     raeburn  15168:             $title=&mt('Table of Contents');
1.444     albertel 15169:             $url='/adm/navmaps';
                   15170:         }
1.445     albertel 15171: 
                   15172:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15173: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15174: 
                   15175: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15176:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15177:     }
1.566     albertel 15178: 
                   15179:     return (1,$outcome);
1.444     albertel 15180: }
                   15181: 
1.1166    raeburn  15182: sub make_unique_code {
                   15183:     my ($cdom,$cnum) = @_;
                   15184:     # get lock on uniquecodes db
                   15185:     my $lockhash = {
                   15186:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15187:                                                   ':'.$env{'user.domain'},
                   15188:                    };
                   15189:     my $tries = 0;
                   15190:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15191:     my ($code,$error);
                   15192:   
                   15193:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15194:         $tries ++;
                   15195:         sleep 1;
                   15196:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15197:     }
                   15198:     if ($gotlock eq 'ok') {
                   15199:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15200:         my $gotcode;
                   15201:         my $attempts = 0;
                   15202:         while ((!$gotcode) && ($attempts < 100)) {
                   15203:             $code = &generate_code();
                   15204:             if (!exists($currcodes{$code})) {
                   15205:                 $gotcode = 1;
                   15206:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15207:                     $error = 'nostore';
                   15208:                 }
                   15209:             }
                   15210:             $attempts ++;
                   15211:         }
                   15212:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15213:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15214:     } else {
                   15215:         $error = 'nolock';
                   15216:     }
                   15217:     return ($code,$error);
                   15218: }
                   15219: 
                   15220: sub generate_code {
                   15221:     my $code;
                   15222:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15223:     for (my $i=0; $i<6; $i++) {
                   15224:         my $lettnum = int (rand 2);
                   15225:         my $item = '';
                   15226:         if ($lettnum) {
                   15227:             $item = $letts[int( rand(18) )];
                   15228:         } else {
                   15229:             $item = 1+int( rand(8) );
                   15230:         }
                   15231:         $code .= $item;
                   15232:     }
                   15233:     return $code;
                   15234: }
                   15235: 
1.444     albertel 15236: ############################################################
                   15237: ############################################################
                   15238: 
1.953     droeschl 15239: #SD
                   15240: # only Community and Course, or anything else?
1.378     raeburn  15241: sub course_type {
                   15242:     my ($cid) = @_;
                   15243:     if (!defined($cid)) {
                   15244:         $cid = $env{'request.course.id'};
                   15245:     }
1.404     albertel 15246:     if (defined($env{'course.'.$cid.'.type'})) {
                   15247:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15248:     } else {
                   15249:         return 'Course';
1.377     raeburn  15250:     }
                   15251: }
1.156     albertel 15252: 
1.406     raeburn  15253: sub group_term {
                   15254:     my $crstype = &course_type();
                   15255:     my %names = (
                   15256:                   'Course' => 'group',
1.865     raeburn  15257:                   'Community' => 'group',
1.406     raeburn  15258:                 );
                   15259:     return $names{$crstype};
                   15260: }
                   15261: 
1.902     raeburn  15262: sub course_types {
1.1165    raeburn  15263:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15264:     my %typename = (
                   15265:                          official   => 'Official course',
                   15266:                          unofficial => 'Unofficial course',
                   15267:                          community  => 'Community',
1.1165    raeburn  15268:                          textbook   => 'Textbook course',
1.902     raeburn  15269:                    );
                   15270:     return (\@types,\%typename);
                   15271: }
                   15272: 
1.156     albertel 15273: sub icon {
                   15274:     my ($file)=@_;
1.505     albertel 15275:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15276:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15277:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15278:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15279: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15280: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15281: 	            $curfext.".gif") {
                   15282: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15283: 		$curfext.".gif";
                   15284: 	}
                   15285:     }
1.249     albertel 15286:     return &lonhttpdurl($iconname);
1.154     albertel 15287: } 
1.84      albertel 15288: 
1.575     albertel 15289: sub lonhttpdurl {
1.692     www      15290: #
                   15291: # Had been used for "small fry" static images on separate port 8080.
                   15292: # Modify here if lightweight http functionality desired again.
                   15293: # Currently eliminated due to increasing firewall issues.
                   15294: #
1.575     albertel 15295:     my ($url)=@_;
1.692     www      15296:     return $url;
1.215     albertel 15297: }
                   15298: 
1.213     albertel 15299: sub connection_aborted {
                   15300:     my ($r)=@_;
                   15301:     $r->print(" ");$r->rflush();
                   15302:     my $c = $r->connection;
                   15303:     return $c->aborted();
                   15304: }
                   15305: 
1.221     foxr     15306: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15307: #    strings as 'strings'.
                   15308: sub escape_single {
1.221     foxr     15309:     my ($input) = @_;
1.223     albertel 15310:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15311:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15312:     return $input;
                   15313: }
1.223     albertel 15314: 
1.222     foxr     15315: #  Same as escape_single, but escape's "'s  This 
                   15316: #  can be used for  "strings"
                   15317: sub escape_double {
                   15318:     my ($input) = @_;
                   15319:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15320:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15321:     return $input;
                   15322: }
1.223     albertel 15323:  
1.222     foxr     15324: #   Escapes the last element of a full URL.
                   15325: sub escape_url {
                   15326:     my ($url)   = @_;
1.238     raeburn  15327:     my @urlslices = split(/\//, $url,-1);
1.369     www      15328:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  15329:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15330: }
1.462     albertel 15331: 
1.820     raeburn  15332: sub compare_arrays {
                   15333:     my ($arrayref1,$arrayref2) = @_;
                   15334:     my (@difference,%count);
                   15335:     @difference = ();
                   15336:     %count = ();
                   15337:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15338:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15339:         foreach my $element (keys(%count)) {
                   15340:             if ($count{$element} == 1) {
                   15341:                 push(@difference,$element);
                   15342:             }
                   15343:         }
                   15344:     }
                   15345:     return @difference;
                   15346: }
                   15347: 
1.817     bisitz   15348: # -------------------------------------------------------- Initialize user login
1.462     albertel 15349: sub init_user_environment {
1.463     albertel 15350:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15351:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15352: 
                   15353:     my $public=($username eq 'public' && $domain eq 'public');
                   15354: 
                   15355: # See if old ID present, if so, remove
                   15356: 
1.1062    raeburn  15357:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15358:     my $now=time;
                   15359: 
                   15360:     if ($public) {
                   15361: 	my $max_public=100;
                   15362: 	my $oldest;
                   15363: 	my $oldest_time=0;
                   15364: 	for(my $next=1;$next<=$max_public;$next++) {
                   15365: 	    if (-e $lonids."/publicuser_$next.id") {
                   15366: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15367: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15368: 		    $oldest_time=$mtime;
                   15369: 		    $oldest=$next;
                   15370: 		}
                   15371: 	    } else {
                   15372: 		$cookie="publicuser_$next";
                   15373: 		last;
                   15374: 	    }
                   15375: 	}
                   15376: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15377:     } else {
1.463     albertel 15378: 	# if this isn't a robot, kill any existing non-robot sessions
                   15379: 	if (!$args->{'robot'}) {
                   15380: 	    opendir(DIR,$lonids);
                   15381: 	    while ($filename=readdir(DIR)) {
                   15382: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   15383: 		    unlink($lonids.'/'.$filename);
                   15384: 		}
1.462     albertel 15385: 	    }
1.463     albertel 15386: 	    closedir(DIR);
1.1204    raeburn  15387: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15388:             my $namespace = 'nohist_courseeditor';
                   15389:             my $lockingkey = 'paste'."\0".'locked_num';
                   15390:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15391:                                                 $domain,$username);
                   15392:             if (exists($lockhash{$lockingkey})) {
                   15393:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15394:                 unless ($delresult eq 'ok') {
                   15395:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15396:                 }
                   15397:             }
1.462     albertel 15398: 	}
                   15399: # Give them a new cookie
1.463     albertel 15400: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15401: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15402: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15403:     
                   15404: # Initialize roles
                   15405: 
1.1062    raeburn  15406: 	($userroles,$firstaccenv,$timerintenv) = 
                   15407:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15408:     }
                   15409: # ------------------------------------ Check browser type and MathML capability
                   15410: 
1.1194    raeburn  15411:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15412:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15413: 
                   15414: # ------------------------------------------------------------- Get environment
                   15415: 
                   15416:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15417:     my ($tmp) = keys(%userenv);
                   15418:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15419:     } else {
                   15420: 	undef(%userenv);
                   15421:     }
                   15422:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15423: 	$form->{'interface'}=$userenv{'interface'};
                   15424:     }
                   15425:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15426: 
                   15427: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15428:     foreach my $option ('interface','localpath','localres') {
                   15429:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15430:     }
                   15431: # --------------------------------------------------------- Write first profile
                   15432: 
                   15433:     {
                   15434: 	my %initial_env = 
                   15435: 	    ("user.name"          => $username,
                   15436: 	     "user.domain"        => $domain,
                   15437: 	     "user.home"          => $authhost,
                   15438: 	     "browser.type"       => $clientbrowser,
                   15439: 	     "browser.version"    => $clientversion,
                   15440: 	     "browser.mathml"     => $clientmathml,
                   15441: 	     "browser.unicode"    => $clientunicode,
                   15442: 	     "browser.os"         => $clientos,
1.1137    raeburn  15443:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  15444:              "browser.info"       => $clientinfo,
1.1194    raeburn  15445:              "browser.osversion"  => $clientosversion,
1.462     albertel 15446: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15447: 	     "request.course.fn"  => '',
                   15448: 	     "request.course.uri" => '',
                   15449: 	     "request.course.sec" => '',
                   15450: 	     "request.role"       => 'cm',
                   15451: 	     "request.role.adv"   => $env{'user.adv'},
                   15452: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15453: 
                   15454:         if ($form->{'localpath'}) {
                   15455: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15456: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15457:         }
                   15458: 	
                   15459: 	if ($form->{'interface'}) {
                   15460: 	    $form->{'interface'}=~s/\W//gs;
                   15461: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15462: 	    $env{'browser.interface'}=$form->{'interface'};
                   15463: 	}
                   15464: 
1.1157    raeburn  15465:         if ($form->{'iptoken'}) {
                   15466:             my $lonhost = $r->dir_config('lonHostID');
                   15467:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15468:             $env{'user.noloadbalance'} = $lonhost;
                   15469:         }
                   15470: 
1.981     raeburn  15471:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  15472:         my %domdef;
                   15473:         unless ($domain eq 'public') {
                   15474:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   15475:         }
1.980     raeburn  15476: 
1.1081    raeburn  15477:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  15478:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  15479:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15480:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  15481:         }
                   15482: 
1.1165    raeburn  15483:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  15484:             $userenv{'canrequest.'.$crstype} =
                   15485:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  15486:                                                   'reload','requestcourses',
                   15487:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  15488:         }
                   15489: 
1.1092    raeburn  15490:         $userenv{'canrequest.author'} =
                   15491:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15492:                                         'reload','requestauthor',
                   15493:                                         \%userenv,\%domdef,\%is_adv);
                   15494:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15495:                                              $domain,$username);
                   15496:         my $reqstatus = $reqauthor{'author_status'};
                   15497:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   15498:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   15499:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15500:                                                   $reqauthor{'author'}{'timestamp'};
                   15501:             }
                   15502:         }
                   15503: 
1.462     albertel 15504: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15505: 
1.462     albertel 15506: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15507: 		 &GDBM_WRCREAT(),0640)) {
                   15508: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15509: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15510: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15511:             if (ref($firstaccenv) eq 'HASH') {
                   15512:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15513:             }
                   15514:             if (ref($timerintenv) eq 'HASH') {
                   15515:                 &_add_to_env(\%disk_env,$timerintenv);
                   15516:             }
1.463     albertel 15517: 	    if (ref($args->{'extra_env'})) {
                   15518: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15519: 	    }
1.462     albertel 15520: 	    untie(%disk_env);
                   15521: 	} else {
1.705     tempelho 15522: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15523: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15524: 	    return 'error: '.$!;
                   15525: 	}
                   15526:     }
                   15527:     $env{'request.role'}='cm';
                   15528:     $env{'request.role.adv'}=$env{'user.adv'};
                   15529:     $env{'browser.type'}=$clientbrowser;
                   15530: 
                   15531:     return $cookie;
                   15532: 
                   15533: }
                   15534: 
                   15535: sub _add_to_env {
                   15536:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15537:     if (ref($env_data) eq 'HASH') {
                   15538:         while (my ($key,$value) = each(%$env_data)) {
                   15539: 	    $idf->{$prefix.$key} = $value;
                   15540: 	    $env{$prefix.$key}   = $value;
                   15541:         }
1.462     albertel 15542:     }
                   15543: }
                   15544: 
1.685     tempelho 15545: # --- Get the symbolic name of a problem and the url
                   15546: sub get_symb {
                   15547:     my ($request,$silent) = @_;
1.726     raeburn  15548:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15549:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15550:     if ($symb eq '') {
                   15551:         if (!$silent) {
1.1071    raeburn  15552:             if (ref($request)) { 
                   15553:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15554:             }
1.685     tempelho 15555:             return ();
                   15556:         }
                   15557:     }
                   15558:     &Apache::lonenc::check_decrypt(\$symb);
                   15559:     return ($symb);
                   15560: }
                   15561: 
                   15562: # --------------------------------------------------------------Get annotation
                   15563: 
                   15564: sub get_annotation {
                   15565:     my ($symb,$enc) = @_;
                   15566: 
                   15567:     my $key = $symb;
                   15568:     if (!$enc) {
                   15569:         $key =
                   15570:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15571:     }
                   15572:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15573:     return $annotation{$key};
                   15574: }
                   15575: 
                   15576: sub clean_symb {
1.731     raeburn  15577:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15578: 
                   15579:     &Apache::lonenc::check_decrypt(\$symb);
                   15580:     my $enc = $env{'request.enc'};
1.731     raeburn  15581:     if ($delete_enc) {
1.730     raeburn  15582:         delete($env{'request.enc'});
                   15583:     }
1.685     tempelho 15584: 
                   15585:     return ($symb,$enc);
                   15586: }
1.462     albertel 15587: 
1.1181    raeburn  15588: ############################################################
                   15589: ############################################################
                   15590: 
                   15591: =pod
                   15592: 
                   15593: =head1 Routines for building display used to search for courses
                   15594: 
                   15595: 
                   15596: =over 4
                   15597: 
                   15598: =item * &build_filters()
                   15599: 
                   15600: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  15601: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15602: and quotacheck.pl
                   15603: 
1.1181    raeburn  15604: 
                   15605: Inputs:
                   15606: 
                   15607: filterlist - anonymous array of fields to include as potential filters 
                   15608: 
                   15609: crstype - course type
                   15610: 
                   15611: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15612:               to pop-open a course selector (will contain "extra element"). 
                   15613: 
                   15614: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15615: 
                   15616: filter - anonymous hash of criteria and their values
                   15617: 
                   15618: action - form action
                   15619: 
                   15620: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15621: 
1.1182    raeburn  15622: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  15623: 
                   15624: cloneruname - username of owner of new course who wants to clone
                   15625: 
                   15626: clonerudom - domain of owner of new course who wants to clone
                   15627: 
                   15628: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   15629: 
                   15630: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15631: 
                   15632: codedom - domain
                   15633: 
                   15634: formname - value of form element named "form". 
                   15635: 
                   15636: fixeddom - domain, if fixed.
                   15637: 
                   15638: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   15639: 
                   15640: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   15641: 
                   15642: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15643: 
                   15644: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15645: 
                   15646: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15647: 
                   15648: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15649: 
                   15650: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15651: 
1.1182    raeburn  15652: 
1.1181    raeburn  15653: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15654: 
1.1182    raeburn  15655: 
1.1181    raeburn  15656: Side Effects: None
                   15657: 
                   15658: =cut
                   15659: 
                   15660: # ---------------------------------------------- search for courses based on last activity etc.
                   15661: 
                   15662: sub build_filters {
                   15663:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15664:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15665:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15666:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15667:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  15668:     my ($list,$jscript);
1.1181    raeburn  15669:     my $onchange = 'javascript:updateFilters(this)';
                   15670:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15671:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15672:         $typeselectform,$instcodetitle);
                   15673:     if ($formname eq '') {
                   15674:         $formname = $caller;
                   15675:     }
                   15676:     foreach my $item (@{$filterlist}) {
                   15677:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15678:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15679:             if ($item eq 'domainfilter') {
                   15680:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15681:             } elsif ($item eq 'coursefilter') {
                   15682:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15683:             } elsif ($item eq 'ownerfilter') {
                   15684:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15685:             } elsif ($item eq 'ownerdomfilter') {
                   15686:                 $filter->{'ownerdomfilter'} =
                   15687:                     &LONCAPA::clean_domain($filter->{$item});
                   15688:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15689:                                                        'ownerdomfilter',1);
                   15690:             } elsif ($item eq 'personfilter') {
                   15691:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15692:             } elsif ($item eq 'persondomfilter') {
                   15693:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15694:                                                         'persondomfilter',1);
                   15695:             } else {
                   15696:                 $filter->{$item} =~ s/\W//g;
                   15697:             }
                   15698:             if (!$filter->{$item}) {
                   15699:                 $filter->{$item} = '';
                   15700:             }
                   15701:         }
                   15702:         if ($item eq 'domainfilter') {
                   15703:             my $allow_blank = 1;
                   15704:             if ($formname eq 'portform') {
                   15705:                 $allow_blank=0;
                   15706:             } elsif ($formname eq 'studentform') {
                   15707:                 $allow_blank=0;
                   15708:             }
                   15709:             if ($fixeddom) {
                   15710:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15711:                                     ' value="'.$codedom.'" />'.
                   15712:                                     &Apache::lonnet::domain($codedom,'description');
                   15713:             } else {
                   15714:                 $domainselectform = &select_dom_form($filter->{$item},
                   15715:                                                      'domainfilter',
                   15716:                                                       $allow_blank,'',$onchange);
                   15717:             }
                   15718:         } else {
                   15719:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15720:         }
                   15721:     }
                   15722: 
                   15723:     # last course activity filter and selection
                   15724:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15725: 
                   15726:     # course created filter and selection
                   15727:     if (exists($filter->{'createdfilter'})) {
                   15728:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15729:     }
                   15730: 
                   15731:     my %lt = &Apache::lonlocal::texthash(
                   15732:                 'cac' => "$crstype Activity",
                   15733:                 'ccr' => "$crstype Created",
                   15734:                 'cde' => "$crstype Title",
                   15735:                 'cdo' => "$crstype Domain",
                   15736:                 'ins' => 'Institutional Code',
                   15737:                 'inc' => 'Institutional Categorization',
                   15738:                 'cow' => "$crstype Owner/Co-owner",
                   15739:                 'cop' => "$crstype Personnel Includes",
                   15740:                 'cog' => 'Type',
                   15741:              );
                   15742: 
                   15743:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15744:         my $typeval = 'Course';
                   15745:         if ($crstype eq 'Community') {
                   15746:             $typeval = 'Community';
                   15747:         }
                   15748:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15749:     } else {
                   15750:         $typeselectform =  '<select name="type" size="1"';
                   15751:         if ($onchange) {
                   15752:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15753:         }
                   15754:         $typeselectform .= '>'."\n";
                   15755:         foreach my $posstype ('Course','Community') {
                   15756:             $typeselectform.='<option value="'.$posstype.'"'.
                   15757:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15758:         }
                   15759:         $typeselectform.="</select>";
                   15760:     }
                   15761: 
                   15762:     my ($cloneableonlyform,$cloneabletitle);
                   15763:     if (exists($filter->{'cloneableonly'})) {
                   15764:         my $cloneableon = '';
                   15765:         my $cloneableoff = ' checked="checked"';
                   15766:         if ($filter->{'cloneableonly'}) {
                   15767:             $cloneableon = $cloneableoff;
                   15768:             $cloneableoff = '';
                   15769:         }
                   15770:         $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>';
                   15771:         if ($formname eq 'ccrs') {
1.1187    bisitz   15772:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  15773:         } else {
                   15774:             $cloneabletitle = &mt('Cloneable by you');
                   15775:         }
                   15776:     }
                   15777:     my $officialjs;
                   15778:     if ($crstype eq 'Course') {
                   15779:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  15780: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15781: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15782:             if ($codedom) { 
1.1181    raeburn  15783:                 $officialjs = 1;
                   15784:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15785:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15786:                                                                   $officialjs,$codetitlesref);
                   15787:                 if ($jscript) {
1.1182    raeburn  15788:                     $jscript = '<script type="text/javascript">'."\n".
                   15789:                                '// <![CDATA['."\n".
                   15790:                                $jscript."\n".
                   15791:                                '// ]]>'."\n".
                   15792:                                '</script>'."\n";
1.1181    raeburn  15793:                 }
                   15794:             }
                   15795:             if ($instcodeform eq '') {
                   15796:                 $instcodeform =
                   15797:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15798:                     $list->{'instcodefilter'}.'" />';
                   15799:                 $instcodetitle = $lt{'ins'};
                   15800:             } else {
                   15801:                 $instcodetitle = $lt{'inc'};
                   15802:             }
                   15803:             if ($fixeddom) {
                   15804:                 $instcodetitle .= '<br />('.$codedom.')';
                   15805:             }
                   15806:         }
                   15807:     }
                   15808:     my $output = qq|
                   15809: <form method="post" name="filterpicker" action="$action">
                   15810: <input type="hidden" name="form" value="$formname" />
                   15811: |;
                   15812:     if ($formname eq 'modifycourse') {
                   15813:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15814:                    '<input type="hidden" name="prevphase" value="'.
                   15815:                    $prevphase.'" />'."\n";
1.1198    musolffc 15816:     } elsif ($formname eq 'quotacheck') {
                   15817:         $output .= qq|
                   15818: <input type="hidden" name="sortby" value="" />
                   15819: <input type="hidden" name="sortorder" value="" />
                   15820: |;
                   15821:     } else {
1.1181    raeburn  15822:         my $name_input;
                   15823:         if ($cnameelement ne '') {
                   15824:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15825:                           $cnameelement.'" />';
                   15826:         }
                   15827:         $output .= qq|
1.1182    raeburn  15828: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15829: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  15830: $name_input
                   15831: $roleelement
                   15832: $multelement
                   15833: $typeelement
                   15834: |;
                   15835:         if ($formname eq 'portform') {
                   15836:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15837:         }
                   15838:     }
                   15839:     if ($fixeddom) {
                   15840:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15841:     }
                   15842:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15843:     if ($sincefilterform) {
                   15844:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15845:                   .$sincefilterform
                   15846:                   .&Apache::lonhtmlcommon::row_closure();
                   15847:     }
                   15848:     if ($createdfilterform) {
                   15849:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15850:                   .$createdfilterform
                   15851:                   .&Apache::lonhtmlcommon::row_closure();
                   15852:     }
                   15853:     if ($domainselectform) {
                   15854:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15855:                   .$domainselectform
                   15856:                   .&Apache::lonhtmlcommon::row_closure();
                   15857:     }
                   15858:     if ($typeselectform) {
                   15859:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15860:             $output .= $typeselectform;
                   15861:         } else {
                   15862:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15863:                       .$typeselectform
                   15864:                       .&Apache::lonhtmlcommon::row_closure();
                   15865:         }
                   15866:     }
                   15867:     if ($instcodeform) {
                   15868:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15869:                   .$instcodeform
                   15870:                   .&Apache::lonhtmlcommon::row_closure();
                   15871:     }
                   15872:     if (exists($filter->{'ownerfilter'})) {
                   15873:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15874:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15875:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15876:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15877:                    $ownerdomselectform.'</td></tr></table>'.
                   15878:                    &Apache::lonhtmlcommon::row_closure();
                   15879:     }
                   15880:     if (exists($filter->{'personfilter'})) {
                   15881:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15882:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15883:                    '<input type="text" name="personfilter" size="20" value="'.
                   15884:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15885:                    $persondomselectform.'</td></tr></table>'.
                   15886:                    &Apache::lonhtmlcommon::row_closure();
                   15887:     }
                   15888:     if (exists($filter->{'coursefilter'})) {
                   15889:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15890:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15891:                   .$list->{'coursefilter'}.'" />'
                   15892:                   .&Apache::lonhtmlcommon::row_closure();
                   15893:     }
                   15894:     if ($cloneableonlyform) {
                   15895:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15896:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15897:     }
                   15898:     if (exists($filter->{'descriptfilter'})) {
                   15899:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15900:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15901:                   .$list->{'descriptfilter'}.'" />'
                   15902:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15903:     }
                   15904:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15905:                '<input type="hidden" name="updater" value="" />'."\n".
                   15906:                '<input type="submit" name="gosearch" value="'.
                   15907:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15908:     return $jscript.$clonewarning.$output;
                   15909: }
                   15910: 
                   15911: =pod 
                   15912: 
                   15913: =item * &timebased_select_form()
                   15914: 
1.1182    raeburn  15915: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  15916: filter e.g., Course Activity, Course Created, when searching for courses
                   15917: or communities
                   15918: 
                   15919: Inputs:
                   15920: 
                   15921: item - name of form element (sincefilter or createdfilter)
                   15922: 
                   15923: filter - anonymous hash of criteria and their values
                   15924: 
                   15925: Returns: HTML for a select box contained a blank, then six time selections,
                   15926:          with value set in incoming form variables currently selected. 
                   15927: 
                   15928: Side Effects: None
                   15929: 
                   15930: =cut
                   15931: 
                   15932: sub timebased_select_form {
                   15933:     my ($item,$filter) = @_;
                   15934:     if (ref($filter) eq 'HASH') {
                   15935:         $filter->{$item} =~ s/[^\d-]//g;
                   15936:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15937:         return &select_form(
                   15938:                             $filter->{$item},
                   15939:                             $item,
                   15940:                             {      '-1' => '',
                   15941:                                 '86400' => &mt('today'),
                   15942:                                '604800' => &mt('last week'),
                   15943:                               '2592000' => &mt('last month'),
                   15944:                               '7776000' => &mt('last three months'),
                   15945:                              '15552000' => &mt('last six months'),
                   15946:                              '31104000' => &mt('last year'),
                   15947:                     'select_form_order' =>
                   15948:                            ['-1','86400','604800','2592000','7776000',
                   15949:                             '15552000','31104000']});
                   15950:     }
                   15951: }
                   15952: 
                   15953: =pod
                   15954: 
                   15955: =item * &js_changer()
                   15956: 
                   15957: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  15958: when course type or domain is changed, and also to hide 'Searching ...' on
                   15959: page load completion for page showing search result.
1.1181    raeburn  15960: 
                   15961: Inputs: None
                   15962: 
1.1183    raeburn  15963: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  15964: 
                   15965: Side Effects: None
                   15966: 
                   15967: =cut
                   15968: 
                   15969: sub js_changer {
                   15970:     return <<ENDJS;
                   15971: <script type="text/javascript">
                   15972: // <![CDATA[
                   15973: function updateFilters(caller) {
                   15974:     if (typeof(caller) != "undefined") {
                   15975:         document.filterpicker.updater.value = caller.name;
                   15976:     }
                   15977:     document.filterpicker.submit();
                   15978: }
1.1183    raeburn  15979: 
                   15980: function hideSearching() {
                   15981:     if (document.getElementById('searching')) {
                   15982:         document.getElementById('searching').style.display = 'none';
                   15983:     }
                   15984:     return;
                   15985: }
                   15986: 
1.1181    raeburn  15987: // ]]>
                   15988: </script>
                   15989: 
                   15990: ENDJS
                   15991: }
                   15992: 
                   15993: =pod
                   15994: 
1.1182    raeburn  15995: =item * &search_courses()
                   15996: 
                   15997: Process selected filters form course search form and pass to lonnet::courseiddump
                   15998: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   15999: 
                   16000: Inputs:
                   16001: 
                   16002: dom - domain being searched 
                   16003: 
                   16004: type - course type ('Course' or 'Community' or '.' if any).
                   16005: 
                   16006: filter - anonymous hash of criteria and their values
                   16007: 
                   16008: numtitles - for institutional codes - number of categories
                   16009: 
                   16010: cloneruname - optional username of new course owner
                   16011: 
                   16012: clonerudom - optional domain of new course owner
                   16013: 
1.1221    raeburn  16014: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  16015:             (used when DC is using course creation form)
                   16016: 
                   16017: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16018: 
1.1221    raeburn  16019: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16020:            (and so can clone automatically)
                   16021: 
                   16022: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16023: 
                   16024: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   16025:               courses to clone 
1.1182    raeburn  16026: 
                   16027: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16028: 
                   16029: 
                   16030: Side Effects: None
                   16031: 
                   16032: =cut
                   16033: 
                   16034: 
                   16035: sub search_courses {
1.1221    raeburn  16036:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16037:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  16038:     my (%courses,%showcourses,$cloner);
                   16039:     if (($filter->{'ownerfilter'} ne '') ||
                   16040:         ($filter->{'ownerdomfilter'} ne '')) {
                   16041:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16042:                                        $filter->{'ownerdomfilter'};
                   16043:     }
                   16044:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16045:         if (!$filter->{$item}) {
                   16046:             $filter->{$item}='.';
                   16047:         }
                   16048:     }
                   16049:     my $now = time;
                   16050:     my $timefilter =
                   16051:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16052:     my ($createdbefore,$createdafter);
                   16053:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16054:         $createdbefore = $now;
                   16055:         $createdafter = $now-$filter->{'createdfilter'};
                   16056:     }
                   16057:     my ($instcodefilter,$regexpok);
                   16058:     if ($numtitles) {
                   16059:         if ($env{'form.official'} eq 'on') {
                   16060:             $instcodefilter =
                   16061:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16062:             $regexpok = 1;
                   16063:         } elsif ($env{'form.official'} eq 'off') {
                   16064:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16065:             unless ($instcodefilter eq '') {
                   16066:                 $regexpok = -1;
                   16067:             }
                   16068:         }
                   16069:     } else {
                   16070:         $instcodefilter = $filter->{'instcodefilter'};
                   16071:     }
                   16072:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16073:     if ($type eq '') { $type = '.'; }
                   16074: 
                   16075:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16076:         $cloner = $cloneruname.':'.$clonerudom;
                   16077:     }
                   16078:     %courses = &Apache::lonnet::courseiddump($dom,
                   16079:                                              $filter->{'descriptfilter'},
                   16080:                                              $timefilter,
                   16081:                                              $instcodefilter,
                   16082:                                              $filter->{'combownerfilter'},
                   16083:                                              $filter->{'coursefilter'},
                   16084:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  16085:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  16086:                                              $filter->{'cloneableonly'},
                   16087:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  16088:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  16089:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16090:         my $ccrole;
                   16091:         if ($type eq 'Community') {
                   16092:             $ccrole = 'co';
                   16093:         } else {
                   16094:             $ccrole = 'cc';
                   16095:         }
                   16096:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16097:                                                      $filter->{'persondomfilter'},
                   16098:                                                      'userroles',undef,
                   16099:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16100:                                                      $dom);
                   16101:         foreach my $role (keys(%rolehash)) {
                   16102:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16103:             my $cid = $cdom.'_'.$cnum;
                   16104:             if (exists($courses{$cid})) {
                   16105:                 if (ref($courses{$cid}) eq 'HASH') {
                   16106:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16107:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   16108:                             push (@{$courses{$cid}{roles}},$courserole);
                   16109:                         }
                   16110:                     } else {
                   16111:                         $courses{$cid}{roles} = [$courserole];
                   16112:                     }
                   16113:                     $showcourses{$cid} = $courses{$cid};
                   16114:                 }
                   16115:             }
                   16116:         }
                   16117:         %courses = %showcourses;
                   16118:     }
                   16119:     return %courses;
                   16120: }
                   16121: 
                   16122: =pod
                   16123: 
1.1181    raeburn  16124: =back
                   16125: 
1.1207    raeburn  16126: =head1 Routines for version requirements for current course.
                   16127: 
                   16128: =over 4
                   16129: 
                   16130: =item * &check_release_required()
                   16131: 
                   16132: Compares required LON-CAPA version with version on server, and
                   16133: if required version is newer looks for a server with the required version.
                   16134: 
                   16135: Looks first at servers in user's owen domain; if none suitable, looks at
                   16136: servers in course's domain are permitted to host sessions for user's domain.
                   16137: 
                   16138: Inputs:
                   16139: 
                   16140: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16141: 
                   16142: $courseid - Course ID of current course
                   16143: 
                   16144: $rolecode - User's current role in course (for switchserver query string).
                   16145: 
                   16146: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16147: 
                   16148: 
                   16149: Returns:
                   16150: 
                   16151: $switchserver - query string tp append to /adm/switchserver call (if 
                   16152:                 current server's LON-CAPA version is too old. 
                   16153: 
                   16154: $warning - Message is displayed if no suitable server could be found.
                   16155: 
                   16156: =cut
                   16157: 
                   16158: sub check_release_required {
                   16159:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16160:     my ($switchserver,$warning);
                   16161:     if ($required ne '') {
                   16162:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16163:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16164:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16165:             my $otherserver;
                   16166:             if (($major eq '' && $minor eq '') ||
                   16167:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16168:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16169:                 my $switchlcrev =
                   16170:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16171:                                                            $userdomserver);
                   16172:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16173:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16174:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16175:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16176:                     if ($cdom ne $env{'user.domain'}) {
                   16177:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16178:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16179:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16180:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16181:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16182:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16183:                         my $canhost =
                   16184:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16185:                                                               $coursedomserver,
                   16186:                                                               $remoterev,
                   16187:                                                               $udomdefaults{'remotesessions'},
                   16188:                                                               $defdomdefaults{'hostedsessions'});
                   16189: 
                   16190:                         if ($canhost) {
                   16191:                             $otherserver = $coursedomserver;
                   16192:                         } else {
                   16193:                             $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.");
                   16194:                         }
                   16195:                     } else {
                   16196:                         $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).");
                   16197:                     }
                   16198:                 } else {
                   16199:                     $otherserver = $userdomserver;
                   16200:                 }
                   16201:             }
                   16202:             if ($otherserver ne '') {
                   16203:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16204:             }
                   16205:         }
                   16206:     }
                   16207:     return ($switchserver,$warning);
                   16208: }
                   16209: 
                   16210: =pod
                   16211: 
                   16212: =item * &check_release_result()
                   16213: 
                   16214: Inputs:
                   16215: 
                   16216: $switchwarning - Warning message if no suitable server found to host session.
                   16217: 
                   16218: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16219:                 and current role.
                   16220: 
                   16221: Returns: HTML to display with information about requirement to switch server.
                   16222:          Either displaying warning with link to Roles/Courses screen or
                   16223:          display link to switchserver.
                   16224: 
1.1181    raeburn  16225: =cut
                   16226: 
1.1207    raeburn  16227: sub check_release_result {
                   16228:     my ($switchwarning,$switchserver) = @_;
                   16229:     my $output = &start_page('Selected course unavailable on this server').
                   16230:                  '<p class="LC_warning">';
                   16231:     if ($switchwarning) {
                   16232:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16233:         if (&show_course()) {
                   16234:             $output .= &mt('Display courses');
                   16235:         } else {
                   16236:             $output .= &mt('Display roles');
                   16237:         }
                   16238:         $output .= '</a>';
                   16239:     } elsif ($switchserver) {
                   16240:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16241:                    '<br />'.
                   16242:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16243:                    &mt('Switch Server').
                   16244:                    '</a>';
                   16245:     }
                   16246:     $output .= '</p>'.&end_page();
                   16247:     return $output;
                   16248: }
                   16249: 
                   16250: =pod
                   16251: 
                   16252: =item * &needs_coursereinit()
                   16253: 
                   16254: Determine if course contents stored for user's session needs to be
                   16255: refreshed, because content has changed since "Big Hash" last tied.
                   16256: 
                   16257: Check for change is made if time last checked is more than 10 minutes ago
                   16258: (by default).
                   16259: 
                   16260: Inputs:
                   16261: 
                   16262: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16263: 
                   16264: $interval (optional) - Time which may elapse (in s) between last check for content
                   16265:                        change in current course. (default: 600 s).  
                   16266: 
                   16267: Returns: an array; first element is:
                   16268: 
                   16269: =over 4
                   16270: 
                   16271: 'switch' - if content updates mean user's session
                   16272:            needs to be switched to a server running a newer LON-CAPA version
                   16273:  
                   16274: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16275:            on current server hosting user's session                
                   16276: 
                   16277: ''       - if no action required.
                   16278: 
                   16279: =back
                   16280: 
                   16281: If first item element is 'switch':
                   16282: 
                   16283: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   16284: 
                   16285: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16286:                               and current role. 
                   16287: 
                   16288: otherwise: no other elements returned.
                   16289: 
                   16290: =back
                   16291: 
                   16292: =cut
                   16293: 
                   16294: sub needs_coursereinit {
                   16295:     my ($loncaparev,$interval) = @_;
                   16296:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16297:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16298:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16299:     my $now = time;
                   16300:     if ($interval eq '') {
                   16301:         $interval = 600;
                   16302:     }
                   16303:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16304:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16305:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16306:         if ($lastchange > $env{'request.course.tied'}) {
                   16307:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16308:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16309:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16310:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16311:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16312:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16313:                     my ($switchserver,$switchwarning) =
                   16314:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16315:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16316:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16317:                         return ('switch',$switchwarning,$switchserver);
                   16318:                     }
                   16319:                 }
                   16320:             }
                   16321:             return ('update');
                   16322:         }
                   16323:     }
                   16324:     return ();
                   16325: }
1.1181    raeburn  16326: 
1.1083    raeburn  16327: sub update_content_constraints {
                   16328:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16329:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16330:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16331:     my %checkresponsetypes;
                   16332:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1219    raeburn  16333:         my ($item,$name,$value,$valmatch) = split(/:/,$key);
1.1083    raeburn  16334:         if ($item eq 'resourcetag') {
                   16335:             if ($name eq 'responsetype') {
                   16336:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16337:             }
                   16338:         }
                   16339:     }
                   16340:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16341:     if (defined($navmap)) {
                   16342:         my %allresponses;
                   16343:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16344:             my %responses = $res->responseTypes();
                   16345:             foreach my $key (keys(%responses)) {
                   16346:                 next unless(exists($checkresponsetypes{$key}));
                   16347:                 $allresponses{$key} += $responses{$key};
                   16348:             }
                   16349:         }
                   16350:         foreach my $key (keys(%allresponses)) {
                   16351:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16352:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16353:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16354:             }
                   16355:         }
                   16356:         undef($navmap);
                   16357:     }
                   16358:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16359:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16360:     }
                   16361:     return;
                   16362: }
                   16363: 
1.1110    raeburn  16364: sub allmaps_incourse {
                   16365:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16366:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16367:         $cid = $env{'request.course.id'};
                   16368:         $cdom = $env{'course.'.$cid.'.domain'};
                   16369:         $cnum = $env{'course.'.$cid.'.num'};
                   16370:         $chome = $env{'course.'.$cid.'.home'};
                   16371:     }
                   16372:     my %allmaps = ();
                   16373:     my $lastchange =
                   16374:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16375:     if ($lastchange > $env{'request.course.tied'}) {
                   16376:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16377:         unless ($ferr) {
                   16378:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16379:         }
                   16380:     }
                   16381:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16382:     if (defined($navmap)) {
                   16383:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16384:             $allmaps{$res->src()} = 1;
                   16385:         }
                   16386:     }
                   16387:     return \%allmaps;
                   16388: }
                   16389: 
1.1083    raeburn  16390: sub parse_supplemental_title {
                   16391:     my ($title) = @_;
                   16392: 
                   16393:     my ($foldertitle,$renametitle);
                   16394:     if ($title =~ /&amp;&amp;&amp;/) {
                   16395:         $title = &HTML::Entites::decode($title);
                   16396:     }
                   16397:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16398:         $renametitle=$4;
                   16399:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16400:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16401:         my $name =  &plainname($uname,$udom);
                   16402:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16403:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16404:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16405:             $name.': <br />'.$foldertitle;
                   16406:     }
                   16407:     if (wantarray) {
                   16408:         return ($title,$foldertitle,$renametitle);
                   16409:     }
                   16410:     return $title;
                   16411: }
                   16412: 
1.1143    raeburn  16413: sub recurse_supplemental {
                   16414:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16415:     if ($suppmap) {
                   16416:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16417:         if ($fatal) {
                   16418:             $errors ++;
                   16419:         } else {
                   16420:             if ($#LONCAPA::map::resources > 0) {
                   16421:                 foreach my $res (@LONCAPA::map::resources) {
                   16422:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16423:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  16424:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16425:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  16426:                         } else {
                   16427:                             $numfiles ++;
                   16428:                         }
                   16429:                     }
                   16430:                 }
                   16431:             }
                   16432:         }
                   16433:     }
                   16434:     return ($numfiles,$errors);
                   16435: }
                   16436: 
1.1101    raeburn  16437: sub symb_to_docspath {
                   16438:     my ($symb) = @_;
                   16439:     return unless ($symb);
                   16440:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16441:     if ($resurl=~/\.(sequence|page)$/) {
                   16442:         $mapurl=$resurl;
                   16443:     } elsif ($resurl eq 'adm/navmaps') {
                   16444:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16445:     }
                   16446:     my $mapresobj;
                   16447:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16448:     if (ref($navmap)) {
                   16449:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   16450:     }
                   16451:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16452:     my $type=$2;
                   16453:     my $path;
                   16454:     if (ref($mapresobj)) {
                   16455:         my $pcslist = $mapresobj->map_hierarchy();
                   16456:         if ($pcslist ne '') {
                   16457:             foreach my $pc (split(/,/,$pcslist)) {
                   16458:                 next if ($pc <= 1);
                   16459:                 my $res = $navmap->getByMapPc($pc);
                   16460:                 if (ref($res)) {
                   16461:                     my $thisurl = $res->src();
                   16462:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16463:                     my $thistitle = $res->title();
                   16464:                     $path .= '&'.
                   16465:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  16466:                              &escape($thistitle).
1.1101    raeburn  16467:                              ':'.$res->randompick().
                   16468:                              ':'.$res->randomout().
                   16469:                              ':'.$res->encrypted().
                   16470:                              ':'.$res->randomorder().
                   16471:                              ':'.$res->is_page();
                   16472:                 }
                   16473:             }
                   16474:         }
                   16475:         $path =~ s/^\&//;
                   16476:         my $maptitle = $mapresobj->title();
                   16477:         if ($mapurl eq 'default') {
1.1129    raeburn  16478:             $maptitle = 'Main Content';
1.1101    raeburn  16479:         }
                   16480:         $path .= (($path ne '')? '&' : '').
                   16481:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16482:                  &escape($maptitle).
1.1101    raeburn  16483:                  ':'.$mapresobj->randompick().
                   16484:                  ':'.$mapresobj->randomout().
                   16485:                  ':'.$mapresobj->encrypted().
                   16486:                  ':'.$mapresobj->randomorder().
                   16487:                  ':'.$mapresobj->is_page();
                   16488:     } else {
                   16489:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16490:         my $ispage = (($type eq 'page')? 1 : '');
                   16491:         if ($mapurl eq 'default') {
1.1129    raeburn  16492:             $maptitle = 'Main Content';
1.1101    raeburn  16493:         }
                   16494:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16495:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  16496:     }
                   16497:     unless ($mapurl eq 'default') {
                   16498:         $path = 'default&'.
1.1146    raeburn  16499:                 &escape('Main Content').
1.1101    raeburn  16500:                 ':::::&'.$path;
                   16501:     }
                   16502:     return $path;
                   16503: }
                   16504: 
1.1094    raeburn  16505: sub captcha_display {
                   16506:     my ($context,$lonhost) = @_;
                   16507:     my ($output,$error);
                   16508:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  16509:     if ($captcha eq 'original') {
1.1094    raeburn  16510:         $output = &create_captcha();
                   16511:         unless ($output) {
1.1172    raeburn  16512:             $error = 'captcha';
1.1094    raeburn  16513:         }
                   16514:     } elsif ($captcha eq 'recaptcha') {
                   16515:         $output = &create_recaptcha($pubkey);
                   16516:         unless ($output) {
1.1172    raeburn  16517:             $error = 'recaptcha';
1.1094    raeburn  16518:         }
                   16519:     }
1.1176    raeburn  16520:     return ($output,$error,$captcha);
1.1094    raeburn  16521: }
                   16522: 
                   16523: sub captcha_response {
                   16524:     my ($context,$lonhost) = @_;
                   16525:     my ($captcha_chk,$captcha_error);
                   16526:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  16527:     if ($captcha eq 'original') {
1.1094    raeburn  16528:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16529:     } elsif ($captcha eq 'recaptcha') {
                   16530:         $captcha_chk = &check_recaptcha($privkey);
                   16531:     } else {
                   16532:         $captcha_chk = 1;
                   16533:     }
                   16534:     return ($captcha_chk,$captcha_error);
                   16535: }
                   16536: 
                   16537: sub get_captcha_config {
                   16538:     my ($context,$lonhost) = @_;
1.1095    raeburn  16539:     my ($captcha,$pubkey,$privkey,$hashtocheck);
1.1094    raeburn  16540:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16541:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16542:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  16543:     if ($context eq 'usercreation') {
                   16544:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16545:         if (ref($domconfig{$context}) eq 'HASH') {
                   16546:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16547:             if (ref($hashtocheck) eq 'HASH') {
                   16548:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16549:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16550:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16551:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16552:                     }
                   16553:                     if ($privkey && $pubkey) {
                   16554:                         $captcha = 'recaptcha';
                   16555:                     } else {
                   16556:                         $captcha = 'original';
                   16557:                     }
                   16558:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16559:                     $captcha = 'original';
                   16560:                 }
1.1094    raeburn  16561:             }
1.1095    raeburn  16562:         } else {
                   16563:             $captcha = 'captcha';
                   16564:         }
                   16565:     } elsif ($context eq 'login') {
                   16566:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16567:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16568:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16569:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  16570:             if ($privkey && $pubkey) {
                   16571:                 $captcha = 'recaptcha';
1.1095    raeburn  16572:             } else {
                   16573:                 $captcha = 'original';
1.1094    raeburn  16574:             }
1.1095    raeburn  16575:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16576:             $captcha = 'original';
1.1094    raeburn  16577:         }
                   16578:     }
                   16579:     return ($captcha,$pubkey,$privkey);
                   16580: }
                   16581: 
                   16582: sub create_captcha {
                   16583:     my %captcha_params = &captcha_settings();
                   16584:     my ($output,$maxtries,$tries) = ('',10,0);
                   16585:     while ($tries < $maxtries) {
                   16586:         $tries ++;
                   16587:         my $captcha = Authen::Captcha->new (
                   16588:                                            output_folder => $captcha_params{'output_dir'},
                   16589:                                            data_folder   => $captcha_params{'db_dir'},
                   16590:                                           );
                   16591:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16592: 
                   16593:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16594:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16595:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  16596:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16597:                       '<br />'.
                   16598:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  16599:             last;
                   16600:         }
                   16601:     }
                   16602:     return $output;
                   16603: }
                   16604: 
                   16605: sub captcha_settings {
                   16606:     my %captcha_params = (
                   16607:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16608:                            www_output_dir => "/captchaspool",
                   16609:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16610:                            numchars       => '5',
                   16611:                          );
                   16612:     return %captcha_params;
                   16613: }
                   16614: 
                   16615: sub check_captcha {
                   16616:     my ($captcha_chk,$captcha_error);
                   16617:     my $code = $env{'form.code'};
                   16618:     my $md5sum = $env{'form.crypt'};
                   16619:     my %captcha_params = &captcha_settings();
                   16620:     my $captcha = Authen::Captcha->new(
                   16621:                       output_folder => $captcha_params{'output_dir'},
                   16622:                       data_folder   => $captcha_params{'db_dir'},
                   16623:                   );
1.1109    raeburn  16624:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  16625:     my %captcha_hash = (
                   16626:                         0       => 'Code not checked (file error)',
                   16627:                        -1      => 'Failed: code expired',
                   16628:                        -2      => 'Failed: invalid code (not in database)',
                   16629:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16630:     );
                   16631:     if ($captcha_chk != 1) {
                   16632:         $captcha_error = $captcha_hash{$captcha_chk}
                   16633:     }
                   16634:     return ($captcha_chk,$captcha_error);
                   16635: }
                   16636: 
                   16637: sub create_recaptcha {
                   16638:     my ($pubkey) = @_;
1.1153    raeburn  16639:     my $use_ssl;
                   16640:     if ($ENV{'SERVER_PORT'} == 443) {
                   16641:         $use_ssl = 1;
                   16642:     }
1.1094    raeburn  16643:     my $captcha = Captcha::reCAPTCHA->new;
                   16644:     return $captcha->get_options_setter({theme => 'white'})."\n".
1.1153    raeburn  16645:            $captcha->get_html($pubkey,undef,$use_ssl).
1.1213    raeburn  16646:            &mt('If the text is hard to read, [_1] will replace them.',
1.1133    raeburn  16647:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1094    raeburn  16648:            '<br /><br />';
                   16649: }
                   16650: 
                   16651: sub check_recaptcha {
                   16652:     my ($privkey) = @_;
                   16653:     my $captcha_chk;
                   16654:     my $captcha = Captcha::reCAPTCHA->new;
                   16655:     my $captcha_result =
                   16656:         $captcha->check_answer(
                   16657:                                 $privkey,
                   16658:                                 $ENV{'REMOTE_ADDR'},
                   16659:                                 $env{'form.recaptcha_challenge_field'},
                   16660:                                 $env{'form.recaptcha_response_field'},
                   16661:                               );
                   16662:     if ($captcha_result->{is_valid}) {
                   16663:         $captcha_chk = 1;
                   16664:     }
                   16665:     return $captcha_chk;
                   16666: }
                   16667: 
1.1174    raeburn  16668: sub emailusername_info {
1.1177    raeburn  16669:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
1.1174    raeburn  16670:     my %titles = &Apache::lonlocal::texthash (
                   16671:                      lastname      => 'Last Name',
                   16672:                      firstname     => 'First Name',
                   16673:                      institution   => 'School/college/university',
                   16674:                      location      => "School's city, state/province, country",
                   16675:                      web           => "School's web address",
                   16676:                      officialemail => 'E-mail address at institution (if different)',
                   16677:                  );
                   16678:     return (\@fields,\%titles);
                   16679: }
                   16680: 
1.1161    raeburn  16681: sub cleanup_html {
                   16682:     my ($incoming) = @_;
                   16683:     my $outgoing;
                   16684:     if ($incoming ne '') {
                   16685:         $outgoing = $incoming;
                   16686:         $outgoing =~ s/;/&#059;/g;
                   16687:         $outgoing =~ s/\#/&#035;/g;
                   16688:         $outgoing =~ s/\&/&#038;/g;
                   16689:         $outgoing =~ s/</&#060;/g;
                   16690:         $outgoing =~ s/>/&#062;/g;
                   16691:         $outgoing =~ s/\(/&#040/g;
                   16692:         $outgoing =~ s/\)/&#041;/g;
                   16693:         $outgoing =~ s/"/&#034;/g;
                   16694:         $outgoing =~ s/'/&#039;/g;
                   16695:         $outgoing =~ s/\$/&#036;/g;
                   16696:         $outgoing =~ s{/}{&#047;}g;
                   16697:         $outgoing =~ s/=/&#061;/g;
                   16698:         $outgoing =~ s/\\/&#092;/g
                   16699:     }
                   16700:     return $outgoing;
                   16701: }
                   16702: 
1.1190    musolffc 16703: # Checks for critical messages and returns a redirect url if one exists.
                   16704: # $interval indicates how often to check for messages.
                   16705: sub critical_redirect {
                   16706:     my ($interval) = @_;
                   16707:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16708:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   16709:                                         $env{'user.name'});
                   16710:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  16711:         my $redirecturl;
1.1190    musolffc 16712:         if ($what[0]) {
                   16713: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16714: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  16715: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16716:                 return (1, $url);
1.1190    musolffc 16717:             }
1.1191    raeburn  16718:         }
                   16719:     } 
                   16720:     return ();
1.1190    musolffc 16721: }
                   16722: 
1.1174    raeburn  16723: # Use:
                   16724: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16725: #
                   16726: ##################################################
                   16727: #          password associated functions         #
                   16728: ##################################################
                   16729: sub des_keys {
                   16730:     # Make a new key for DES encryption.
                   16731:     # Each key has two parts which are returned separately.
                   16732:     # Please note:  Each key must be passed through the &hex function
                   16733:     # before it is output to the web browser.  The hex versions cannot
                   16734:     # be used to decrypt.
                   16735:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16736:                 '8','9','a','b','c','d','e','f');
                   16737:     my $lkey='';
                   16738:     for (0..7) {
                   16739:         $lkey.=$hexstr[rand(15)];
                   16740:     }
                   16741:     my $ukey='';
                   16742:     for (0..7) {
                   16743:         $ukey.=$hexstr[rand(15)];
                   16744:     }
                   16745:     return ($lkey,$ukey);
                   16746: }
                   16747: 
                   16748: sub des_decrypt {
                   16749:     my ($key,$cyphertext) = @_;
                   16750:     my $keybin=pack("H16",$key);
                   16751:     my $cypher;
                   16752:     if ($Crypt::DES::VERSION>=2.03) {
                   16753:         $cypher=new Crypt::DES $keybin;
                   16754:     } else {
                   16755:         $cypher=new DES $keybin;
                   16756:     }
                   16757:     my $plaintext=
                   16758:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
                   16759:     $plaintext.=
                   16760:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
                   16761:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
                   16762:     return $plaintext;
                   16763: }
                   16764: 
1.112     bowersj2 16765: 1;
                   16766: __END__;
1.41      ng       16767: 

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