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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1231  ! damieng     4: # $Id: loncommon.pm,v 1.1230 2015/12/22 20:39:18 damieng 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: /*
1.1231  ! damieng  7651:   styles used for response display
        !          7652: */
        !          7653: div.LC_radiofoil, div.LC_rankfoil {
        !          7654:   margin: .5em 0em .5em 0em;
        !          7655: }
        !          7656: table.LC_itemgroup {
        !          7657:   margin-top: 1em;
        !          7658: }
        !          7659: 
        !          7660: /*
1.1100    raeburn  7661:   styles used by TTH when "Default set of options to pass to tth/m
                   7662:   when converting TeX" in course settings has been set
                   7663: 
                   7664:   option passed: -t
                   7665: 
                   7666: */
                   7667: 
                   7668: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7669: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7670: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7671: td div.norm {line-height:normal;}
                   7672: 
                   7673: /*
                   7674:   option passed -y3
                   7675: */
                   7676: 
                   7677: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7678: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7679: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7680: 
1.1230    damieng  7681: /*
                   7682:   sections with roles, for content only
                   7683: */
                   7684: section[class^="role-"] {
                   7685:   padding-left: 10px;
                   7686:   padding-right: 5px;
                   7687:   margin-top: 8px;
                   7688:   margin-bottom: 8px;
                   7689:   border: 1px solid #2A4;
                   7690:   border-radius: 5px;
                   7691:   box-shadow: 0px 1px 1px #BBB;
                   7692: }
                   7693: section[class^="role-"]>h1 {
                   7694:   position: relative;
                   7695:   margin: 0px;
                   7696:   padding-top: 10px;
                   7697:   padding-left: 40px;
                   7698: }
                   7699: section[class^="role-"]>h1:before {
                   7700:   position: absolute;
                   7701:   left: -5px;
                   7702:   top: 5px;
                   7703: }
                   7704: section.role-activity>h1:before {
                   7705:   content:url('/adm/daxe/images/section_icons/activity.png');
                   7706: }
                   7707: section.role-advice>h1:before {
                   7708:   content:url('/adm/daxe/images/section_icons/advice.png');
                   7709: }
                   7710: section.role-bibliography>h1:before {
                   7711:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   7712: }
                   7713: section.role-citation>h1:before {
                   7714:   content:url('/adm/daxe/images/section_icons/citation.png');
                   7715: }
                   7716: section.role-conclusion>h1:before {
                   7717:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   7718: }
                   7719: section.role-definition>h1:before {
                   7720:   content:url('/adm/daxe/images/section_icons/definition.png');
                   7721: }
                   7722: section.role-demonstration>h1:before {
                   7723:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   7724: }
                   7725: section.role-example>h1:before {
                   7726:   content:url('/adm/daxe/images/section_icons/example.png');
                   7727: }
                   7728: section.role-explanation>h1:before {
                   7729:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   7730: }
                   7731: section.role-introduction>h1:before {
                   7732:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   7733: }
                   7734: section.role-method>h1:before {
                   7735:   content:url('/adm/daxe/images/section_icons/method.png');
                   7736: }
                   7737: section.role-more_information>h1:before {
                   7738:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   7739: }
                   7740: section.role-objectives>h1:before {
                   7741:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   7742: }
                   7743: section.role-prerequisites>h1:before {
                   7744:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   7745: }
                   7746: section.role-remark>h1:before {
                   7747:   content:url('/adm/daxe/images/section_icons/remark.png');
                   7748: }
                   7749: section.role-reminder>h1:before {
                   7750:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   7751: }
                   7752: section.role-summary>h1:before {
                   7753:   content:url('/adm/daxe/images/section_icons/summary.png');
                   7754: }
                   7755: section.role-syntax>h1:before {
                   7756:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   7757: }
                   7758: section.role-warning>h1:before {
                   7759:   content:url('/adm/daxe/images/section_icons/warning.png');
                   7760: }
                   7761: 
1.343     albertel 7762: END
                   7763: }
                   7764: 
1.306     albertel 7765: =pod
                   7766: 
                   7767: =item * &headtag()
                   7768: 
                   7769: Returns a uniform footer for LON-CAPA web pages.
                   7770: 
1.307     albertel 7771: Inputs: $title - optional title for the head
                   7772:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7773:         $args - optional arguments
1.319     albertel 7774:             force_register - if is true call registerurl so the remote is 
                   7775:                              informed
1.415     albertel 7776:             redirect       -> array ref of
                   7777:                                    1- seconds before redirect occurs
                   7778:                                    2- url to redirect to
                   7779:                                    3- whether the side effect should occur
1.315     albertel 7780:                            (side effect of setting 
                   7781:                                $env{'internal.head.redirect'} to the url 
                   7782:                                redirected too)
1.352     albertel 7783:             domain         -> force to color decorate a page for a specific
                   7784:                                domain
                   7785:             function       -> force usage of a specific rolish color scheme
                   7786:             bgcolor        -> override the default page bgcolor
1.460     albertel 7787:             no_auto_mt_title
                   7788:                            -> prevent &mt()ing the title arg
1.464     albertel 7789: 
1.306     albertel 7790: =cut
                   7791: 
                   7792: sub headtag {
1.313     albertel 7793:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7794:     
1.363     albertel 7795:     my $function = $args->{'function'} || &get_users_function();
                   7796:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7797:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  7798:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7799:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7800: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7801: 		   #time(),
1.418     albertel 7802: 		   $env{'environment.color.timestamp'},
1.363     albertel 7803: 		   $function,$domain,$bgcolor);
                   7804: 
1.369     www      7805:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7806: 
1.308     albertel 7807:     my $result =
                   7808: 	'<head>'.
1.1160    raeburn  7809: 	&font_settings($args);
1.319     albertel 7810: 
1.1188    raeburn  7811:     my $inhibitprint;
                   7812:     if ($args->{'print_suppress'}) {
                   7813:         $inhibitprint = &print_suppression();
                   7814:     }
1.1064    raeburn  7815: 
1.461     albertel 7816:     if (!$args->{'frameset'}) {
                   7817: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7818:     }
1.962     droeschl 7819:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7820:         $result .= Apache::lonxml::display_title();
1.319     albertel 7821:     }
1.436     albertel 7822:     if (!$args->{'no_nav_bar'} 
                   7823: 	&& !$args->{'only_body'}
                   7824: 	&& !$args->{'frameset'}) {
1.1154    raeburn  7825: 	$result .= &help_menu_js($httphost);
1.1032    www      7826:         $result.=&modal_window();
1.1038    www      7827:         $result.=&togglebox_script();
1.1034    www      7828:         $result.=&wishlist_window();
1.1041    www      7829:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7830:     } else {
                   7831:         if ($args->{'add_modal'}) {
                   7832:            $result.=&modal_window();
                   7833:         }
                   7834:         if ($args->{'add_wishlist'}) {
                   7835:            $result.=&wishlist_window();
                   7836:         }
1.1038    www      7837:         if ($args->{'add_togglebox'}) {
                   7838:            $result.=&togglebox_script();
                   7839:         }
1.1041    www      7840:         if ($args->{'add_progressbar'}) {
                   7841:            $result.=&LCprogressbarUpdate_script();
                   7842:         }
1.436     albertel 7843:     }
1.314     albertel 7844:     if (ref($args->{'redirect'})) {
1.414     albertel 7845: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7846: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7847: 	if (!$inhibit_continue) {
                   7848: 	    $env{'internal.head.redirect'} = $url;
                   7849: 	}
1.313     albertel 7850: 	$result.=<<ADDMETA
                   7851: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7852: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7853: ADDMETA
1.1210    raeburn  7854:     } else {
                   7855:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7856:             my $requrl = $env{'request.uri'};
                   7857:             if ($requrl eq '') {
                   7858:                 $requrl = $ENV{'REQUEST_URI'};
                   7859:                 $requrl =~ s/\?.+$//;
                   7860:             }
                   7861:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7862:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7863:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7864:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7865:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7866:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7867:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7868:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7869:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7870:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7871:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7872:                                 my $numsec = 5;
                   7873:                                 my $timeout = $numsec * 1000;
                   7874:                                 my ($newurl,$locknum,%locks,$msg);
                   7875:                                 if ($env{'request.role.adv'}) {
                   7876:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7877:                                 }
                   7878:                                 my $disable_submit = 0;
                   7879:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7880:                                     $disable_submit = 1;
                   7881:                                 }
                   7882:                                 if ($locknum) {
                   7883:                                     my @lockinfo = sort(values(%locks));
                   7884:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7885:                                            join(", ",sort(values(%locks)))."\\n".
                   7886:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7887:                                 } else {
                   7888:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7889:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7890:                                     }
                   7891:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7892:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7893:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7894:                                         $newurl .= '&role='.$env{'request.role'};
                   7895:                                     }
                   7896:                                     if ($env{'request.symb'}) {
                   7897:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7898:                                     } else {
                   7899:                                         $newurl .= '&origurl='.$requrl;
                   7900:                                     }
                   7901:                                 }
1.1222    damieng  7902:                                 &js_escape(\$msg);
1.1210    raeburn  7903:                                 $result.=<<OFFLOAD
                   7904: <meta http-equiv="pragma" content="no-cache" />
                   7905: <script type="text/javascript">
1.1215    raeburn  7906: // <![CDATA[
1.1210    raeburn  7907: function LC_Offload_Now() {
                   7908:     var dest = "$newurl";
                   7909:     if (dest != '') {
                   7910:         window.location.href="$newurl";
                   7911:     }
                   7912: }
1.1214    raeburn  7913: \$(document).ready(function () {
                   7914:     window.alert('$msg');
                   7915:     if ($disable_submit) {
1.1210    raeburn  7916:         \$(".LC_hwk_submit").prop("disabled", true);
                   7917:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  7918:     }
                   7919:     setTimeout('LC_Offload_Now()', $timeout);
                   7920: });
1.1215    raeburn  7921: // ]]>
1.1210    raeburn  7922: </script>
                   7923: OFFLOAD
                   7924:                             }
                   7925:                         }
                   7926:                     }
                   7927:                 }
                   7928:             }
                   7929:         }
1.313     albertel 7930:     }
1.306     albertel 7931:     if (!defined($title)) {
                   7932: 	$title = 'The LearningOnline Network with CAPA';
                   7933:     }
1.460     albertel 7934:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7935:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  7936: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7937:     if (!$args->{'frameset'}) {
                   7938:         $result .= ' /';
                   7939:     }
                   7940:     $result .= '>' 
1.1064    raeburn  7941:         .$inhibitprint
1.414     albertel 7942: 	.$head_extra;
1.1137    raeburn  7943:     if ($env{'browser.mobile'}) {
                   7944:         $result .= '
                   7945: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7946: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7947:     }
1.962     droeschl 7948:     return $result.'</head>';
1.306     albertel 7949: }
                   7950: 
                   7951: =pod
                   7952: 
1.340     albertel 7953: =item * &font_settings()
                   7954: 
                   7955: Returns neccessary <meta> to set the proper encoding
                   7956: 
1.1160    raeburn  7957: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7958: 
                   7959: =cut
                   7960: 
                   7961: sub font_settings {
1.1160    raeburn  7962:     my ($args) = @_;
1.340     albertel 7963:     my $headerstring='';
1.1160    raeburn  7964:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7965:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  7966:         $headerstring.=
                   7967:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7968:         if (!$args->{'frameset'}) {
                   7969: 	    $headerstring.= ' /';
                   7970:         }
                   7971: 	$headerstring .= '>'."\n";
1.340     albertel 7972:     }
                   7973:     return $headerstring;
                   7974: }
                   7975: 
1.341     albertel 7976: =pod
                   7977: 
1.1064    raeburn  7978: =item * &print_suppression()
                   7979: 
                   7980: In course context returns css which causes the body to be blank when media="print",
                   7981: if printout generation is unavailable for the current resource.
                   7982: 
                   7983: This could be because:
                   7984: 
                   7985: (a) printstartdate is in the future
                   7986: 
                   7987: (b) printenddate is in the past
                   7988: 
                   7989: (c) there is an active exam block with "printout"
                   7990: functionality blocked
                   7991: 
                   7992: Users with pav, pfo or evb privileges are exempt.
                   7993: 
                   7994: Inputs: none
                   7995: 
                   7996: =cut
                   7997: 
                   7998: 
                   7999: sub print_suppression {
                   8000:     my $noprint;
                   8001:     if ($env{'request.course.id'}) {
                   8002:         my $scope = $env{'request.course.id'};
                   8003:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8004:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8005:             return;
                   8006:         }
                   8007:         if ($env{'request.course.sec'} ne '') {
                   8008:             $scope .= "/$env{'request.course.sec'}";
                   8009:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8010:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8011:                 return;
1.1064    raeburn  8012:             }
                   8013:         }
                   8014:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8015:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8016:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8017:         if ($blocked) {
                   8018:             my $checkrole = "cm./$cdom/$cnum";
                   8019:             if ($env{'request.course.sec'} ne '') {
                   8020:                 $checkrole .= "/$env{'request.course.sec'}";
                   8021:             }
                   8022:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8023:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8024:                 $noprint = 1;
                   8025:             }
                   8026:         }
                   8027:         unless ($noprint) {
                   8028:             my $symb = &Apache::lonnet::symbread();
                   8029:             if ($symb ne '') {
                   8030:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8031:                 if (ref($navmap)) {
                   8032:                     my $res = $navmap->getBySymb($symb);
                   8033:                     if (ref($res)) {
                   8034:                         if (!$res->resprintable()) {
                   8035:                             $noprint = 1;
                   8036:                         }
                   8037:                     }
                   8038:                 }
                   8039:             }
                   8040:         }
                   8041:         if ($noprint) {
                   8042:             return <<"ENDSTYLE";
                   8043: <style type="text/css" media="print">
                   8044:     body { display:none }
                   8045: </style>
                   8046: ENDSTYLE
                   8047:         }
                   8048:     }
                   8049:     return;
                   8050: }
                   8051: 
                   8052: =pod
                   8053: 
1.341     albertel 8054: =item * &xml_begin()
                   8055: 
                   8056: Returns the needed doctype and <html>
                   8057: 
                   8058: Inputs: none
                   8059: 
                   8060: =cut
                   8061: 
                   8062: sub xml_begin {
1.1168    raeburn  8063:     my ($is_frameset) = @_;
1.341     albertel 8064:     my $output='';
                   8065: 
                   8066:     if ($env{'browser.mathml'}) {
                   8067: 	$output='<?xml version="1.0"?>'
                   8068:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8069: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8070:             
                   8071: #	    .'<!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">] >'
                   8072: 	    .'<!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">'
                   8073:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8074: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8075:     } elsif ($is_frameset) {
                   8076:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8077:                 '<html>'."\n";
1.341     albertel 8078:     } else {
1.1168    raeburn  8079: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8080:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8081:     }
                   8082:     return $output;
                   8083: }
1.340     albertel 8084: 
                   8085: =pod
                   8086: 
1.306     albertel 8087: =item * &start_page()
                   8088: 
                   8089: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8090: 
1.648     raeburn  8091: Inputs:
                   8092: 
                   8093: =over 4
                   8094: 
                   8095: $title - optional title for the page
                   8096: 
                   8097: $head_extra - optional extra HTML to incude inside the <head>
                   8098: 
                   8099: $args - additional optional args supported are:
                   8100: 
                   8101: =over 8
                   8102: 
                   8103:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8104:                                     arg on
1.814     bisitz   8105:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8106:              add_entries    -> additional attributes to add to the  <body>
                   8107:              domain         -> force to color decorate a page for a 
1.317     albertel 8108:                                     specific domain
1.648     raeburn  8109:              function       -> force usage of a specific rolish color
1.317     albertel 8110:                                     scheme
1.648     raeburn  8111:              redirect       -> see &headtag()
                   8112:              bgcolor        -> override the default page bg color
                   8113:              js_ready       -> return a string ready for being used in 
1.317     albertel 8114:                                     a javascript writeln
1.648     raeburn  8115:              html_encode    -> return a string ready for being used in 
1.320     albertel 8116:                                     a html attribute
1.648     raeburn  8117:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8118:                                     $forcereg arg
1.648     raeburn  8119:              frameset       -> if true will start with a <frameset>
1.330     albertel 8120:                                     rather than <body>
1.648     raeburn  8121:              skip_phases    -> hash ref of 
1.338     albertel 8122:                                     head -> skip the <html><head> generation
                   8123:                                     body -> skip all <body> generation
1.648     raeburn  8124:              no_auto_mt_title -> prevent &mt()ing the title arg
                   8125:              inherit_jsmath -> when creating popup window in a page,
                   8126:                                     should it have jsmath forced on by the
                   8127:                                     current page
1.867     kalberla 8128:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8129:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  8130:              group          -> includes the current group, if page is for a 
                   8131:                                specific group  
1.361     albertel 8132: 
1.648     raeburn  8133: =back
1.460     albertel 8134: 
1.648     raeburn  8135: =back
1.562     albertel 8136: 
1.306     albertel 8137: =cut
                   8138: 
                   8139: sub start_page {
1.309     albertel 8140:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8141:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8142: 
1.315     albertel 8143:     $env{'internal.start_page'}++;
1.1096    raeburn  8144:     my ($result,@advtools);
1.964     droeschl 8145: 
1.338     albertel 8146:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8147:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8148:     }
                   8149:     
                   8150:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8151: 	if ($args->{'frameset'}) {
                   8152: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8153: 						$args->{'add_entries'});
                   8154: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8155:         } else {
                   8156:             $result .=
                   8157:                 &bodytag($title, 
                   8158:                          $args->{'function'},       $args->{'add_entries'},
                   8159:                          $args->{'only_body'},      $args->{'domain'},
                   8160:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8161:                          $args->{'bgcolor'},        $args,
                   8162:                          \@advtools);
1.831     bisitz   8163:         }
1.330     albertel 8164:     }
1.338     albertel 8165: 
1.315     albertel 8166:     if ($args->{'js_ready'}) {
1.713     kaisler  8167: 		$result = &js_ready($result);
1.315     albertel 8168:     }
1.320     albertel 8169:     if ($args->{'html_encode'}) {
1.713     kaisler  8170: 		$result = &html_encode($result);
                   8171:     }
                   8172: 
1.813     bisitz   8173:     # Preparation for new and consistent functionlist at top of screen
                   8174:     # if ($args->{'functionlist'}) {
                   8175:     #            $result .= &build_functionlist();
                   8176:     #}
                   8177: 
1.964     droeschl 8178:     # Don't add anything more if only_body wanted or in const space
                   8179:     return $result if    $args->{'only_body'} 
                   8180:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8181: 
                   8182:     #Breadcrumbs
1.758     kaisler  8183:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8184: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8185: 		#if any br links exists, add them to the breadcrumbs
                   8186: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8187: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8188: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8189: 			}
                   8190: 		}
1.1096    raeburn  8191:                 # if @advtools array contains items add then to the breadcrumbs
                   8192:                 if (@advtools > 0) {
                   8193:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8194:                 }
1.758     kaisler  8195: 
                   8196: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8197: 		if(exists($args->{'bread_crumbs_component'})){
                   8198: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   8199: 		}else{
                   8200: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   8201: 		}
1.320     albertel 8202:     }
1.315     albertel 8203:     return $result;
1.306     albertel 8204: }
                   8205: 
                   8206: sub end_page {
1.315     albertel 8207:     my ($args) = @_;
                   8208:     $env{'internal.end_page'}++;
1.330     albertel 8209:     my $result;
1.335     albertel 8210:     if ($args->{'discussion'}) {
                   8211: 	my ($target,$parser);
                   8212: 	if (ref($args->{'discussion'})) {
                   8213: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8214: 				$args->{'discussion'}{'parser'});
                   8215: 	}
                   8216: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8217:     }
1.330     albertel 8218:     if ($args->{'frameset'}) {
                   8219: 	$result .= '</frameset>';
                   8220:     } else {
1.635     raeburn  8221: 	$result .= &endbodytag($args);
1.330     albertel 8222:     }
1.1080    raeburn  8223:     unless ($args->{'notbody'}) {
                   8224:         $result .= "\n</html>";
                   8225:     }
1.330     albertel 8226: 
1.315     albertel 8227:     if ($args->{'js_ready'}) {
1.317     albertel 8228: 	$result = &js_ready($result);
1.315     albertel 8229:     }
1.335     albertel 8230: 
1.320     albertel 8231:     if ($args->{'html_encode'}) {
                   8232: 	$result = &html_encode($result);
                   8233:     }
1.335     albertel 8234: 
1.315     albertel 8235:     return $result;
                   8236: }
                   8237: 
1.1034    www      8238: sub wishlist_window {
                   8239:     return(<<'ENDWISHLIST');
1.1046    raeburn  8240: <script type="text/javascript">
1.1034    www      8241: // <![CDATA[
                   8242: // <!-- BEGIN LON-CAPA Internal
                   8243: function set_wishlistlink(title, path) {
                   8244:     if (!title) {
                   8245:         title = document.title;
                   8246:         title = title.replace(/^LON-CAPA /,'');
                   8247:     }
1.1175    raeburn  8248:     title = encodeURIComponent(title);
1.1203    raeburn  8249:     title = title.replace("'","\\\'");
1.1034    www      8250:     if (!path) {
                   8251:         path = location.pathname;
                   8252:     }
1.1175    raeburn  8253:     path = encodeURIComponent(path);
1.1203    raeburn  8254:     path = path.replace("'","\\\'");
1.1034    www      8255:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8256:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8257: }
                   8258: // END LON-CAPA Internal -->
                   8259: // ]]>
                   8260: </script>
                   8261: ENDWISHLIST
                   8262: }
                   8263: 
1.1030    www      8264: sub modal_window {
                   8265:     return(<<'ENDMODAL');
1.1046    raeburn  8266: <script type="text/javascript">
1.1030    www      8267: // <![CDATA[
                   8268: // <!-- BEGIN LON-CAPA Internal
                   8269: var modalWindow = {
                   8270: 	parent:"body",
                   8271: 	windowId:null,
                   8272: 	content:null,
                   8273: 	width:null,
                   8274: 	height:null,
                   8275: 	close:function()
                   8276: 	{
                   8277: 	        $(".LCmodal-window").remove();
                   8278: 	        $(".LCmodal-overlay").remove();
                   8279: 	},
                   8280: 	open:function()
                   8281: 	{
                   8282: 		var modal = "";
                   8283: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8284: 		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;\">";
                   8285: 		modal += this.content;
                   8286: 		modal += "</div>";	
                   8287: 
                   8288: 		$(this.parent).append(modal);
                   8289: 
                   8290: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8291: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8292: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8293: 	}
                   8294: };
1.1140    raeburn  8295: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8296: 	{
1.1203    raeburn  8297:                 source = source.replace("'","&#39;");
1.1030    www      8298: 		modalWindow.windowId = "myModal";
                   8299: 		modalWindow.width = width;
                   8300: 		modalWindow.height = height;
1.1196    raeburn  8301: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8302: 		modalWindow.open();
1.1208    raeburn  8303: 	};
1.1030    www      8304: // END LON-CAPA Internal -->
                   8305: // ]]>
                   8306: </script>
                   8307: ENDMODAL
                   8308: }
                   8309: 
                   8310: sub modal_link {
1.1140    raeburn  8311:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8312:     unless ($width) { $width=480; }
                   8313:     unless ($height) { $height=400; }
1.1031    www      8314:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8315:     unless ($transparency) { $transparency='true'; }
                   8316: 
1.1074    raeburn  8317:     my $target_attr;
                   8318:     if (defined($target)) {
                   8319:         $target_attr = 'target="'.$target.'"';
                   8320:     }
                   8321:     return <<"ENDLINK";
1.1140    raeburn  8322: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8323:            $linktext</a>
                   8324: ENDLINK
1.1030    www      8325: }
                   8326: 
1.1032    www      8327: sub modal_adhoc_script {
                   8328:     my ($funcname,$width,$height,$content)=@_;
                   8329:     return (<<ENDADHOC);
1.1046    raeburn  8330: <script type="text/javascript">
1.1032    www      8331: // <![CDATA[
                   8332:         var $funcname = function()
                   8333:         {
                   8334:                 modalWindow.windowId = "myModal";
                   8335:                 modalWindow.width = $width;
                   8336:                 modalWindow.height = $height;
                   8337:                 modalWindow.content = '$content';
                   8338:                 modalWindow.open();
                   8339:         };  
                   8340: // ]]>
                   8341: </script>
                   8342: ENDADHOC
                   8343: }
                   8344: 
1.1041    www      8345: sub modal_adhoc_inner {
                   8346:     my ($funcname,$width,$height,$content)=@_;
                   8347:     my $innerwidth=$width-20;
                   8348:     $content=&js_ready(
1.1140    raeburn  8349:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8350:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8351:                  $content.
1.1041    www      8352:                  &end_scrollbox().
1.1140    raeburn  8353:                  &end_page()
1.1041    www      8354:              );
                   8355:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8356: }
                   8357: 
                   8358: sub modal_adhoc_window {
                   8359:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8360:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8361:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8362: }
                   8363: 
                   8364: sub modal_adhoc_launch {
                   8365:     my ($funcname,$width,$height,$content)=@_;
                   8366:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8367: <script type="text/javascript">
                   8368: // <![CDATA[
                   8369: $funcname();
                   8370: // ]]>
                   8371: </script>
                   8372: ENDLAUNCH
                   8373: }
                   8374: 
                   8375: sub modal_adhoc_close {
                   8376:     return (<<ENDCLOSE);
                   8377: <script type="text/javascript">
                   8378: // <![CDATA[
                   8379: modalWindow.close();
                   8380: // ]]>
                   8381: </script>
                   8382: ENDCLOSE
                   8383: }
                   8384: 
1.1038    www      8385: sub togglebox_script {
                   8386:    return(<<ENDTOGGLE);
                   8387: <script type="text/javascript"> 
                   8388: // <![CDATA[
                   8389: function LCtoggleDisplay(id,hidetext,showtext) {
                   8390:    link = document.getElementById(id + "link").childNodes[0];
                   8391:    with (document.getElementById(id).style) {
                   8392:       if (display == "none" ) {
                   8393:           display = "inline";
                   8394:           link.nodeValue = hidetext;
                   8395:         } else {
                   8396:           display = "none";
                   8397:           link.nodeValue = showtext;
                   8398:        }
                   8399:    }
                   8400: }
                   8401: // ]]>
                   8402: </script>
                   8403: ENDTOGGLE
                   8404: }
                   8405: 
1.1039    www      8406: sub start_togglebox {
                   8407:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8408:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8409:     unless ($showtext) { $showtext=&mt('show'); }
                   8410:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8411:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8412:     return &start_data_table().
                   8413:            &start_data_table_header_row().
                   8414:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8415:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8416:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8417:            &end_data_table_header_row().
                   8418:            '<tr id="'.$id.'" style="display:none""><td>';
                   8419: }
                   8420: 
                   8421: sub end_togglebox {
                   8422:     return '</td></tr>'.&end_data_table();
                   8423: }
                   8424: 
1.1041    www      8425: sub LCprogressbar_script {
1.1045    www      8426:    my ($id)=@_;
1.1041    www      8427:    return(<<ENDPROGRESS);
                   8428: <script type="text/javascript">
                   8429: // <![CDATA[
1.1045    www      8430: \$('#progressbar$id').progressbar({
1.1041    www      8431:   value: 0,
                   8432:   change: function(event, ui) {
                   8433:     var newVal = \$(this).progressbar('option', 'value');
                   8434:     \$('.pblabel', this).text(LCprogressTxt);
                   8435:   }
                   8436: });
                   8437: // ]]>
                   8438: </script>
                   8439: ENDPROGRESS
                   8440: }
                   8441: 
                   8442: sub LCprogressbarUpdate_script {
                   8443:    return(<<ENDPROGRESSUPDATE);
                   8444: <style type="text/css">
                   8445: .ui-progressbar { position:relative; }
                   8446: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8447: </style>
                   8448: <script type="text/javascript">
                   8449: // <![CDATA[
1.1045    www      8450: var LCprogressTxt='---';
                   8451: 
                   8452: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8453:    LCprogressTxt=progresstext;
1.1045    www      8454:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8455: }
                   8456: // ]]>
                   8457: </script>
                   8458: ENDPROGRESSUPDATE
                   8459: }
                   8460: 
1.1042    www      8461: my $LClastpercent;
1.1045    www      8462: my $LCidcnt;
                   8463: my $LCcurrentid;
1.1042    www      8464: 
1.1041    www      8465: sub LCprogressbar {
1.1042    www      8466:     my ($r)=(@_);
                   8467:     $LClastpercent=0;
1.1045    www      8468:     $LCidcnt++;
                   8469:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8470:     my $starting=&mt('Starting');
                   8471:     my $content=(<<ENDPROGBAR);
1.1045    www      8472:   <div id="progressbar$LCcurrentid">
1.1041    www      8473:     <span class="pblabel">$starting</span>
                   8474:   </div>
                   8475: ENDPROGBAR
1.1045    www      8476:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8477: }
                   8478: 
                   8479: sub LCprogressbarUpdate {
1.1042    www      8480:     my ($r,$val,$text)=@_;
                   8481:     unless ($val) { 
                   8482:        if ($LClastpercent) {
                   8483:            $val=$LClastpercent;
                   8484:        } else {
                   8485:            $val=0;
                   8486:        }
                   8487:     }
1.1041    www      8488:     if ($val<0) { $val=0; }
                   8489:     if ($val>100) { $val=0; }
1.1042    www      8490:     $LClastpercent=$val;
1.1041    www      8491:     unless ($text) { $text=$val.'%'; }
                   8492:     $text=&js_ready($text);
1.1044    www      8493:     &r_print($r,<<ENDUPDATE);
1.1041    www      8494: <script type="text/javascript">
                   8495: // <![CDATA[
1.1045    www      8496: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8497: // ]]>
                   8498: </script>
                   8499: ENDUPDATE
1.1035    www      8500: }
                   8501: 
1.1042    www      8502: sub LCprogressbarClose {
                   8503:     my ($r)=@_;
                   8504:     $LClastpercent=0;
1.1044    www      8505:     &r_print($r,<<ENDCLOSE);
1.1042    www      8506: <script type="text/javascript">
                   8507: // <![CDATA[
1.1045    www      8508: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8509: // ]]>
                   8510: </script>
                   8511: ENDCLOSE
1.1044    www      8512: }
                   8513: 
                   8514: sub r_print {
                   8515:     my ($r,$to_print)=@_;
                   8516:     if ($r) {
                   8517:       $r->print($to_print);
                   8518:       $r->rflush();
                   8519:     } else {
                   8520:       print($to_print);
                   8521:     }
1.1042    www      8522: }
                   8523: 
1.320     albertel 8524: sub html_encode {
                   8525:     my ($result) = @_;
                   8526: 
1.322     albertel 8527:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8528:     
                   8529:     return $result;
                   8530: }
1.1044    www      8531: 
1.317     albertel 8532: sub js_ready {
                   8533:     my ($result) = @_;
                   8534: 
1.323     albertel 8535:     $result =~ s/[\n\r]/ /xmsg;
                   8536:     $result =~ s/\\/\\\\/xmsg;
                   8537:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8538:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8539:     
                   8540:     return $result;
                   8541: }
                   8542: 
1.315     albertel 8543: sub validate_page {
                   8544:     if (  exists($env{'internal.start_page'})
1.316     albertel 8545: 	  &&     $env{'internal.start_page'} > 1) {
                   8546: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8547: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8548: 				 $ENV{'request.filename'});
1.315     albertel 8549:     }
                   8550:     if (  exists($env{'internal.end_page'})
1.316     albertel 8551: 	  &&     $env{'internal.end_page'} > 1) {
                   8552: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8553: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8554: 				 $env{'request.filename'});
1.315     albertel 8555:     }
                   8556:     if (     exists($env{'internal.start_page'})
                   8557: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8558: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8559: 				 $env{'request.filename'});
1.315     albertel 8560:     }
                   8561:     if (   ! exists($env{'internal.start_page'})
                   8562: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8563: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8564: 				 $env{'request.filename'});
1.315     albertel 8565:     }
1.306     albertel 8566: }
1.315     albertel 8567: 
1.996     www      8568: 
                   8569: sub start_scrollbox {
1.1140    raeburn  8570:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8571:     unless ($outerwidth) { $outerwidth='520px'; }
                   8572:     unless ($width) { $width='500px'; }
                   8573:     unless ($height) { $height='200px'; }
1.1075    raeburn  8574:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8575:     if ($id ne '') {
1.1140    raeburn  8576:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  8577:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8578:     }
1.1075    raeburn  8579:     if ($bgcolor ne '') {
                   8580:         $tdcol = "background-color: $bgcolor;";
                   8581:     }
1.1137    raeburn  8582:     my $nicescroll_js;
                   8583:     if ($env{'browser.mobile'}) {
1.1140    raeburn  8584:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8585:     }
                   8586:     return <<"END";
                   8587: $nicescroll_js
                   8588: 
                   8589: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   8590: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   8591: END
                   8592: }
                   8593: 
                   8594: sub end_scrollbox {
                   8595:     return '</div></td></tr></table>';
                   8596: }
                   8597: 
                   8598: sub nicescroll_javascript {
                   8599:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8600:     my %options;
                   8601:     if (ref($cursor) eq 'HASH') {
                   8602:         %options = %{$cursor};
                   8603:     }
                   8604:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8605:         $options{'railalign'} = 'left';
                   8606:     }
                   8607:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8608:         my $function  = &get_users_function();
                   8609:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  8610:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  8611:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  8612:         }
1.1140    raeburn  8613:     }
                   8614:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8615:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  8616:             $options{'cursoropacity'}='1.0';
                   8617:         }
1.1140    raeburn  8618:     } else {
                   8619:         $options{'cursoropacity'}='1.0';
                   8620:     }
                   8621:     if ($options{'cursorfixedheight'} eq 'none') {
                   8622:         delete($options{'cursorfixedheight'});
                   8623:     } else {
                   8624:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8625:     }
                   8626:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8627:         delete($options{'railoffset'});
                   8628:     }
                   8629:     my @niceoptions;
                   8630:     while (my($key,$value) = each(%options)) {
                   8631:         if ($value =~ /^\{.+\}$/) {
                   8632:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  8633:         } else {
1.1140    raeburn  8634:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  8635:         }
1.1140    raeburn  8636:     }
                   8637:     my $nicescroll_js = '
1.1137    raeburn  8638: $(document).ready(
1.1140    raeburn  8639:       function() {
                   8640:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8641:       }
1.1137    raeburn  8642: );
                   8643: ';
1.1140    raeburn  8644:     if ($framecheck) {
                   8645:         $nicescroll_js .= '
                   8646: function expand_div(caller) {
                   8647:     if (top === self) {
                   8648:         document.getElementById("'.$id.'").style.width = "auto";
                   8649:         document.getElementById("'.$id.'").style.height = "auto";
                   8650:     } else {
                   8651:         try {
                   8652:             if (parent.frames) {
                   8653:                 if (parent.frames.length > 1) {
                   8654:                     var framesrc = parent.frames[1].location.href;
                   8655:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8656:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8657:                         document.getElementById("'.$id.'").style.width = "auto";
                   8658:                         document.getElementById("'.$id.'").style.height = "auto";
                   8659:                     }
                   8660:                 }
                   8661:             }
                   8662:         } catch (e) {
                   8663:             return;
                   8664:         }
1.1137    raeburn  8665:     }
1.1140    raeburn  8666:     return;
1.996     www      8667: }
1.1140    raeburn  8668: ';
                   8669:     }
                   8670:     if ($needjsready) {
                   8671:         $nicescroll_js = '
                   8672: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8673:     } else {
                   8674:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8675:     }
                   8676:     return $nicescroll_js;
1.996     www      8677: }
                   8678: 
1.318     albertel 8679: sub simple_error_page {
1.1150    bisitz   8680:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  8681:     if (ref($args) eq 'HASH') {
                   8682:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8683:     } else {
                   8684:         $msg = &mt($msg);
                   8685:     }
1.1150    bisitz   8686: 
1.318     albertel 8687:     my $page =
                   8688: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   8689: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8690: 	&Apache::loncommon::end_page();
                   8691:     if (ref($r)) {
                   8692: 	$r->print($page);
1.327     albertel 8693: 	return;
1.318     albertel 8694:     }
                   8695:     return $page;
                   8696: }
1.347     albertel 8697: 
                   8698: {
1.610     albertel 8699:     my @row_count;
1.961     onken    8700: 
                   8701:     sub start_data_table_count {
                   8702:         unshift(@row_count, 0);
                   8703:         return;
                   8704:     }
                   8705: 
                   8706:     sub end_data_table_count {
                   8707:         shift(@row_count);
                   8708:         return;
                   8709:     }
                   8710: 
1.347     albertel 8711:     sub start_data_table {
1.1018    raeburn  8712: 	my ($add_class,$id) = @_;
1.422     albertel 8713: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8714:         my $table_id;
                   8715:         if (defined($id)) {
                   8716:             $table_id = ' id="'.$id.'"';
                   8717:         }
1.961     onken    8718: 	&start_data_table_count();
1.1018    raeburn  8719: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8720:     }
                   8721: 
                   8722:     sub end_data_table {
1.961     onken    8723: 	&end_data_table_count();
1.389     albertel 8724: 	return '</table>'."\n";;
1.347     albertel 8725:     }
                   8726: 
                   8727:     sub start_data_table_row {
1.974     wenzelju 8728: 	my ($add_class, $id) = @_;
1.610     albertel 8729: 	$row_count[0]++;
                   8730: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8731: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8732:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8733:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8734:     }
1.471     banghart 8735:     
                   8736:     sub continue_data_table_row {
1.974     wenzelju 8737: 	my ($add_class, $id) = @_;
1.610     albertel 8738: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8739: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8740:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8741:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8742:     }
1.347     albertel 8743: 
                   8744:     sub end_data_table_row {
1.389     albertel 8745: 	return '</tr>'."\n";;
1.347     albertel 8746:     }
1.367     www      8747: 
1.421     albertel 8748:     sub start_data_table_empty_row {
1.707     bisitz   8749: #	$row_count[0]++;
1.421     albertel 8750: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8751:     }
                   8752: 
                   8753:     sub end_data_table_empty_row {
                   8754: 	return '</tr>'."\n";;
                   8755:     }
                   8756: 
1.367     www      8757:     sub start_data_table_header_row {
1.389     albertel 8758: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8759:     }
                   8760: 
                   8761:     sub end_data_table_header_row {
1.389     albertel 8762: 	return '</tr>'."\n";;
1.367     www      8763:     }
1.890     droeschl 8764: 
                   8765:     sub data_table_caption {
                   8766:         my $caption = shift;
                   8767:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8768:     }
1.347     albertel 8769: }
                   8770: 
1.548     albertel 8771: =pod
                   8772: 
                   8773: =item * &inhibit_menu_check($arg)
                   8774: 
                   8775: Checks for a inhibitmenu state and generates output to preserve it
                   8776: 
                   8777: Inputs:         $arg - can be any of
                   8778:                      - undef - in which case the return value is a string 
                   8779:                                to add  into arguments list of a uri
                   8780:                      - 'input' - in which case the return value is a HTML
                   8781:                                  <form> <input> field of type hidden to
                   8782:                                  preserve the value
                   8783:                      - a url - in which case the return value is the url with
                   8784:                                the neccesary cgi args added to preserve the
                   8785:                                inhibitmenu state
                   8786:                      - a ref to a url - no return value, but the string is
                   8787:                                         updated to include the neccessary cgi
                   8788:                                         args to preserve the inhibitmenu state
                   8789: 
                   8790: =cut
                   8791: 
                   8792: sub inhibit_menu_check {
                   8793:     my ($arg) = @_;
                   8794:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8795:     if ($arg eq 'input') {
                   8796: 	if ($env{'form.inhibitmenu'}) {
                   8797: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8798: 	} else {
                   8799: 	    return
                   8800: 	}
                   8801:     }
                   8802:     if ($env{'form.inhibitmenu'}) {
                   8803: 	if (ref($arg)) {
                   8804: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8805: 	} elsif ($arg eq '') {
                   8806: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8807: 	} else {
                   8808: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8809: 	}
                   8810:     }
                   8811:     if (!ref($arg)) {
                   8812: 	return $arg;
                   8813:     }
                   8814: }
                   8815: 
1.251     albertel 8816: ###############################################
1.182     matthew  8817: 
                   8818: =pod
                   8819: 
1.549     albertel 8820: =back
                   8821: 
                   8822: =head1 User Information Routines
                   8823: 
                   8824: =over 4
                   8825: 
1.405     albertel 8826: =item * &get_users_function()
1.182     matthew  8827: 
                   8828: Used by &bodytag to determine the current users primary role.
                   8829: Returns either 'student','coordinator','admin', or 'author'.
                   8830: 
                   8831: =cut
                   8832: 
                   8833: ###############################################
                   8834: sub get_users_function {
1.815     tempelho 8835:     my $function = 'norole';
1.818     tempelho 8836:     if ($env{'request.role'}=~/^(st)/) {
                   8837:         $function='student';
                   8838:     }
1.907     raeburn  8839:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8840:         $function='coordinator';
                   8841:     }
1.258     albertel 8842:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8843:         $function='admin';
                   8844:     }
1.826     bisitz   8845:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8846:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8847:         $function='author';
                   8848:     }
                   8849:     return $function;
1.54      www      8850: }
1.99      www      8851: 
                   8852: ###############################################
                   8853: 
1.233     raeburn  8854: =pod
                   8855: 
1.821     raeburn  8856: =item * &show_course()
                   8857: 
                   8858: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8859: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8860: 
                   8861: Inputs:
                   8862: None
                   8863: 
                   8864: Outputs:
                   8865: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8866: 
                   8867: =cut
                   8868: 
                   8869: ###############################################
                   8870: sub show_course {
                   8871:     my $course = !$env{'user.adv'};
                   8872:     if (!$env{'user.adv'}) {
                   8873:         foreach my $env (keys(%env)) {
                   8874:             next if ($env !~ m/^user\.priv\./);
                   8875:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8876:                 $course = 0;
                   8877:                 last;
                   8878:             }
                   8879:         }
                   8880:     }
                   8881:     return $course;
                   8882: }
                   8883: 
                   8884: ###############################################
                   8885: 
                   8886: =pod
                   8887: 
1.542     raeburn  8888: =item * &check_user_status()
1.274     raeburn  8889: 
                   8890: Determines current status of supplied role for a
                   8891: specific user. Roles can be active, previous or future.
                   8892: 
                   8893: Inputs: 
                   8894: user's domain, user's username, course's domain,
1.375     raeburn  8895: course's number, optional section ID.
1.274     raeburn  8896: 
                   8897: Outputs:
                   8898: role status: active, previous or future. 
                   8899: 
                   8900: =cut
                   8901: 
                   8902: sub check_user_status {
1.412     raeburn  8903:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8904:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  8905:     my @uroles = keys(%userinfo);
1.274     raeburn  8906:     my $srchstr;
                   8907:     my $active_chk = 'none';
1.412     raeburn  8908:     my $now = time;
1.274     raeburn  8909:     if (@uroles > 0) {
1.908     raeburn  8910:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8911:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8912:         } else {
1.412     raeburn  8913:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8914:         }
                   8915:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8916:             my $role_end = 0;
                   8917:             my $role_start = 0;
                   8918:             $active_chk = 'active';
1.412     raeburn  8919:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8920:                 $role_end = $1;
                   8921:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8922:                     $role_start = $1;
1.274     raeburn  8923:                 }
                   8924:             }
                   8925:             if ($role_start > 0) {
1.412     raeburn  8926:                 if ($now < $role_start) {
1.274     raeburn  8927:                     $active_chk = 'future';
                   8928:                 }
                   8929:             }
                   8930:             if ($role_end > 0) {
1.412     raeburn  8931:                 if ($now > $role_end) {
1.274     raeburn  8932:                     $active_chk = 'previous';
                   8933:                 }
                   8934:             }
                   8935:         }
                   8936:     }
                   8937:     return $active_chk;
                   8938: }
                   8939: 
                   8940: ###############################################
                   8941: 
                   8942: =pod
                   8943: 
1.405     albertel 8944: =item * &get_sections()
1.233     raeburn  8945: 
                   8946: Determines all the sections for a course including
                   8947: sections with students and sections containing other roles.
1.419     raeburn  8948: Incoming parameters: 
                   8949: 
                   8950: 1. domain
                   8951: 2. course number 
                   8952: 3. reference to array containing roles for which sections should 
                   8953: be gathered (optional).
                   8954: 4. reference to array containing status types for which sections 
                   8955: should be gathered (optional).
                   8956: 
                   8957: If the third argument is undefined, sections are gathered for any role. 
                   8958: If the fourth argument is undefined, sections are gathered for any status.
                   8959: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8960:  
1.374     raeburn  8961: Returns section hash (keys are section IDs, values are
                   8962: number of users in each section), subject to the
1.419     raeburn  8963: optional roles filter, optional status filter 
1.233     raeburn  8964: 
                   8965: =cut
                   8966: 
                   8967: ###############################################
                   8968: sub get_sections {
1.419     raeburn  8969:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8970:     if (!defined($cdom) || !defined($cnum)) {
                   8971:         my $cid =  $env{'request.course.id'};
                   8972: 
                   8973: 	return if (!defined($cid));
                   8974: 
                   8975:         $cdom = $env{'course.'.$cid.'.domain'};
                   8976:         $cnum = $env{'course.'.$cid.'.num'};
                   8977:     }
                   8978: 
                   8979:     my %sectioncount;
1.419     raeburn  8980:     my $now = time;
1.240     albertel 8981: 
1.1118    raeburn  8982:     my $check_students = 1;
                   8983:     my $only_students = 0;
                   8984:     if (ref($possible_roles) eq 'ARRAY') {
                   8985:         if (grep(/^st$/,@{$possible_roles})) {
                   8986:             if (@{$possible_roles} == 1) {
                   8987:                 $only_students = 1;
                   8988:             }
                   8989:         } else {
                   8990:             $check_students = 0;
                   8991:         }
                   8992:     }
                   8993: 
                   8994:     if ($check_students) { 
1.276     albertel 8995: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8996: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8997: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8998:         my $start_index = &Apache::loncoursedata::CL_START();
                   8999:         my $end_index = &Apache::loncoursedata::CL_END();
                   9000:         my $status;
1.366     albertel 9001: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9002: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9003: 				                     $data->[$status_index],
                   9004:                                                      $data->[$start_index],
                   9005:                                                      $data->[$end_index]);
                   9006:             if ($stu_status eq 'Active') {
                   9007:                 $status = 'active';
                   9008:             } elsif ($end < $now) {
                   9009:                 $status = 'previous';
                   9010:             } elsif ($start > $now) {
                   9011:                 $status = 'future';
                   9012:             } 
                   9013: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9014:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9015:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9016: 		    $sectioncount{$section}++;
                   9017:                 }
1.240     albertel 9018: 	    }
                   9019: 	}
                   9020:     }
1.1118    raeburn  9021:     if ($only_students) {
                   9022:         return %sectioncount;
                   9023:     }
1.240     albertel 9024:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9025:     foreach my $user (sort(keys(%courseroles))) {
                   9026: 	if ($user !~ /^(\w{2})/) { next; }
                   9027: 	my ($role) = ($user =~ /^(\w{2})/);
                   9028: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9029: 	my ($section,$status);
1.240     albertel 9030: 	if ($role eq 'cr' &&
                   9031: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9032: 	    $section=$1;
                   9033: 	}
                   9034: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9035: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9036:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9037:         if ($end == -1 && $start == -1) {
                   9038:             next; #deleted role
                   9039:         }
                   9040:         if (!defined($possible_status)) { 
                   9041:             $sectioncount{$section}++;
                   9042:         } else {
                   9043:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9044:                 $status = 'active';
                   9045:             } elsif ($end < $now) {
                   9046:                 $status = 'future';
                   9047:             } elsif ($start > $now) {
                   9048:                 $status = 'previous';
                   9049:             }
                   9050:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9051:                 $sectioncount{$section}++;
                   9052:             }
                   9053:         }
1.233     raeburn  9054:     }
1.366     albertel 9055:     return %sectioncount;
1.233     raeburn  9056: }
                   9057: 
1.274     raeburn  9058: ###############################################
1.294     raeburn  9059: 
                   9060: =pod
1.405     albertel 9061: 
                   9062: =item * &get_course_users()
                   9063: 
1.275     raeburn  9064: Retrieves usernames:domains for users in the specified course
                   9065: with specific role(s), and access status. 
                   9066: 
                   9067: Incoming parameters:
1.277     albertel 9068: 1. course domain
                   9069: 2. course number
                   9070: 3. access status: users must have - either active, 
1.275     raeburn  9071: previous, future, or all.
1.277     albertel 9072: 4. reference to array of permissible roles
1.288     raeburn  9073: 5. reference to array of section restrictions (optional)
                   9074: 6. reference to results object (hash of hashes).
                   9075: 7. reference to optional userdata hash
1.609     raeburn  9076: 8. reference to optional statushash
1.630     raeburn  9077: 9. flag if privileged users (except those set to unhide in
                   9078:    course settings) should be excluded    
1.609     raeburn  9079: Keys of top level results hash are roles.
1.275     raeburn  9080: Keys of inner hashes are username:domain, with 
                   9081: values set to access type.
1.288     raeburn  9082: Optional userdata hash returns an array with arguments in the 
                   9083: same order as loncoursedata::get_classlist() for student data.
                   9084: 
1.609     raeburn  9085: Optional statushash returns
                   9086: 
1.288     raeburn  9087: Entries for end, start, section and status are blank because
                   9088: of the possibility of multiple values for non-student roles.
                   9089: 
1.275     raeburn  9090: =cut
1.405     albertel 9091: 
1.275     raeburn  9092: ###############################################
1.405     albertel 9093: 
1.275     raeburn  9094: sub get_course_users {
1.630     raeburn  9095:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9096:     my %idx = ();
1.419     raeburn  9097:     my %seclists;
1.288     raeburn  9098: 
                   9099:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9100:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9101:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9102:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9103:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9104:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9105:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9106:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9107: 
1.290     albertel 9108:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9109:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9110:         my $now = time;
1.277     albertel 9111:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9112:             my $match = 0;
1.412     raeburn  9113:             my $secmatch = 0;
1.419     raeburn  9114:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9115:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9116:             if ($section eq '') {
                   9117:                 $section = 'none';
                   9118:             }
1.291     albertel 9119:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9120:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9121:                     $secmatch = 1;
                   9122:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9123:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9124:                         $secmatch = 1;
                   9125:                     }
                   9126:                 } else {  
1.419     raeburn  9127: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9128: 		        $secmatch = 1;
                   9129:                     }
1.290     albertel 9130: 		}
1.412     raeburn  9131:                 if (!$secmatch) {
                   9132:                     next;
                   9133:                 }
1.419     raeburn  9134:             }
1.275     raeburn  9135:             if (defined($$types{'active'})) {
1.288     raeburn  9136:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9137:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9138:                     $match = 1;
1.275     raeburn  9139:                 }
                   9140:             }
                   9141:             if (defined($$types{'previous'})) {
1.609     raeburn  9142:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9143:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9144:                     $match = 1;
1.275     raeburn  9145:                 }
                   9146:             }
                   9147:             if (defined($$types{'future'})) {
1.609     raeburn  9148:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9149:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9150:                     $match = 1;
1.275     raeburn  9151:                 }
                   9152:             }
1.609     raeburn  9153:             if ($match) {
                   9154:                 push(@{$seclists{$student}},$section);
                   9155:                 if (ref($userdata) eq 'HASH') {
                   9156:                     $$userdata{$student} = $$classlist{$student};
                   9157:                 }
                   9158:                 if (ref($statushash) eq 'HASH') {
                   9159:                     $statushash->{$student}{'st'}{$section} = $status;
                   9160:                 }
1.288     raeburn  9161:             }
1.275     raeburn  9162:         }
                   9163:     }
1.412     raeburn  9164:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9165:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9166:         my $now = time;
1.609     raeburn  9167:         my %displaystatus = ( previous => 'Expired',
                   9168:                               active   => 'Active',
                   9169:                               future   => 'Future',
                   9170:                             );
1.1121    raeburn  9171:         my (%nothide,@possdoms);
1.630     raeburn  9172:         if ($hidepriv) {
                   9173:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9174:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9175:                 if ($user !~ /:/) {
                   9176:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9177:                 } else {
                   9178:                     $nothide{$user} = 1;
                   9179:                 }
                   9180:             }
1.1121    raeburn  9181:             my @possdoms = ($cdom);
                   9182:             if ($coursehash{'checkforpriv'}) {
                   9183:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9184:             }
1.630     raeburn  9185:         }
1.439     raeburn  9186:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9187:             my $match = 0;
1.412     raeburn  9188:             my $secmatch = 0;
1.439     raeburn  9189:             my $status;
1.412     raeburn  9190:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9191:             $user =~ s/:$//;
1.439     raeburn  9192:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9193:             if ($end == -1 || $start == -1) {
                   9194:                 next;
                   9195:             }
                   9196:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9197:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9198:                 my ($uname,$udom) = split(/:/,$user);
                   9199:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9200:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9201:                         $secmatch = 1;
                   9202:                     } elsif ($usec eq '') {
1.420     albertel 9203:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9204:                             $secmatch = 1;
                   9205:                         }
                   9206:                     } else {
                   9207:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9208:                             $secmatch = 1;
                   9209:                         }
                   9210:                     }
                   9211:                     if (!$secmatch) {
                   9212:                         next;
                   9213:                     }
1.288     raeburn  9214:                 }
1.419     raeburn  9215:                 if ($usec eq '') {
                   9216:                     $usec = 'none';
                   9217:                 }
1.275     raeburn  9218:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9219:                     if ($hidepriv) {
1.1121    raeburn  9220:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9221:                             (!$nothide{$uname.':'.$udom})) {
                   9222:                             next;
                   9223:                         }
                   9224:                     }
1.503     raeburn  9225:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9226:                         $status = 'previous';
                   9227:                     } elsif ($start > $now) {
                   9228:                         $status = 'future';
                   9229:                     } else {
                   9230:                         $status = 'active';
                   9231:                     }
1.277     albertel 9232:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9233:                         if ($status eq $type) {
1.420     albertel 9234:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9235:                                 push(@{$$users{$role}{$user}},$type);
                   9236:                             }
1.288     raeburn  9237:                             $match = 1;
                   9238:                         }
                   9239:                     }
1.419     raeburn  9240:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9241:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9242: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9243:                         }
1.420     albertel 9244:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9245:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9246:                         }
1.609     raeburn  9247:                         if (ref($statushash) eq 'HASH') {
                   9248:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9249:                         }
1.275     raeburn  9250:                     }
                   9251:                 }
                   9252:             }
                   9253:         }
1.290     albertel 9254:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9255:             if ((defined($cdom)) && (defined($cnum))) {
                   9256:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9257:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9258:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9259:                     next if ($owner eq '');
                   9260:                     my ($ownername,$ownerdom);
                   9261:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9262:                         $ownername = $1;
                   9263:                         $ownerdom = $2;
                   9264:                     } else {
                   9265:                         $ownername = $owner;
                   9266:                         $ownerdom = $cdom;
                   9267:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9268:                     }
                   9269:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9270:                     if (defined($userdata) && 
1.609     raeburn  9271: 			!exists($$userdata{$owner})) {
                   9272: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9273:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9274:                             push(@{$seclists{$owner}},'none');
                   9275:                         }
                   9276:                         if (ref($statushash) eq 'HASH') {
                   9277:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9278:                         }
1.290     albertel 9279: 		    }
1.279     raeburn  9280:                 }
                   9281:             }
                   9282:         }
1.419     raeburn  9283:         foreach my $user (keys(%seclists)) {
                   9284:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9285:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9286:         }
1.275     raeburn  9287:     }
                   9288:     return;
                   9289: }
                   9290: 
1.288     raeburn  9291: sub get_user_info {
                   9292:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9293:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9294: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9295:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9296:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9297:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9298:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9299:     return;
                   9300: }
1.275     raeburn  9301: 
1.472     raeburn  9302: ###############################################
                   9303: 
                   9304: =pod
                   9305: 
                   9306: =item * &get_user_quota()
                   9307: 
1.1134    raeburn  9308: Retrieves quota assigned for storage of user files.
                   9309: Default is to report quota for portfolio files.
1.472     raeburn  9310: 
                   9311: Incoming parameters:
                   9312: 1. user's username
                   9313: 2. user's domain
1.1134    raeburn  9314: 3. quota name - portfolio, author, or course
1.1136    raeburn  9315:    (if no quota name provided, defaults to portfolio).
1.1165    raeburn  9316: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1136    raeburn  9317:    course
1.472     raeburn  9318: 
                   9319: Returns:
1.1163    raeburn  9320: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9321: 2. (Optional) Type of setting: custom or default
                   9322:    (individually assigned or default for user's 
                   9323:    institutional status).
                   9324: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9325:    or student - types as defined in localenroll::inst_usertypes 
                   9326:    for user's domain, which determines default quota for user.
                   9327: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9328: 
                   9329: If a value has been stored in the user's environment, 
1.536     raeburn  9330: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9331: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9332: 
                   9333: =cut
                   9334: 
                   9335: ###############################################
                   9336: 
                   9337: 
                   9338: sub get_user_quota {
1.1136    raeburn  9339:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9340:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9341:     if (!defined($udom)) {
                   9342:         $udom = $env{'user.domain'};
                   9343:     }
                   9344:     if (!defined($uname)) {
                   9345:         $uname = $env{'user.name'};
                   9346:     }
                   9347:     if (($udom eq '' || $uname eq '') ||
                   9348:         ($udom eq 'public') && ($uname eq 'public')) {
                   9349:         $quota = 0;
1.536     raeburn  9350:         $quotatype = 'default';
                   9351:         $defquota = 0; 
1.472     raeburn  9352:     } else {
1.536     raeburn  9353:         my $inststatus;
1.1134    raeburn  9354:         if ($quotaname eq 'course') {
                   9355:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9356:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9357:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9358:             } else {
                   9359:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9360:                 $quota = $cenv{'internal.uploadquota'};
                   9361:             }
1.536     raeburn  9362:         } else {
1.1134    raeburn  9363:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9364:                 if ($quotaname eq 'author') {
                   9365:                     $quota = $env{'environment.authorquota'};
                   9366:                 } else {
                   9367:                     $quota = $env{'environment.portfolioquota'};
                   9368:                 }
                   9369:                 $inststatus = $env{'environment.inststatus'};
                   9370:             } else {
                   9371:                 my %userenv = 
                   9372:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9373:                                          'authorquota','inststatus'],$udom,$uname);
                   9374:                 my ($tmp) = keys(%userenv);
                   9375:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9376:                     if ($quotaname eq 'author') {
                   9377:                         $quota = $userenv{'authorquota'};
                   9378:                     } else {
                   9379:                         $quota = $userenv{'portfolioquota'};
                   9380:                     }
                   9381:                     $inststatus = $userenv{'inststatus'};
                   9382:                 } else {
                   9383:                     undef(%userenv);
                   9384:                 }
                   9385:             }
                   9386:         }
                   9387:         if ($quota eq '' || wantarray) {
                   9388:             if ($quotaname eq 'course') {
                   9389:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9390:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
                   9391:                     ($crstype eq 'community') || ($crstype eq 'textbook')) { 
1.1136    raeburn  9392:                     $defquota = $domdefs{$crstype.'quota'};
                   9393:                 }
                   9394:                 if ($defquota eq '') {
                   9395:                     $defquota = 500;
                   9396:                 }
1.1134    raeburn  9397:             } else {
                   9398:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9399:             }
                   9400:             if ($quota eq '') {
                   9401:                 $quota = $defquota;
                   9402:                 $quotatype = 'default';
                   9403:             } else {
                   9404:                 $quotatype = 'custom';
                   9405:             }
1.472     raeburn  9406:         }
                   9407:     }
1.536     raeburn  9408:     if (wantarray) {
                   9409:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9410:     } else {
                   9411:         return $quota;
                   9412:     }
1.472     raeburn  9413: }
                   9414: 
                   9415: ###############################################
                   9416: 
                   9417: =pod
                   9418: 
                   9419: =item * &default_quota()
                   9420: 
1.536     raeburn  9421: Retrieves default quota assigned for storage of user portfolio files,
                   9422: given an (optional) user's institutional status.
1.472     raeburn  9423: 
                   9424: Incoming parameters:
1.1142    raeburn  9425: 
1.472     raeburn  9426: 1. domain
1.536     raeburn  9427: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9428:    status types (e.g., faculty, staff, student etc.)
                   9429:    which apply to the user for whom the default is being retrieved.
                   9430:    If the institutional status string in undefined, the domain
1.1134    raeburn  9431:    default quota will be returned.
                   9432: 3.  quota name - portfolio, author, or course
                   9433:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9434: 
                   9435: Returns:
1.1142    raeburn  9436: 
1.1163    raeburn  9437: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9438: 2. (Optional) institutional type which determined the value of the
                   9439:    default quota.
1.472     raeburn  9440: 
                   9441: If a value has been stored in the domain's configuration db,
                   9442: it will return that, otherwise it returns 20 (for backwards 
                   9443: compatibility with domains which have not set up a configuration
1.1163    raeburn  9444: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9445: 
1.536     raeburn  9446: If the user's status includes multiple types (e.g., staff and student),
                   9447: the largest default quota which applies to the user determines the
                   9448: default quota returned.
                   9449: 
1.472     raeburn  9450: =cut
                   9451: 
                   9452: ###############################################
                   9453: 
                   9454: 
                   9455: sub default_quota {
1.1134    raeburn  9456:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9457:     my ($defquota,$settingstatus);
                   9458:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9459:                                             ['quotas'],$udom);
1.1134    raeburn  9460:     my $key = 'defaultquota';
                   9461:     if ($quotaname eq 'author') {
                   9462:         $key = 'authorquota';
                   9463:     }
1.622     raeburn  9464:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9465:         if ($inststatus ne '') {
1.765     raeburn  9466:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9467:             foreach my $item (@statuses) {
1.1134    raeburn  9468:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9469:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9470:                         if ($defquota eq '') {
1.1134    raeburn  9471:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9472:                             $settingstatus = $item;
1.1134    raeburn  9473:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9474:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9475:                             $settingstatus = $item;
                   9476:                         }
                   9477:                     }
1.1134    raeburn  9478:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9479:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9480:                         if ($defquota eq '') {
                   9481:                             $defquota = $quotahash{'quotas'}{$item};
                   9482:                             $settingstatus = $item;
                   9483:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9484:                             $defquota = $quotahash{'quotas'}{$item};
                   9485:                             $settingstatus = $item;
                   9486:                         }
1.536     raeburn  9487:                     }
                   9488:                 }
                   9489:             }
                   9490:         }
                   9491:         if ($defquota eq '') {
1.1134    raeburn  9492:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9493:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9494:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9495:                 $defquota = $quotahash{'quotas'}{'default'};
                   9496:             }
1.536     raeburn  9497:             $settingstatus = 'default';
1.1139    raeburn  9498:             if ($defquota eq '') {
                   9499:                 if ($quotaname eq 'author') {
                   9500:                     $defquota = 500;
                   9501:                 }
                   9502:             }
1.536     raeburn  9503:         }
                   9504:     } else {
                   9505:         $settingstatus = 'default';
1.1134    raeburn  9506:         if ($quotaname eq 'author') {
                   9507:             $defquota = 500;
                   9508:         } else {
                   9509:             $defquota = 20;
                   9510:         }
1.536     raeburn  9511:     }
                   9512:     if (wantarray) {
                   9513:         return ($defquota,$settingstatus);
1.472     raeburn  9514:     } else {
1.536     raeburn  9515:         return $defquota;
1.472     raeburn  9516:     }
                   9517: }
                   9518: 
1.1135    raeburn  9519: ###############################################
                   9520: 
                   9521: =pod
                   9522: 
1.1136    raeburn  9523: =item * &excess_filesize_warning()
1.1135    raeburn  9524: 
                   9525: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  9526: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  9527: space to be exceeded.
1.1136    raeburn  9528: 
                   9529: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  9530: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  9531: 
1.1165    raeburn  9532: Inputs: 7 
1.1136    raeburn  9533: 1. username or coursenum
1.1135    raeburn  9534: 2. domain
1.1136    raeburn  9535: 3. context ('author' or 'course')
1.1135    raeburn  9536: 4. filename of file for which action is being requested
                   9537: 5. filesize (kB) of file
                   9538: 6. action being taken: copy or upload.
1.1165    raeburn  9539: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1135    raeburn  9540: 
                   9541: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  9542:          otherwise return null.
                   9543: 
                   9544: =back
1.1135    raeburn  9545: 
                   9546: =cut
                   9547: 
1.1136    raeburn  9548: sub excess_filesize_warning {
1.1165    raeburn  9549:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  9550:     my $current_disk_usage = 0;
1.1165    raeburn  9551:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  9552:     if ($context eq 'author') {
                   9553:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9554:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9555:     } else {
                   9556:         foreach my $subdir ('docs','supplemental') {
                   9557:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9558:         }
                   9559:     }
1.1135    raeburn  9560:     $disk_quota = int($disk_quota * 1000);
                   9561:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   9562:         return '<p class="LC_warning">'.
1.1135    raeburn  9563:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   9564:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9565:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  9566:                             $disk_quota,$current_disk_usage).
                   9567:                '</p>';
                   9568:     }
                   9569:     return;
                   9570: }
                   9571: 
                   9572: ###############################################
                   9573: 
                   9574: 
1.1136    raeburn  9575: 
                   9576: 
1.384     raeburn  9577: sub get_secgrprole_info {
                   9578:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9579:     my %sections_count = &get_sections($cdom,$cnum);
                   9580:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9581:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9582:     my @groups = sort(keys(%curr_groups));
                   9583:     my $allroles = [];
                   9584:     my $rolehash;
                   9585:     my $accesshash = {
                   9586:                      active => 'Currently has access',
                   9587:                      future => 'Will have future access',
                   9588:                      previous => 'Previously had access',
                   9589:                   };
                   9590:     if ($needroles) {
                   9591:         $rolehash = {'all' => 'all'};
1.385     albertel 9592:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9593: 	if (&Apache::lonnet::error(%user_roles)) {
                   9594: 	    undef(%user_roles);
                   9595: 	}
                   9596:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9597:             my ($role)=split(/\:/,$item,2);
                   9598:             if ($role eq 'cr') { next; }
                   9599:             if ($role =~ /^cr/) {
                   9600:                 $$rolehash{$role} = (split('/',$role))[3];
                   9601:             } else {
                   9602:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9603:             }
                   9604:         }
                   9605:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9606:             push(@{$allroles},$key);
                   9607:         }
                   9608:         push (@{$allroles},'st');
                   9609:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9610:     }
                   9611:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9612: }
                   9613: 
1.555     raeburn  9614: sub user_picker {
1.994     raeburn  9615:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9616:     my $currdom = $dom;
                   9617:     my %curr_selected = (
                   9618:                         srchin => 'dom',
1.580     raeburn  9619:                         srchby => 'lastname',
1.555     raeburn  9620:                       );
                   9621:     my $srchterm;
1.625     raeburn  9622:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9623:         if ($srch->{'srchby'} ne '') {
                   9624:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9625:         }
                   9626:         if ($srch->{'srchin'} ne '') {
                   9627:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9628:         }
                   9629:         if ($srch->{'srchtype'} ne '') {
                   9630:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9631:         }
                   9632:         if ($srch->{'srchdomain'} ne '') {
                   9633:             $currdom = $srch->{'srchdomain'};
                   9634:         }
                   9635:         $srchterm = $srch->{'srchterm'};
                   9636:     }
1.1222    damieng  9637:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9638:                     'usr'       => 'Search criteria',
1.563     raeburn  9639:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9640:                     'uname'     => 'username',
                   9641:                     'lastname'  => 'last name',
1.555     raeburn  9642:                     'lastfirst' => 'last name, first name',
1.558     albertel 9643:                     'crs'       => 'in this course',
1.576     raeburn  9644:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9645:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9646:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9647:                     'exact'     => 'is',
                   9648:                     'contains'  => 'contains',
1.569     raeburn  9649:                     'begins'    => 'begins with',
1.1222    damieng  9650:                                        );
                   9651:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9652:                     'youm'      => "You must include some text to search for.",
                   9653:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9654:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9655:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9656:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9657:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9658:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9659:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9660:                                        );
1.1222    damieng  9661:     &html_escape(\%html_lt);
                   9662:     &js_escape(\%js_lt);
1.563     raeburn  9663:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9664:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9665: 
                   9666:     my @srchins = ('crs','dom','alc','instd');
                   9667: 
                   9668:     foreach my $option (@srchins) {
                   9669:         # FIXME 'alc' option unavailable until 
                   9670:         #       loncreateuser::print_user_query_page()
                   9671:         #       has been completed.
                   9672:         next if ($option eq 'alc');
1.880     raeburn  9673:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9674:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9675:         if ($curr_selected{'srchin'} eq $option) {
                   9676:             $srchinsel .= ' 
1.1222    damieng  9677:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9678:         } else {
                   9679:             $srchinsel .= '
1.1222    damieng  9680:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9681:         }
1.555     raeburn  9682:     }
1.563     raeburn  9683:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9684: 
                   9685:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9686:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9687:         if ($curr_selected{'srchby'} eq $option) {
                   9688:             $srchbysel .= '
1.1222    damieng  9689:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9690:         } else {
                   9691:             $srchbysel .= '
1.1222    damieng  9692:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9693:          }
                   9694:     }
                   9695:     $srchbysel .= "\n  </select>\n";
                   9696: 
                   9697:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9698:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9699:         if ($curr_selected{'srchtype'} eq $option) {
                   9700:             $srchtypesel .= '
1.1222    damieng  9701:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9702:         } else {
                   9703:             $srchtypesel .= '
1.1222    damieng  9704:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9705:         }
                   9706:     }
                   9707:     $srchtypesel .= "\n  </select>\n";
                   9708: 
1.558     albertel 9709:     my ($newuserscript,$new_user_create);
1.994     raeburn  9710:     my $context_dom = $env{'request.role.domain'};
                   9711:     if ($context eq 'requestcrs') {
                   9712:         if ($env{'form.coursedom'} ne '') { 
                   9713:             $context_dom = $env{'form.coursedom'};
                   9714:         }
                   9715:     }
1.556     raeburn  9716:     if ($forcenewuser) {
1.576     raeburn  9717:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9718:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9719:                 if ($cancreate) {
                   9720:                     $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>';
                   9721:                 } else {
1.799     bisitz   9722:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9723:                     my %usertypetext = (
                   9724:                         official   => 'institutional',
                   9725:                         unofficial => 'non-institutional',
                   9726:                     );
1.799     bisitz   9727:                     $new_user_create = '<p class="LC_warning">'
                   9728:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9729:                                       .' '
                   9730:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9731:                                           ,'<a href="'.$helplink.'">','</a>')
                   9732:                                       .'</p><br />';
1.627     raeburn  9733:                 }
1.576     raeburn  9734:             }
                   9735:         }
                   9736: 
1.556     raeburn  9737:         $newuserscript = <<"ENDSCRIPT";
                   9738: 
1.570     raeburn  9739: function setSearch(createnew,callingForm) {
1.556     raeburn  9740:     if (createnew == 1) {
1.570     raeburn  9741:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9742:             if (callingForm.srchby.options[i].value == 'uname') {
                   9743:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9744:             }
                   9745:         }
1.570     raeburn  9746:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9747:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9748: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9749:             }
                   9750:         }
1.570     raeburn  9751:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9752:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9753:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9754:             }
                   9755:         }
1.570     raeburn  9756:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9757:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9758:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9759:             }
                   9760:         }
                   9761:     }
                   9762: }
                   9763: ENDSCRIPT
1.558     albertel 9764: 
1.556     raeburn  9765:     }
                   9766: 
1.555     raeburn  9767:     my $output = <<"END_BLOCK";
1.556     raeburn  9768: <script type="text/javascript">
1.824     bisitz   9769: // <![CDATA[
1.570     raeburn  9770: function validateEntry(callingForm) {
1.558     albertel 9771: 
1.556     raeburn  9772:     var checkok = 1;
1.558     albertel 9773:     var srchin;
1.570     raeburn  9774:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9775: 	if ( callingForm.srchin[i].checked ) {
                   9776: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9777: 	}
                   9778:     }
                   9779: 
1.570     raeburn  9780:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9781:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9782:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9783:     var srchterm =  callingForm.srchterm.value;
                   9784:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9785:     var msg = "";
                   9786: 
                   9787:     if (srchterm == "") {
                   9788:         checkok = 0;
1.1222    damieng  9789:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  9790:     }
                   9791: 
1.569     raeburn  9792:     if (srchtype== 'begins') {
                   9793:         if (srchterm.length < 2) {
                   9794:             checkok = 0;
1.1222    damieng  9795:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  9796:         }
                   9797:     }
                   9798: 
1.556     raeburn  9799:     if (srchtype== 'contains') {
                   9800:         if (srchterm.length < 3) {
                   9801:             checkok = 0;
1.1222    damieng  9802:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  9803:         }
                   9804:     }
                   9805:     if (srchin == 'instd') {
                   9806:         if (srchdomain == '') {
                   9807:             checkok = 0;
1.1222    damieng  9808:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  9809:         }
                   9810:     }
                   9811:     if (srchin == 'dom') {
                   9812:         if (srchdomain == '') {
                   9813:             checkok = 0;
1.1222    damieng  9814:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  9815:         }
                   9816:     }
                   9817:     if (srchby == 'lastfirst') {
                   9818:         if (srchterm.indexOf(",") == -1) {
                   9819:             checkok = 0;
1.1222    damieng  9820:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  9821:         }
                   9822:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9823:             checkok = 0;
1.1222    damieng  9824:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  9825:         }
                   9826:     }
                   9827:     if (checkok == 0) {
1.1222    damieng  9828:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  9829:         return;
                   9830:     }
                   9831:     if (checkok == 1) {
1.570     raeburn  9832:         callingForm.submit();
1.556     raeburn  9833:     }
                   9834: }
                   9835: 
                   9836: $newuserscript
                   9837: 
1.824     bisitz   9838: // ]]>
1.556     raeburn  9839: </script>
1.558     albertel 9840: 
                   9841: $new_user_create
                   9842: 
1.555     raeburn  9843: END_BLOCK
1.558     albertel 9844: 
1.876     raeburn  9845:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  9846:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  9847:                $domform.
                   9848:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  9849:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  9850:                $srchbysel.
                   9851:                $srchtypesel. 
                   9852:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9853:                $srchinsel.
                   9854:                &Apache::lonhtmlcommon::row_closure(1). 
                   9855:                &Apache::lonhtmlcommon::end_pick_box().
                   9856:                '<br />';
1.555     raeburn  9857:     return $output;
                   9858: }
                   9859: 
1.612     raeburn  9860: sub user_rule_check {
1.615     raeburn  9861:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  9862:     my ($response,%inst_response);
1.612     raeburn  9863:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  9864:         if (keys(%{$usershash}) > 1) {
                   9865:             my (%by_username,%by_id,%userdoms);
                   9866:             my $checkid; 
                   9867:             if (ref($checks) eq 'HASH') {
                   9868:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   9869:                     $checkid = 1;
                   9870:                 }
                   9871:             }
                   9872:             foreach my $user (keys(%{$usershash})) {
                   9873:                 my ($uname,$udom) = split(/:/,$user);
                   9874:                 if ($checkid) {
                   9875:                     if (ref($usershash->{$user}) eq 'HASH') {
                   9876:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  9877:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  9878:                             $userdoms{$udom} = 1;
1.1227    raeburn  9879:                             if (ref($inst_results) eq 'HASH') {
                   9880:                                 $inst_results->{$uname.':'.$udom} = {};
                   9881:                             }
1.1226    raeburn  9882:                         }
                   9883:                     }
                   9884:                 } else {
                   9885:                     $by_username{$udom}{$uname} = 1;
                   9886:                     $userdoms{$udom} = 1;
1.1227    raeburn  9887:                     if (ref($inst_results) eq 'HASH') {
                   9888:                         $inst_results->{$uname.':'.$udom} = {};
                   9889:                     }
1.1226    raeburn  9890:                 }
                   9891:             }
                   9892:             foreach my $udom (keys(%userdoms)) {
                   9893:                 if (!$got_rules->{$udom}) {
                   9894:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9895:                                                              ['usercreation'],$udom);
                   9896:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9897:                         foreach my $item ('username','id') {
                   9898:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  9899:                                 $$curr_rules{$udom}{$item} =
                   9900:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  9901:                             }
                   9902:                         }
                   9903:                     }
                   9904:                     $got_rules->{$udom} = 1;
                   9905:                 }
1.612     raeburn  9906:             }
1.1226    raeburn  9907:             if ($checkid) {
                   9908:                 foreach my $udom (keys(%by_id)) {
                   9909:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   9910:                     if ($outcome eq 'ok') {
1.1227    raeburn  9911:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   9912:                             my $uname = $by_id{$udom}{$id};
                   9913:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9914:                         }
1.1226    raeburn  9915:                         if (ref($results) eq 'HASH') {
                   9916:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  9917:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   9918:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   9919:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9920:                                 }
1.1226    raeburn  9921:                             }
                   9922:                         }
                   9923:                     }
1.612     raeburn  9924:                 }
1.615     raeburn  9925:             } else {
1.1226    raeburn  9926:                 foreach my $udom (keys(%by_username)) {
                   9927:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   9928:                     if ($outcome eq 'ok') {
1.1227    raeburn  9929:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   9930:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9931:                         }
1.1226    raeburn  9932:                         if (ref($results) eq 'HASH') {
                   9933:                             foreach my $uname (keys(%{$results})) {
                   9934:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9935:                             }
                   9936:                         }
                   9937:                     }
                   9938:                 }
1.612     raeburn  9939:             }
1.1226    raeburn  9940:         } elsif (keys(%{$usershash}) == 1) {
                   9941:             my $user = (keys(%{$usershash}))[0];
                   9942:             my ($uname,$udom) = split(/:/,$user);
                   9943:             if (($udom ne '') && ($uname ne '')) {
                   9944:                 if (ref($usershash->{$user}) eq 'HASH') {
                   9945:                     if (ref($checks) eq 'HASH') {
                   9946:                         if (defined($checks->{'username'})) {
                   9947:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   9948:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   9949:                         } elsif (defined($checks->{'id'})) {
                   9950:                             if ($usershash->{$user}->{'id'} ne '') {
                   9951:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9952:                                     &Apache::lonnet::get_instuser($udom,undef,
                   9953:                                                                   $usershash->{$user}->{'id'});
                   9954:                             } else {
                   9955:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9956:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   9957:                             }
1.585     raeburn  9958:                         }
1.1226    raeburn  9959:                     } else {
                   9960:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   9961:                             &Apache::lonnet::get_instuser($udom,$uname);
                   9962:                        return;
                   9963:                     }
                   9964:                     if (!$got_rules->{$udom}) {
                   9965:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9966:                                                                  ['usercreation'],$udom);
                   9967:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9968:                             foreach my $item ('username','id') {
                   9969:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9970:                                    $$curr_rules{$udom}{$item} = 
                   9971:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   9972:                                 }
                   9973:                             }
                   9974:                         }
                   9975:                         $got_rules->{$udom} = 1;
1.585     raeburn  9976:                     }
                   9977:                 }
1.1226    raeburn  9978:             } else {
                   9979:                 return;
                   9980:             }
                   9981:         } else {
                   9982:             return;
                   9983:         }
                   9984:         foreach my $user (keys(%{$usershash})) {
                   9985:             my ($uname,$udom) = split(/:/,$user);
                   9986:             next if (($udom eq '') || ($uname eq ''));
                   9987:             my $id;
1.1227    raeburn  9988:             if (ref($inst_results) eq 'HASH') {
                   9989:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   9990:                     $id = $inst_results->{$user}->{'id'};
                   9991:                 }
                   9992:             }
                   9993:             if ($id eq '') { 
                   9994:                 if (ref($usershash->{$user})) {
                   9995:                     $id = $usershash->{$user}->{'id'};
                   9996:                 }
1.585     raeburn  9997:             }
1.612     raeburn  9998:             foreach my $item (keys(%{$checks})) {
                   9999:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10000:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10001:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10002:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10003:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10004:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10005:                                 if ($rule_check{$rule}) {
                   10006:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10007:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10008:                                         if (ref($inst_results) eq 'HASH') {
                   10009:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10010:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10011:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10012:                                                 } elsif ($item eq 'id') {
                   10013:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10014:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10015:                                                     }
1.615     raeburn  10016:                                                 }
1.612     raeburn  10017:                                             }
                   10018:                                         }
1.615     raeburn  10019:                                     }
                   10020:                                     last;
1.585     raeburn  10021:                                 }
                   10022:                             }
                   10023:                         }
                   10024:                     }
                   10025:                 }
                   10026:             }
                   10027:         }
                   10028:     }
1.612     raeburn  10029:     return;
                   10030: }
                   10031: 
                   10032: sub user_rule_formats {
                   10033:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10034:     my %text = ( 
                   10035:                  'username' => 'Usernames',
                   10036:                  'id'       => 'IDs',
                   10037:                );
                   10038:     my $output;
                   10039:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10040:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10041:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10042:             $output = '<br />'.
                   10043:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10044:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10045:                       ' <ul>';
1.612     raeburn  10046:             foreach my $rule (@{$ruleorder}) {
                   10047:                 if (ref($curr_rules) eq 'ARRAY') {
                   10048:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10049:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10050:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10051:                                         $rules->{$rule}{'desc'}.'</li>';
                   10052:                         }
                   10053:                     }
                   10054:                 }
                   10055:             }
                   10056:             $output .= '</ul>';
                   10057:         }
                   10058:     }
                   10059:     return $output;
                   10060: }
                   10061: 
                   10062: sub instrule_disallow_msg {
1.615     raeburn  10063:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10064:     my $response;
                   10065:     my %text = (
                   10066:                   item   => 'username',
                   10067:                   items  => 'usernames',
                   10068:                   match  => 'matches',
                   10069:                   do     => 'does',
                   10070:                   action => 'a username',
                   10071:                   one    => 'one',
                   10072:                );
                   10073:     if ($count > 1) {
                   10074:         $text{'item'} = 'usernames';
                   10075:         $text{'match'} ='match';
                   10076:         $text{'do'} = 'do';
                   10077:         $text{'action'} = 'usernames',
                   10078:         $text{'one'} = 'ones';
                   10079:     }
                   10080:     if ($checkitem eq 'id') {
                   10081:         $text{'items'} = 'IDs';
                   10082:         $text{'item'} = 'ID';
                   10083:         $text{'action'} = 'an ID';
1.615     raeburn  10084:         if ($count > 1) {
                   10085:             $text{'item'} = 'IDs';
                   10086:             $text{'action'} = 'IDs';
                   10087:         }
1.612     raeburn  10088:     }
1.674     bisitz   10089:     $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  10090:     if ($mode eq 'upload') {
                   10091:         if ($checkitem eq 'username') {
                   10092:             $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'}.");
                   10093:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10094:             $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  10095:         }
1.669     raeburn  10096:     } elsif ($mode eq 'selfcreate') {
                   10097:         if ($checkitem eq 'id') {
                   10098:             $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.");
                   10099:         }
1.615     raeburn  10100:     } else {
                   10101:         if ($checkitem eq 'username') {
                   10102:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10103:         } elsif ($checkitem eq 'id') {
                   10104:             $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.");
                   10105:         }
1.612     raeburn  10106:     }
                   10107:     return $response;
1.585     raeburn  10108: }
                   10109: 
1.624     raeburn  10110: sub personal_data_fieldtitles {
                   10111:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10112:                         id => 'Student/Employee ID',
                   10113:                         permanentemail => 'E-mail address',
                   10114:                         lastname => 'Last Name',
                   10115:                         firstname => 'First Name',
                   10116:                         middlename => 'Middle Name',
                   10117:                         generation => 'Generation',
                   10118:                         gen => 'Generation',
1.765     raeburn  10119:                         inststatus => 'Affiliation',
1.624     raeburn  10120:                    );
                   10121:     return %fieldtitles;
                   10122: }
                   10123: 
1.642     raeburn  10124: sub sorted_inst_types {
                   10125:     my ($dom) = @_;
1.1185    raeburn  10126:     my ($usertypes,$order);
                   10127:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10128:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10129:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10130:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10131:     } else {
                   10132:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10133:     }
1.642     raeburn  10134:     my $othertitle = &mt('All users');
                   10135:     if ($env{'request.course.id'}) {
1.668     raeburn  10136:         $othertitle  = &mt('Any users');
1.642     raeburn  10137:     }
                   10138:     my @types;
                   10139:     if (ref($order) eq 'ARRAY') {
                   10140:         @types = @{$order};
                   10141:     }
                   10142:     if (@types == 0) {
                   10143:         if (ref($usertypes) eq 'HASH') {
                   10144:             @types = sort(keys(%{$usertypes}));
                   10145:         }
                   10146:     }
                   10147:     if (keys(%{$usertypes}) > 0) {
                   10148:         $othertitle = &mt('Other users');
                   10149:     }
                   10150:     return ($othertitle,$usertypes,\@types);
                   10151: }
                   10152: 
1.645     raeburn  10153: sub get_institutional_codes {
                   10154:     my ($settings,$allcourses,$LC_code) = @_;
                   10155: # Get complete list of course sections to update
                   10156:     my @currsections = ();
                   10157:     my @currxlists = ();
                   10158:     my $coursecode = $$settings{'internal.coursecode'};
                   10159: 
                   10160:     if ($$settings{'internal.sectionnums'} ne '') {
                   10161:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10162:     }
                   10163: 
                   10164:     if ($$settings{'internal.crosslistings'} ne '') {
                   10165:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10166:     }
                   10167: 
                   10168:     if (@currxlists > 0) {
                   10169:         foreach (@currxlists) {
                   10170:             if (m/^([^:]+):(\w*)$/) {
                   10171:                 unless (grep/^$1$/,@{$allcourses}) {
                   10172:                     push @{$allcourses},$1;
                   10173:                     $$LC_code{$1} = $2;
                   10174:                 }
                   10175:             }
                   10176:         }
                   10177:     }
                   10178:  
                   10179:     if (@currsections > 0) {
                   10180:         foreach (@currsections) {
                   10181:             if (m/^(\w+):(\w*)$/) {
                   10182:                 my $sec = $coursecode.$1;
                   10183:                 my $lc_sec = $2;
                   10184:                 unless (grep/^$sec$/,@{$allcourses}) {
                   10185:                     push @{$allcourses},$sec;
                   10186:                     $$LC_code{$sec} = $lc_sec;
                   10187:                 }
                   10188:             }
                   10189:         }
                   10190:     }
                   10191:     return;
                   10192: }
                   10193: 
1.971     raeburn  10194: sub get_standard_codeitems {
                   10195:     return ('Year','Semester','Department','Number','Section');
                   10196: }
                   10197: 
1.112     bowersj2 10198: =pod
                   10199: 
1.780     raeburn  10200: =head1 Slot Helpers
                   10201: 
                   10202: =over 4
                   10203: 
                   10204: =item * sorted_slots()
                   10205: 
1.1040    raeburn  10206: Sorts an array of slot names in order of an optional sort key,
                   10207: default sort is by slot start time (earliest first). 
1.780     raeburn  10208: 
                   10209: Inputs:
                   10210: 
                   10211: =over 4
                   10212: 
                   10213: slotsarr  - Reference to array of unsorted slot names.
                   10214: 
                   10215: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10216: 
1.1040    raeburn  10217: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10218: 
1.549     albertel 10219: =back
                   10220: 
1.780     raeburn  10221: Returns:
                   10222: 
                   10223: =over 4
                   10224: 
1.1040    raeburn  10225: sorted   - An array of slot names sorted by a specified sort key 
                   10226:            (default sort key is start time of the slot).
1.780     raeburn  10227: 
                   10228: =back
                   10229: 
                   10230: =cut
                   10231: 
                   10232: 
                   10233: sub sorted_slots {
1.1040    raeburn  10234:     my ($slotsarr,$slots,$sortkey) = @_;
                   10235:     if ($sortkey eq '') {
                   10236:         $sortkey = 'starttime';
                   10237:     }
1.780     raeburn  10238:     my @sorted;
                   10239:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10240:         @sorted =
                   10241:             sort {
                   10242:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10243:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10244:                      }
                   10245:                      if (ref($slots->{$a})) { return -1;}
                   10246:                      if (ref($slots->{$b})) { return 1;}
                   10247:                      return 0;
                   10248:                  } @{$slotsarr};
                   10249:     }
                   10250:     return @sorted;
                   10251: }
                   10252: 
1.1040    raeburn  10253: =pod
                   10254: 
                   10255: =item * get_future_slots()
                   10256: 
                   10257: Inputs:
                   10258: 
                   10259: =over 4
                   10260: 
                   10261: cnum - course number
                   10262: 
                   10263: cdom - course domain
                   10264: 
                   10265: now - current UNIX time
                   10266: 
                   10267: symb - optional symb
                   10268: 
                   10269: =back
                   10270: 
                   10271: Returns:
                   10272: 
                   10273: =over 4
                   10274: 
                   10275: sorted_reservable - ref to array of student_schedulable slots currently 
                   10276:                     reservable, ordered by end date of reservation period.
                   10277: 
                   10278: reservable_now - ref to hash of student_schedulable slots currently
                   10279:                  reservable.
                   10280: 
                   10281:     Keys in inner hash are:
                   10282:     (a) symb: either blank or symb to which slot use is restricted.
                   10283:     (b) endreserve: end date of reservation period. 
                   10284: 
                   10285: sorted_future - ref to array of student_schedulable slots reservable in
                   10286:                 the future, ordered by start date of reservation period.
                   10287: 
                   10288: future_reservable - ref to hash of student_schedulable slots reservable
                   10289:                     in the future.
                   10290: 
                   10291:     Keys in inner hash are:
                   10292:     (a) symb: either blank or symb to which slot use is restricted.
                   10293:     (b) startreserve:  start date of reservation period.
                   10294: 
                   10295: =back
                   10296: 
                   10297: =cut
                   10298: 
                   10299: sub get_future_slots {
                   10300:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  10301:     my $map;
                   10302:     if ($symb) {
                   10303:         ($map) = &Apache::lonnet::decode_symb($symb);
                   10304:     }
1.1040    raeburn  10305:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10306:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10307:     foreach my $slot (keys(%slots)) {
                   10308:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10309:         if ($symb) {
1.1229    raeburn  10310:             if ($slots{$slot}->{'symb'} ne '') {
                   10311:                 my $canuse;
                   10312:                 my %oksymbs;
                   10313:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   10314:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   10315:                 if ($oksymbs{$symb}) {
                   10316:                     $canuse = 1;
                   10317:                 } else {
                   10318:                     foreach my $item (@slotsymbs) {
                   10319:                         if ($item =~ /\.(page|sequence)$/) {
                   10320:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   10321:                             if (($map ne '') && ($map eq $sloturl)) {
                   10322:                                 $canuse = 1;
                   10323:                                 last;
                   10324:                             }
                   10325:                         }
                   10326:                     }
                   10327:                 }
                   10328:                 next unless ($canuse);
                   10329:             }
1.1040    raeburn  10330:         }
                   10331:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10332:             ($slots{$slot}->{'endtime'} > $now)) {
                   10333:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10334:                 my $userallowed = 0;
                   10335:                 if ($slots{$slot}->{'allowedsections'}) {
                   10336:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10337:                     if (!defined($env{'request.role.sec'})
                   10338:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10339:                         $userallowed=1;
                   10340:                     } else {
                   10341:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10342:                             $userallowed=1;
                   10343:                         }
                   10344:                     }
                   10345:                     unless ($userallowed) {
                   10346:                         if (defined($env{'request.course.groups'})) {
                   10347:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10348:                             foreach my $group (@groups) {
                   10349:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10350:                                     $userallowed=1;
                   10351:                                     last;
                   10352:                                 }
                   10353:                             }
                   10354:                         }
                   10355:                     }
                   10356:                 }
                   10357:                 if ($slots{$slot}->{'allowedusers'}) {
                   10358:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10359:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10360:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10361:                         $userallowed = 1;
                   10362:                     }
                   10363:                 }
                   10364:                 next unless($userallowed);
                   10365:             }
                   10366:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10367:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10368:             my $symb = $slots{$slot}->{'symb'};
                   10369:             if (($startreserve < $now) &&
                   10370:                 (!$endreserve || $endreserve > $now)) {
                   10371:                 my $lastres = $endreserve;
                   10372:                 if (!$lastres) {
                   10373:                     $lastres = $slots{$slot}->{'starttime'};
                   10374:                 }
                   10375:                 $reservable_now{$slot} = {
                   10376:                                            symb       => $symb,
                   10377:                                            endreserve => $lastres
                   10378:                                          };
                   10379:             } elsif (($startreserve > $now) &&
                   10380:                      (!$endreserve || $endreserve > $startreserve)) {
                   10381:                 $future_reservable{$slot} = {
                   10382:                                               symb         => $symb,
                   10383:                                               startreserve => $startreserve
                   10384:                                             };
                   10385:             }
                   10386:         }
                   10387:     }
                   10388:     my @unsorted_reservable = keys(%reservable_now);
                   10389:     if (@unsorted_reservable > 0) {
                   10390:         @sorted_reservable = 
                   10391:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10392:     }
                   10393:     my @unsorted_future = keys(%future_reservable);
                   10394:     if (@unsorted_future > 0) {
                   10395:         @sorted_future =
                   10396:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10397:     }
                   10398:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10399: }
1.780     raeburn  10400: 
                   10401: =pod
                   10402: 
1.1057    foxr     10403: =back
                   10404: 
1.549     albertel 10405: =head1 HTTP Helpers
                   10406: 
                   10407: =over 4
                   10408: 
1.648     raeburn  10409: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10410: 
1.258     albertel 10411: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10412: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10413: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10414: 
                   10415: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10416: $possible_names is an ref to an array of form element names.  As an example:
                   10417: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10418: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10419: 
                   10420: =cut
1.1       albertel 10421: 
1.6       albertel 10422: sub get_unprocessed_cgi {
1.25      albertel 10423:   my ($query,$possible_names)= @_;
1.26      matthew  10424:   # $Apache::lonxml::debug=1;
1.356     albertel 10425:   foreach my $pair (split(/&/,$query)) {
                   10426:     my ($name, $value) = split(/=/,$pair);
1.369     www      10427:     $name = &unescape($name);
1.25      albertel 10428:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10429:       $value =~ tr/+/ /;
                   10430:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10431:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10432:     }
1.16      harris41 10433:   }
1.6       albertel 10434: }
                   10435: 
1.112     bowersj2 10436: =pod
                   10437: 
1.648     raeburn  10438: =item * &cacheheader() 
1.112     bowersj2 10439: 
                   10440: returns cache-controlling header code
                   10441: 
                   10442: =cut
                   10443: 
1.7       albertel 10444: sub cacheheader {
1.258     albertel 10445:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10446:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10447:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10448:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10449:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10450:     return $output;
1.7       albertel 10451: }
                   10452: 
1.112     bowersj2 10453: =pod
                   10454: 
1.648     raeburn  10455: =item * &no_cache($r) 
1.112     bowersj2 10456: 
                   10457: specifies header code to not have cache
                   10458: 
                   10459: =cut
                   10460: 
1.9       albertel 10461: sub no_cache {
1.216     albertel 10462:     my ($r) = @_;
                   10463:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10464: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10465:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10466:     $r->no_cache(1);
                   10467:     $r->header_out("Expires" => $date);
                   10468:     $r->header_out("Pragma" => "no-cache");
1.123     www      10469: }
                   10470: 
                   10471: sub content_type {
1.181     albertel 10472:     my ($r,$type,$charset) = @_;
1.299     foxr     10473:     if ($r) {
                   10474: 	#  Note that printout.pl calls this with undef for $r.
                   10475: 	&no_cache($r);
                   10476:     }
1.258     albertel 10477:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10478:     unless ($charset) {
                   10479: 	$charset=&Apache::lonlocal::current_encoding;
                   10480:     }
                   10481:     if ($charset) { $type.='; charset='.$charset; }
                   10482:     if ($r) {
                   10483: 	$r->content_type($type);
                   10484:     } else {
                   10485: 	print("Content-type: $type\n\n");
                   10486:     }
1.9       albertel 10487: }
1.25      albertel 10488: 
1.112     bowersj2 10489: =pod
                   10490: 
1.648     raeburn  10491: =item * &add_to_env($name,$value) 
1.112     bowersj2 10492: 
1.258     albertel 10493: adds $name to the %env hash with value
1.112     bowersj2 10494: $value, if $name already exists, the entry is converted to an array
                   10495: reference and $value is added to the array.
                   10496: 
                   10497: =cut
                   10498: 
1.25      albertel 10499: sub add_to_env {
                   10500:   my ($name,$value)=@_;
1.258     albertel 10501:   if (defined($env{$name})) {
                   10502:     if (ref($env{$name})) {
1.25      albertel 10503:       #already have multiple values
1.258     albertel 10504:       push(@{ $env{$name} },$value);
1.25      albertel 10505:     } else {
                   10506:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10507:       my $first=$env{$name};
                   10508:       undef($env{$name});
                   10509:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10510:     }
                   10511:   } else {
1.258     albertel 10512:     $env{$name}=$value;
1.25      albertel 10513:   }
1.31      albertel 10514: }
1.149     albertel 10515: 
                   10516: =pod
                   10517: 
1.648     raeburn  10518: =item * &get_env_multiple($name) 
1.149     albertel 10519: 
1.258     albertel 10520: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10521: values may be defined and end up as an array ref.
                   10522: 
                   10523: returns an array of values
                   10524: 
                   10525: =cut
                   10526: 
                   10527: sub get_env_multiple {
                   10528:     my ($name) = @_;
                   10529:     my @values;
1.258     albertel 10530:     if (defined($env{$name})) {
1.149     albertel 10531:         # exists is it an array
1.258     albertel 10532:         if (ref($env{$name})) {
                   10533:             @values=@{ $env{$name} };
1.149     albertel 10534:         } else {
1.258     albertel 10535:             $values[0]=$env{$name};
1.149     albertel 10536:         }
                   10537:     }
                   10538:     return(@values);
                   10539: }
                   10540: 
1.660     raeburn  10541: sub ask_for_embedded_content {
                   10542:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10543:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  10544:         %currsubfile,%unused,$rem);
1.1071    raeburn  10545:     my $counter = 0;
                   10546:     my $numnew = 0;
1.987     raeburn  10547:     my $numremref = 0;
                   10548:     my $numinvalid = 0;
                   10549:     my $numpathchg = 0;
                   10550:     my $numexisting = 0;
1.1071    raeburn  10551:     my $numunused = 0;
                   10552:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  10553:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10554:     my $heading = &mt('Upload embedded files');
                   10555:     my $buttontext = &mt('Upload');
                   10556: 
1.1085    raeburn  10557:     if ($env{'request.course.id'}) {
1.1123    raeburn  10558:         if ($actionurl eq '/adm/dependencies') {
                   10559:             $navmap = Apache::lonnavmaps::navmap->new();
                   10560:         }
                   10561:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10562:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  10563:     }
1.1123    raeburn  10564:     if (($actionurl eq '/adm/portfolio') || 
                   10565:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10566:         my $current_path='/';
                   10567:         if ($env{'form.currentpath'}) {
                   10568:             $current_path = $env{'form.currentpath'};
                   10569:         }
                   10570:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  10571:             $udom = $cdom;
                   10572:             $uname = $cnum;
1.984     raeburn  10573:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10574:         } else {
                   10575:             $udom = $env{'user.domain'};
                   10576:             $uname = $env{'user.name'};
                   10577:             $url = '/userfiles/portfolio';
                   10578:         }
1.987     raeburn  10579:         $toplevel = $url.'/';
1.984     raeburn  10580:         $url .= $current_path;
                   10581:         $getpropath = 1;
1.987     raeburn  10582:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10583:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10584:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10585:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10586:         $toplevel = $url;
1.984     raeburn  10587:         if ($rest ne '') {
1.987     raeburn  10588:             $url .= $rest;
                   10589:         }
                   10590:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10591:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10592:             $url = $args->{'docs_url'};
                   10593:             $toplevel = $url;
1.1084    raeburn  10594:             if ($args->{'context'} eq 'paste') {
                   10595:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10596:                 ($path) = 
                   10597:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10598:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10599:                 $fileloc =~ s{^/}{};
                   10600:             }
1.1071    raeburn  10601:         }
1.1084    raeburn  10602:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  10603:         if ($env{'request.course.id'} ne '') {
                   10604:             if (ref($args) eq 'HASH') {
                   10605:                 $url = $args->{'docs_url'};
                   10606:                 $title = $args->{'docs_title'};
1.1126    raeburn  10607:                 $toplevel = $url; 
                   10608:                 unless ($toplevel =~ m{^/}) {
                   10609:                     $toplevel = "/$url";
                   10610:                 }
1.1085    raeburn  10611:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  10612:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10613:                     $path = $1;
                   10614:                 } else {
                   10615:                     ($path) =
                   10616:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10617:                 }
1.1195    raeburn  10618:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10619:                     $fileloc = $toplevel;
                   10620:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10621:                     my ($udom,$uname,$fname) =
                   10622:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10623:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10624:                 } else {
                   10625:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10626:                 }
1.1071    raeburn  10627:                 $fileloc =~ s{^/}{};
                   10628:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10629:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10630:             }
1.987     raeburn  10631:         }
1.1123    raeburn  10632:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10633:         $udom = $cdom;
                   10634:         $uname = $cnum;
                   10635:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10636:         $toplevel = $url;
                   10637:         $path = $url;
                   10638:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10639:         $fileloc =~ s{^/}{};
1.987     raeburn  10640:     }
1.1126    raeburn  10641:     foreach my $file (keys(%{$allfiles})) {
                   10642:         my $embed_file;
                   10643:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10644:             $embed_file = $1;
                   10645:         } else {
                   10646:             $embed_file = $file;
                   10647:         }
1.1158    raeburn  10648:         my ($absolutepath,$cleaned_file);
                   10649:         if ($embed_file =~ m{^\w+://}) {
                   10650:             $cleaned_file = $embed_file;
1.1147    raeburn  10651:             $newfiles{$cleaned_file} = 1;
                   10652:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10653:         } else {
1.1158    raeburn  10654:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10655:             if ($embed_file =~ m{^/}) {
                   10656:                 $absolutepath = $embed_file;
                   10657:             }
1.1147    raeburn  10658:             if ($cleaned_file =~ m{/}) {
                   10659:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10660:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10661:                 my $item = $fname;
                   10662:                 if ($path ne '') {
                   10663:                     $item = $path.'/'.$fname;
                   10664:                     $subdependencies{$path}{$fname} = 1;
                   10665:                 } else {
                   10666:                     $dependencies{$item} = 1;
                   10667:                 }
                   10668:                 if ($absolutepath) {
                   10669:                     $mapping{$item} = $absolutepath;
                   10670:                 } else {
                   10671:                     $mapping{$item} = $embed_file;
                   10672:                 }
                   10673:             } else {
                   10674:                 $dependencies{$embed_file} = 1;
                   10675:                 if ($absolutepath) {
1.1147    raeburn  10676:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10677:                 } else {
1.1147    raeburn  10678:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10679:                 }
                   10680:             }
1.984     raeburn  10681:         }
                   10682:     }
1.1071    raeburn  10683:     my $dirptr = 16384;
1.984     raeburn  10684:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10685:         $currsubfile{$path} = {};
1.1123    raeburn  10686:         if (($actionurl eq '/adm/portfolio') || 
                   10687:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10688:             my ($sublistref,$listerror) =
                   10689:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10690:             if (ref($sublistref) eq 'ARRAY') {
                   10691:                 foreach my $line (@{$sublistref}) {
                   10692:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10693:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10694:                 }
1.984     raeburn  10695:             }
1.987     raeburn  10696:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10697:             if (opendir(my $dir,$url.'/'.$path)) {
                   10698:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10699:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10700:             }
1.1084    raeburn  10701:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10702:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10703:                   ($args->{'context'} eq 'paste')) ||
                   10704:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10705:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  10706:                 my $dir;
                   10707:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10708:                     $dir = $fileloc;
                   10709:                 } else {
                   10710:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10711:                 }
1.1071    raeburn  10712:                 if ($dir ne '') {
                   10713:                     my ($sublistref,$listerror) =
                   10714:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10715:                     if (ref($sublistref) eq 'ARRAY') {
                   10716:                         foreach my $line (@{$sublistref}) {
                   10717:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10718:                                 undef,$mtime)=split(/\&/,$line,12);
                   10719:                             unless (($testdir&$dirptr) ||
                   10720:                                     ($file_name =~ /^\.\.?$/)) {
                   10721:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10722:                             }
                   10723:                         }
                   10724:                     }
                   10725:                 }
1.984     raeburn  10726:             }
                   10727:         }
                   10728:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10729:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10730:                 my $item = $path.'/'.$file;
                   10731:                 unless ($mapping{$item} eq $item) {
                   10732:                     $pathchanges{$item} = 1;
                   10733:                 }
                   10734:                 $existing{$item} = 1;
                   10735:                 $numexisting ++;
                   10736:             } else {
                   10737:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10738:             }
                   10739:         }
1.1071    raeburn  10740:         if ($actionurl eq '/adm/dependencies') {
                   10741:             foreach my $path (keys(%currsubfile)) {
                   10742:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10743:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10744:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  10745:                              next if (($rem ne '') &&
                   10746:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10747:                                        (ref($navmap) &&
                   10748:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10749:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10750:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10751:                              $unused{$path.'/'.$file} = 1; 
                   10752:                          }
                   10753:                     }
                   10754:                 }
                   10755:             }
                   10756:         }
1.984     raeburn  10757:     }
1.987     raeburn  10758:     my %currfile;
1.1123    raeburn  10759:     if (($actionurl eq '/adm/portfolio') ||
                   10760:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10761:         my ($dirlistref,$listerror) =
                   10762:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10763:         if (ref($dirlistref) eq 'ARRAY') {
                   10764:             foreach my $line (@{$dirlistref}) {
                   10765:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10766:                 $currfile{$file_name} = 1;
                   10767:             }
1.984     raeburn  10768:         }
1.987     raeburn  10769:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10770:         if (opendir(my $dir,$url)) {
1.987     raeburn  10771:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10772:             map {$currfile{$_} = 1;} @dir_list;
                   10773:         }
1.1084    raeburn  10774:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10775:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10776:               ($args->{'context'} eq 'paste')) ||
                   10777:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10778:         if ($env{'request.course.id'} ne '') {
                   10779:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10780:             if ($dir ne '') {
                   10781:                 my ($dirlistref,$listerror) =
                   10782:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10783:                 if (ref($dirlistref) eq 'ARRAY') {
                   10784:                     foreach my $line (@{$dirlistref}) {
                   10785:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10786:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10787:                         unless (($testdir&$dirptr) ||
                   10788:                                 ($file_name =~ /^\.\.?$/)) {
                   10789:                             $currfile{$file_name} = [$size,$mtime];
                   10790:                         }
                   10791:                     }
                   10792:                 }
                   10793:             }
                   10794:         }
1.984     raeburn  10795:     }
                   10796:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10797:         if (exists($currfile{$file})) {
1.987     raeburn  10798:             unless ($mapping{$file} eq $file) {
                   10799:                 $pathchanges{$file} = 1;
                   10800:             }
                   10801:             $existing{$file} = 1;
                   10802:             $numexisting ++;
                   10803:         } else {
1.984     raeburn  10804:             $newfiles{$file} = 1;
                   10805:         }
                   10806:     }
1.1071    raeburn  10807:     foreach my $file (keys(%currfile)) {
                   10808:         unless (($file eq $filename) ||
                   10809:                 ($file eq $filename.'.bak') ||
                   10810:                 ($dependencies{$file})) {
1.1085    raeburn  10811:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  10812:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10813:                     next if (($rem ne '') &&
                   10814:                              (($env{"httpref.$rem".$file} ne '') ||
                   10815:                               (ref($navmap) &&
                   10816:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10817:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10818:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10819:                 }
1.1085    raeburn  10820:             }
1.1071    raeburn  10821:             $unused{$file} = 1;
                   10822:         }
                   10823:     }
1.1084    raeburn  10824:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10825:         ($args->{'context'} eq 'paste')) {
                   10826:         $counter = scalar(keys(%existing));
                   10827:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  10828:         return ($output,$counter,$numpathchg,\%existing);
                   10829:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   10830:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10831:         $counter = scalar(keys(%existing));
                   10832:         $numpathchg = scalar(keys(%pathchanges));
                   10833:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  10834:     }
1.984     raeburn  10835:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10836:         if ($actionurl eq '/adm/dependencies') {
                   10837:             next if ($embed_file =~ m{^\w+://});
                   10838:         }
1.660     raeburn  10839:         $upload_output .= &start_data_table_row().
1.1123    raeburn  10840:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10841:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10842:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  10843:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10844:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10845:         }
1.1123    raeburn  10846:         $upload_output .= '</td>';
1.1071    raeburn  10847:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  10848:             $upload_output.='<td align="right">'.
                   10849:                             '<span class="LC_info LC_fontsize_medium">'.
                   10850:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10851:             $numremref++;
1.660     raeburn  10852:         } elsif ($args->{'error_on_invalid_names'}
                   10853:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  10854:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10855:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10856:             $numinvalid++;
1.660     raeburn  10857:         } else {
1.1123    raeburn  10858:             $upload_output .= '<td>'.
                   10859:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10860:                                                      $embed_file,\%mapping,
1.1071    raeburn  10861:                                                      $allfiles,$codebase,'upload');
                   10862:             $counter ++;
                   10863:             $numnew ++;
1.987     raeburn  10864:         }
                   10865:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10866:     }
                   10867:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10868:         if ($actionurl eq '/adm/dependencies') {
                   10869:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10870:             $modify_output .= &start_data_table_row().
                   10871:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10872:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10873:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10874:                               '<td>'.$size.'</td>'.
                   10875:                               '<td>'.$mtime.'</td>'.
                   10876:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10877:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10878:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10879:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10880:                               &embedded_file_element('upload_embedded',$counter,
                   10881:                                                      $embed_file,\%mapping,
                   10882:                                                      $allfiles,$codebase,'modify').
                   10883:                               '</div></td>'.
                   10884:                               &end_data_table_row()."\n";
                   10885:             $counter ++;
                   10886:         } else {
                   10887:             $upload_output .= &start_data_table_row().
1.1123    raeburn  10888:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10889:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10890:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10891:                               &Apache::loncommon::end_data_table_row()."\n";
                   10892:         }
                   10893:     }
                   10894:     my $delidx = $counter;
                   10895:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10896:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10897:         $delete_output .= &start_data_table_row().
                   10898:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10899:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10900:                           '<td>'.$size.'</td>'.
                   10901:                           '<td>'.$mtime.'</td>'.
                   10902:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10903:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10904:                           &embedded_file_element('upload_embedded',$delidx,
                   10905:                                                  $oldfile,\%mapping,$allfiles,
                   10906:                                                  $codebase,'delete').'</td>'.
                   10907:                           &end_data_table_row()."\n"; 
                   10908:         $numunused ++;
                   10909:         $delidx ++;
1.987     raeburn  10910:     }
                   10911:     if ($upload_output) {
                   10912:         $upload_output = &start_data_table().
                   10913:                          $upload_output.
                   10914:                          &end_data_table()."\n";
                   10915:     }
1.1071    raeburn  10916:     if ($modify_output) {
                   10917:         $modify_output = &start_data_table().
                   10918:                          &start_data_table_header_row().
                   10919:                          '<th>'.&mt('File').'</th>'.
                   10920:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10921:                          '<th>'.&mt('Modified').'</th>'.
                   10922:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10923:                          &end_data_table_header_row().
                   10924:                          $modify_output.
                   10925:                          &end_data_table()."\n";
                   10926:     }
                   10927:     if ($delete_output) {
                   10928:         $delete_output = &start_data_table().
                   10929:                          &start_data_table_header_row().
                   10930:                          '<th>'.&mt('File').'</th>'.
                   10931:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10932:                          '<th>'.&mt('Modified').'</th>'.
                   10933:                          '<th>'.&mt('Delete?').'</th>'.
                   10934:                          &end_data_table_header_row().
                   10935:                          $delete_output.
                   10936:                          &end_data_table()."\n";
                   10937:     }
1.987     raeburn  10938:     my $applies = 0;
                   10939:     if ($numremref) {
                   10940:         $applies ++;
                   10941:     }
                   10942:     if ($numinvalid) {
                   10943:         $applies ++;
                   10944:     }
                   10945:     if ($numexisting) {
                   10946:         $applies ++;
                   10947:     }
1.1071    raeburn  10948:     if ($counter || $numunused) {
1.987     raeburn  10949:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10950:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10951:                   $state.'<h3>'.$heading.'</h3>'; 
                   10952:         if ($actionurl eq '/adm/dependencies') {
                   10953:             if ($numnew) {
                   10954:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10955:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10956:                            $upload_output.'<br />'."\n";
                   10957:             }
                   10958:             if ($numexisting) {
                   10959:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10960:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10961:                            $modify_output.'<br />'."\n";
                   10962:                            $buttontext = &mt('Save changes');
                   10963:             }
                   10964:             if ($numunused) {
                   10965:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10966:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10967:                            $delete_output.'<br />'."\n";
                   10968:                            $buttontext = &mt('Save changes');
                   10969:             }
                   10970:         } else {
                   10971:             $output .= $upload_output.'<br />'."\n";
                   10972:         }
                   10973:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10974:                    $counter.'" />'."\n";
                   10975:         if ($actionurl eq '/adm/dependencies') { 
                   10976:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10977:                        $numnew.'" />'."\n";
                   10978:         } elsif ($actionurl eq '') {
1.987     raeburn  10979:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10980:         }
                   10981:     } elsif ($applies) {
                   10982:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10983:         if ($applies > 1) {
                   10984:             $output .=  
1.1123    raeburn  10985:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10986:             if ($numremref) {
                   10987:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10988:             }
                   10989:             if ($numinvalid) {
                   10990:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10991:             }
                   10992:             if ($numexisting) {
                   10993:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10994:             }
                   10995:             $output .= '</ul><br />';
                   10996:         } elsif ($numremref) {
                   10997:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10998:         } elsif ($numinvalid) {
                   10999:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11000:         } elsif ($numexisting) {
                   11001:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11002:         }
                   11003:         $output .= $upload_output.'<br />';
                   11004:     }
                   11005:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11006:     $chgcount = $counter;
1.987     raeburn  11007:     if (keys(%pathchanges) > 0) {
                   11008:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11009:             if ($counter) {
1.987     raeburn  11010:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11011:                                                   $embed_file,\%mapping,
1.1071    raeburn  11012:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11013:             } else {
                   11014:                 $pathchange_output .= 
                   11015:                     &start_data_table_row().
                   11016:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11017:                     $chgcount.'" checked="checked" /></td>'.
                   11018:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11019:                     '<td>'.$embed_file.
                   11020:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11021:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11022:                     '</td>'.&end_data_table_row();
1.660     raeburn  11023:             }
1.987     raeburn  11024:             $numpathchg ++;
                   11025:             $chgcount ++;
1.660     raeburn  11026:         }
                   11027:     }
1.1127    raeburn  11028:     if (($counter) || ($numunused)) {
1.987     raeburn  11029:         if ($numpathchg) {
                   11030:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11031:                        $numpathchg.'" />'."\n";
                   11032:         }
                   11033:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11034:             ($actionurl eq '/adm/imsimport')) {
                   11035:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11036:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11037:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11038:         } elsif ($actionurl eq '/adm/dependencies') {
                   11039:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11040:         }
1.1123    raeburn  11041:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11042:     } elsif ($numpathchg) {
                   11043:         my %pathchange = ();
                   11044:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11045:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11046:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11047:         }
1.987     raeburn  11048:     }
1.1071    raeburn  11049:     return ($output,$counter,$numpathchg);
1.987     raeburn  11050: }
                   11051: 
1.1147    raeburn  11052: =pod
                   11053: 
                   11054: =item * clean_path($name)
                   11055: 
                   11056: Performs clean-up of directories, subdirectories and filename in an
                   11057: embedded object, referenced in an HTML file which is being uploaded
                   11058: to a course or portfolio, where 
                   11059: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11060: checked.
                   11061: 
                   11062: Clean-up is similar to replacements in lonnet::clean_filename()
                   11063: except each / between sub-directory and next level is preserved.
                   11064: 
                   11065: =cut
                   11066: 
                   11067: sub clean_path {
                   11068:     my ($embed_file) = @_;
                   11069:     $embed_file =~s{^/+}{};
                   11070:     my @contents;
                   11071:     if ($embed_file =~ m{/}) {
                   11072:         @contents = split(/\//,$embed_file);
                   11073:     } else {
                   11074:         @contents = ($embed_file);
                   11075:     }
                   11076:     my $lastidx = scalar(@contents)-1;
                   11077:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11078:         $contents[$i]=~s{\\}{/}g;
                   11079:         $contents[$i]=~s/\s+/\_/g;
                   11080:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11081:         if ($i == $lastidx) {
                   11082:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11083:         }
                   11084:     }
                   11085:     if ($lastidx > 0) {
                   11086:         return join('/',@contents);
                   11087:     } else {
                   11088:         return $contents[0];
                   11089:     }
                   11090: }
                   11091: 
1.987     raeburn  11092: sub embedded_file_element {
1.1071    raeburn  11093:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11094:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11095:                    (ref($codebase) eq 'HASH'));
                   11096:     my $output;
1.1071    raeburn  11097:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11098:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11099:     }
                   11100:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11101:                &escape($embed_file).'" />';
                   11102:     unless (($context eq 'upload_embedded') && 
                   11103:             ($mapping->{$embed_file} eq $embed_file)) {
                   11104:         $output .='
                   11105:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11106:     }
                   11107:     my $attrib;
                   11108:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11109:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11110:     }
                   11111:     $output .=
                   11112:         "\n\t\t".
                   11113:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11114:         $attrib.'" />';
                   11115:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11116:         $output .=
                   11117:             "\n\t\t".
                   11118:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11119:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11120:     }
1.987     raeburn  11121:     return $output;
1.660     raeburn  11122: }
                   11123: 
1.1071    raeburn  11124: sub get_dependency_details {
                   11125:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11126:     my ($size,$mtime,$showsize,$showmtime);
                   11127:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11128:         if ($embed_file =~ m{/}) {
                   11129:             my ($path,$fname) = split(/\//,$embed_file);
                   11130:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11131:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11132:             }
                   11133:         } else {
                   11134:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11135:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11136:             }
                   11137:         }
                   11138:         $showsize = $size/1024.0;
                   11139:         $showsize = sprintf("%.1f",$showsize);
                   11140:         if ($mtime > 0) {
                   11141:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11142:         }
                   11143:     }
                   11144:     return ($showsize,$showmtime);
                   11145: }
                   11146: 
                   11147: sub ask_embedded_js {
                   11148:     return <<"END";
                   11149: <script type="text/javascript"">
                   11150: // <![CDATA[
                   11151: function toggleBrowse(counter) {
                   11152:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11153:     var fileid = document.getElementById('embedded_item_'+counter);
                   11154:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11155:     if (chkboxid.checked == true) {
                   11156:         uploaddivid.style.display='block';
                   11157:     } else {
                   11158:         uploaddivid.style.display='none';
                   11159:         fileid.value = '';
                   11160:     }
                   11161: }
                   11162: // ]]>
                   11163: </script>
                   11164: 
                   11165: END
                   11166: }
                   11167: 
1.661     raeburn  11168: sub upload_embedded {
                   11169:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11170:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11171:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11172:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11173:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11174:         my $orig_uploaded_filename =
                   11175:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11176:         foreach my $type ('orig','ref','attrib','codebase') {
                   11177:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11178:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11179:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11180:             }
                   11181:         }
1.661     raeburn  11182:         my ($path,$fname) =
                   11183:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11184:         # no path, whole string is fname
                   11185:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11186:         $fname = &Apache::lonnet::clean_filename($fname);
                   11187:         # See if there is anything left
                   11188:         next if ($fname eq '');
                   11189: 
                   11190:         # Check if file already exists as a file or directory.
                   11191:         my ($state,$msg);
                   11192:         if ($context eq 'portfolio') {
                   11193:             my $port_path = $dirpath;
                   11194:             if ($group ne '') {
                   11195:                 $port_path = "groups/$group/$port_path";
                   11196:             }
1.987     raeburn  11197:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11198:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11199:                                               $dir_root,$port_path,$disk_quota,
                   11200:                                               $current_disk_usage,$uname,$udom);
                   11201:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11202:                 || $state eq 'file_locked') {
1.661     raeburn  11203:                 $output .= $msg;
                   11204:                 next;
                   11205:             }
                   11206:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11207:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11208:             if ($state eq 'exists') {
                   11209:                 $output .= $msg;
                   11210:                 next;
                   11211:             }
                   11212:         }
                   11213:         # Check if extension is valid
                   11214:         if (($fname =~ /\.(\w+)$/) &&
                   11215:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   11216:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11217:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11218:             next;
                   11219:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11220:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11221:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11222:             next;
                   11223:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   11224:             $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  11225:             next;
                   11226:         }
                   11227:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  11228:         my $subdir = $path;
                   11229:         $subdir =~ s{/+$}{};
1.661     raeburn  11230:         if ($context eq 'portfolio') {
1.984     raeburn  11231:             my $result;
                   11232:             if ($state eq 'existingfile') {
                   11233:                 $result=
                   11234:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  11235:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11236:             } else {
1.984     raeburn  11237:                 $result=
                   11238:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11239:                                                     $dirpath.
1.1123    raeburn  11240:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11241:                 if ($result !~ m|^/uploaded/|) {
                   11242:                     $output .= '<span class="LC_error">'
                   11243:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11244:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11245:                                .'</span><br />';
                   11246:                     next;
                   11247:                 } else {
1.987     raeburn  11248:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11249:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11250:                 }
1.661     raeburn  11251:             }
1.1123    raeburn  11252:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  11253:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11254:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11255:             my $result =
1.1126    raeburn  11256:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11257:             if ($result !~ m|^/uploaded/|) {
                   11258:                 $output .= '<span class="LC_error">'
                   11259:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11260:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11261:                            .'</span><br />';
                   11262:                     next;
                   11263:             } else {
                   11264:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11265:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11266:                 if ($context eq 'syllabus') {
                   11267:                     &Apache::lonnet::make_public_indefinitely($result);
                   11268:                 }
1.987     raeburn  11269:             }
1.661     raeburn  11270:         } else {
                   11271: # Save the file
                   11272:             my $target = $env{'form.embedded_item_'.$i};
                   11273:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11274:             my $dest = $fullpath.$fname;
                   11275:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11276:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11277:             my $count;
                   11278:             my $filepath = $dir_root;
1.1027    raeburn  11279:             foreach my $subdir (@parts) {
                   11280:                 $filepath .= "/$subdir";
                   11281:                 if (!-e $filepath) {
1.661     raeburn  11282:                     mkdir($filepath,0770);
                   11283:                 }
                   11284:             }
                   11285:             my $fh;
                   11286:             if (!open($fh,'>'.$dest)) {
                   11287:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11288:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11289:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11290:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11291:                            '</span><br />';
                   11292:             } else {
                   11293:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11294:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11295:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11296:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11297:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11298:                               '</span><br />';
                   11299:                 } else {
1.987     raeburn  11300:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11301:                                $url.'</span>').'<br />';
                   11302:                     unless ($context eq 'testbank') {
                   11303:                         $footer .= &mt('View embedded file: [_1]',
                   11304:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11305:                     }
                   11306:                 }
                   11307:                 close($fh);
                   11308:             }
                   11309:         }
                   11310:         if ($env{'form.embedded_ref_'.$i}) {
                   11311:             $pathchange{$i} = 1;
                   11312:         }
                   11313:     }
                   11314:     if ($output) {
                   11315:         $output = '<p>'.$output.'</p>';
                   11316:     }
                   11317:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11318:     $returnflag = 'ok';
1.1071    raeburn  11319:     my $numpathchgs = scalar(keys(%pathchange));
                   11320:     if ($numpathchgs > 0) {
1.987     raeburn  11321:         if ($context eq 'portfolio') {
                   11322:             $output .= '<p>'.&mt('or').'</p>';
                   11323:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11324:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11325:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11326:             $returnflag = 'modify_orightml';
                   11327:         }
                   11328:     }
1.1071    raeburn  11329:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11330: }
                   11331: 
                   11332: sub modify_html_form {
                   11333:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11334:     my $end = 0;
                   11335:     my $modifyform;
                   11336:     if ($context eq 'upload_embedded') {
                   11337:         return unless (ref($pathchange) eq 'HASH');
                   11338:         if ($env{'form.number_embedded_items'}) {
                   11339:             $end += $env{'form.number_embedded_items'};
                   11340:         }
                   11341:         if ($env{'form.number_pathchange_items'}) {
                   11342:             $end += $env{'form.number_pathchange_items'};
                   11343:         }
                   11344:         if ($end) {
                   11345:             for (my $i=0; $i<$end; $i++) {
                   11346:                 if ($i < $env{'form.number_embedded_items'}) {
                   11347:                     next unless($pathchange->{$i});
                   11348:                 }
                   11349:                 $modifyform .=
                   11350:                     &start_data_table_row().
                   11351:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11352:                     'checked="checked" /></td>'.
                   11353:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11354:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11355:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11356:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11357:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11358:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11359:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11360:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11361:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11362:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11363:                     &end_data_table_row();
1.1071    raeburn  11364:             }
1.987     raeburn  11365:         }
                   11366:     } else {
                   11367:         $modifyform = $pathchgtable;
                   11368:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11369:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11370:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11371:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11372:         }
                   11373:     }
                   11374:     if ($modifyform) {
1.1071    raeburn  11375:         if ($actionurl eq '/adm/dependencies') {
                   11376:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11377:         }
1.987     raeburn  11378:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11379:                '<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".
                   11380:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11381:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11382:                '</ol></p>'."\n".'<p>'.
                   11383:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11384:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11385:                &start_data_table()."\n".
                   11386:                &start_data_table_header_row().
                   11387:                '<th>'.&mt('Change?').'</th>'.
                   11388:                '<th>'.&mt('Current reference').'</th>'.
                   11389:                '<th>'.&mt('Required reference').'</th>'.
                   11390:                &end_data_table_header_row()."\n".
                   11391:                $modifyform.
                   11392:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11393:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11394:                '</form>'."\n";
                   11395:     }
                   11396:     return;
                   11397: }
                   11398: 
                   11399: sub modify_html_refs {
1.1123    raeburn  11400:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11401:     my $container;
                   11402:     if ($context eq 'portfolio') {
                   11403:         $container = $env{'form.container'};
                   11404:     } elsif ($context eq 'coursedoc') {
                   11405:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11406:     } elsif ($context eq 'manage_dependencies') {
                   11407:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11408:         $container = "/$container";
1.1123    raeburn  11409:     } elsif ($context eq 'syllabus') {
                   11410:         $container = $url;
1.987     raeburn  11411:     } else {
1.1027    raeburn  11412:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11413:     }
                   11414:     my (%allfiles,%codebase,$output,$content);
                   11415:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  11416:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  11417:         if (wantarray) {
                   11418:             return ('',0,0); 
                   11419:         } else {
                   11420:             return;
                   11421:         }
                   11422:     }
                   11423:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11424:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11425:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11426:             if (wantarray) {
                   11427:                 return ('',0,0);
                   11428:             } else {
                   11429:                 return;
                   11430:             }
                   11431:         } 
1.987     raeburn  11432:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11433:         if ($content eq '-1') {
                   11434:             if (wantarray) {
                   11435:                 return ('',0,0);
                   11436:             } else {
                   11437:                 return;
                   11438:             }
                   11439:         }
1.987     raeburn  11440:     } else {
1.1071    raeburn  11441:         unless ($container =~ /^\Q$dir_root\E/) {
                   11442:             if (wantarray) {
                   11443:                 return ('',0,0);
                   11444:             } else {
                   11445:                 return;
                   11446:             }
                   11447:         } 
1.987     raeburn  11448:         if (open(my $fh,"<$container")) {
                   11449:             $content = join('', <$fh>);
                   11450:             close($fh);
                   11451:         } else {
1.1071    raeburn  11452:             if (wantarray) {
                   11453:                 return ('',0,0);
                   11454:             } else {
                   11455:                 return;
                   11456:             }
1.987     raeburn  11457:         }
                   11458:     }
                   11459:     my ($count,$codebasecount) = (0,0);
                   11460:     my $mm = new File::MMagic;
                   11461:     my $mime_type = $mm->checktype_contents($content);
                   11462:     if ($mime_type eq 'text/html') {
                   11463:         my $parse_result = 
                   11464:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11465:                                                     \%codebase,\$content);
                   11466:         if ($parse_result eq 'ok') {
                   11467:             foreach my $i (@changes) {
                   11468:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11469:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11470:                 if ($allfiles{$ref}) {
                   11471:                     my $newname =  $orig;
                   11472:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11473:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11474:                     if ($attrib_regexp =~ /:/) {
                   11475:                         $attrib_regexp =~ s/\:/|/g;
                   11476:                     }
                   11477:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11478:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11479:                         $count += $numchg;
1.1123    raeburn  11480:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  11481:                         delete($allfiles{$ref});
1.987     raeburn  11482:                     }
                   11483:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11484:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11485:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11486:                         $codebasecount ++;
                   11487:                     }
                   11488:                 }
                   11489:             }
1.1123    raeburn  11490:             my $skiprewrites;
1.987     raeburn  11491:             if ($count || $codebasecount) {
                   11492:                 my $saveresult;
1.1071    raeburn  11493:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11494:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11495:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11496:                     if ($url eq $container) {
                   11497:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11498:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11499:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11500:                                             $fname.'</span>').'</p>';
1.987     raeburn  11501:                     } else {
                   11502:                          $output = '<p class="LC_error">'.
                   11503:                                    &mt('Error: update failed for: [_1].',
                   11504:                                    '<span class="LC_filename">'.
                   11505:                                    $container.'</span>').'</p>';
                   11506:                     }
1.1123    raeburn  11507:                     if ($context eq 'syllabus') {
                   11508:                         unless ($saveresult eq 'ok') {
                   11509:                             $skiprewrites = 1;
                   11510:                         }
                   11511:                     }
1.987     raeburn  11512:                 } else {
                   11513:                     if (open(my $fh,">$container")) {
                   11514:                         print $fh $content;
                   11515:                         close($fh);
                   11516:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11517:                                   $count,'<span class="LC_filename">'.
                   11518:                                   $container.'</span>').'</p>';
1.661     raeburn  11519:                     } else {
1.987     raeburn  11520:                          $output = '<p class="LC_error">'.
                   11521:                                    &mt('Error: could not update [_1].',
                   11522:                                    '<span class="LC_filename">'.
                   11523:                                    $container.'</span>').'</p>';
1.661     raeburn  11524:                     }
                   11525:                 }
                   11526:             }
1.1123    raeburn  11527:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11528:                 my ($actionurl,$state);
                   11529:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11530:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11531:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11532:                                               \%codebase,
                   11533:                                               {'context' => 'rewrites',
                   11534:                                                'ignore_remote_references' => 1,});
                   11535:                 if (ref($mapping) eq 'HASH') {
                   11536:                     my $rewrites = 0;
                   11537:                     foreach my $key (keys(%{$mapping})) {
                   11538:                         next if ($key =~ m{^https?://});
                   11539:                         my $ref = $mapping->{$key};
                   11540:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11541:                         my $attrib;
                   11542:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11543:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11544:                         }
                   11545:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11546:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11547:                             $rewrites += $numchg;
                   11548:                         }
                   11549:                     }
                   11550:                     if ($rewrites) {
                   11551:                         my $saveresult; 
                   11552:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11553:                         if ($url eq $container) {
                   11554:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11555:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11556:                                             $count,'<span class="LC_filename">'.
                   11557:                                             $fname.'</span>').'</p>';
                   11558:                         } else {
                   11559:                             $output .= '<p class="LC_error">'.
                   11560:                                        &mt('Error: could not update links in [_1].',
                   11561:                                        '<span class="LC_filename">'.
                   11562:                                        $container.'</span>').'</p>';
                   11563: 
                   11564:                         }
                   11565:                     }
                   11566:                 }
                   11567:             }
1.987     raeburn  11568:         } else {
                   11569:             &logthis('Failed to parse '.$container.
                   11570:                      ' to modify references: '.$parse_result);
1.661     raeburn  11571:         }
                   11572:     }
1.1071    raeburn  11573:     if (wantarray) {
                   11574:         return ($output,$count,$codebasecount);
                   11575:     } else {
                   11576:         return $output;
                   11577:     }
1.661     raeburn  11578: }
                   11579: 
                   11580: sub check_for_existing {
                   11581:     my ($path,$fname,$element) = @_;
                   11582:     my ($state,$msg);
                   11583:     if (-d $path.'/'.$fname) {
                   11584:         $state = 'exists';
                   11585:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11586:     } elsif (-e $path.'/'.$fname) {
                   11587:         $state = 'exists';
                   11588:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11589:     }
                   11590:     if ($state eq 'exists') {
                   11591:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11592:     }
                   11593:     return ($state,$msg);
                   11594: }
                   11595: 
                   11596: sub check_for_upload {
                   11597:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11598:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11599:     my $filesize = length($env{'form.'.$element});
                   11600:     if (!$filesize) {
                   11601:         my $msg = '<span class="LC_error">'.
                   11602:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11603:                       '<span class="LC_filename">'.$fname.'</span>',
                   11604:                       $filesize).'<br />'.
1.1007    raeburn  11605:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11606:                   '</span>';
                   11607:         return ('zero_bytes',$msg);
                   11608:     }
                   11609:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11610:     my $getpropath = 1;
1.1021    raeburn  11611:     my ($dirlistref,$listerror) =
                   11612:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11613:     my $found_file = 0;
                   11614:     my $locked_file = 0;
1.991     raeburn  11615:     my @lockers;
                   11616:     my $navmap;
                   11617:     if ($env{'request.course.id'}) {
                   11618:         $navmap = Apache::lonnavmaps::navmap->new();
                   11619:     }
1.1021    raeburn  11620:     if (ref($dirlistref) eq 'ARRAY') {
                   11621:         foreach my $line (@{$dirlistref}) {
                   11622:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11623:             if ($file_name eq $fname){
                   11624:                 $file_name = $path.$file_name;
                   11625:                 if ($group ne '') {
                   11626:                     $file_name = $group.$file_name;
                   11627:                 }
                   11628:                 $found_file = 1;
                   11629:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11630:                     foreach my $lock (@lockers) {
                   11631:                         if (ref($lock) eq 'ARRAY') {
                   11632:                             my ($symb,$crsid) = @{$lock};
                   11633:                             if ($crsid eq $env{'request.course.id'}) {
                   11634:                                 if (ref($navmap)) {
                   11635:                                     my $res = $navmap->getBySymb($symb);
                   11636:                                     foreach my $part (@{$res->parts()}) { 
                   11637:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11638:                                         unless (($slot_status == $res->RESERVED) ||
                   11639:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11640:                                             $locked_file = 1;
                   11641:                                         }
1.991     raeburn  11642:                                     }
1.1021    raeburn  11643:                                 } else {
                   11644:                                     $locked_file = 1;
1.991     raeburn  11645:                                 }
                   11646:                             } else {
                   11647:                                 $locked_file = 1;
                   11648:                             }
                   11649:                         }
1.1021    raeburn  11650:                    }
                   11651:                 } else {
                   11652:                     my @info = split(/\&/,$rest);
                   11653:                     my $currsize = $info[6]/1000;
                   11654:                     if ($currsize < $filesize) {
                   11655:                         my $extra = $filesize - $currsize;
                   11656:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   11657:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11658:                                       &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   11659:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11660:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11661:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11662:                             return ('will_exceed_quota',$msg);
                   11663:                         }
1.984     raeburn  11664:                     }
                   11665:                 }
1.661     raeburn  11666:             }
                   11667:         }
                   11668:     }
                   11669:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   11670:         my $msg = '<p class="LC_warning">'.
                   11671:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  11672:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11673:         return ('will_exceed_quota',$msg);
                   11674:     } elsif ($found_file) {
                   11675:         if ($locked_file) {
1.1179    bisitz   11676:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11677:             $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   11678:             $msg .= '</p>';
1.661     raeburn  11679:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11680:             return ('file_locked',$msg);
                   11681:         } else {
1.1179    bisitz   11682:             my $msg = '<p class="LC_error">';
1.984     raeburn  11683:             $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   11684:             $msg .= '</p>';
1.984     raeburn  11685:             return ('existingfile',$msg);
1.661     raeburn  11686:         }
                   11687:     }
                   11688: }
                   11689: 
1.987     raeburn  11690: sub check_for_traversal {
                   11691:     my ($path,$url,$toplevel) = @_;
                   11692:     my @parts=split(/\//,$path);
                   11693:     my $cleanpath;
                   11694:     my $fullpath = $url;
                   11695:     for (my $i=0;$i<@parts;$i++) {
                   11696:         next if ($parts[$i] eq '.');
                   11697:         if ($parts[$i] eq '..') {
                   11698:             $fullpath =~ s{([^/]+/)$}{};
                   11699:         } else {
                   11700:             $fullpath .= $parts[$i].'/';
                   11701:         }
                   11702:     }
                   11703:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11704:         $cleanpath = $1;
                   11705:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11706:         my $curr_toprel = $1;
                   11707:         my @parts = split(/\//,$curr_toprel);
                   11708:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11709:         my @urlparts = split(/\//,$url_toprel);
                   11710:         my $doubledots;
                   11711:         my $startdiff = -1;
                   11712:         for (my $i=0; $i<@urlparts; $i++) {
                   11713:             if ($startdiff == -1) {
                   11714:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11715:                     $startdiff = $i;
                   11716:                     $doubledots .= '../';
                   11717:                 }
                   11718:             } else {
                   11719:                 $doubledots .= '../';
                   11720:             }
                   11721:         }
                   11722:         if ($startdiff > -1) {
                   11723:             $cleanpath = $doubledots;
                   11724:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11725:                 $cleanpath .= $parts[$i].'/';
                   11726:             }
                   11727:         }
                   11728:     }
                   11729:     $cleanpath =~ s{(/)$}{};
                   11730:     return $cleanpath;
                   11731: }
1.31      albertel 11732: 
1.1053    raeburn  11733: sub is_archive_file {
                   11734:     my ($mimetype) = @_;
                   11735:     if (($mimetype eq 'application/octet-stream') ||
                   11736:         ($mimetype eq 'application/x-stuffit') ||
                   11737:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11738:         return 1;
                   11739:     }
                   11740:     return;
                   11741: }
                   11742: 
                   11743: sub decompress_form {
1.1065    raeburn  11744:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11745:     my %lt = &Apache::lonlocal::texthash (
                   11746:         this => 'This file is an archive file.',
1.1067    raeburn  11747:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11748:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11749:         youm => 'You may wish to extract its contents.',
                   11750:         extr => 'Extract contents',
1.1067    raeburn  11751:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11752:         proa => 'Process automatically?',
1.1053    raeburn  11753:         yes  => 'Yes',
                   11754:         no   => 'No',
1.1067    raeburn  11755:         fold => 'Title for folder containing movie',
                   11756:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11757:     );
1.1065    raeburn  11758:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11759:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11760:     my $info = &list_archive_contents($fileloc,\@paths);
                   11761:     if (@paths) {
                   11762:         foreach my $path (@paths) {
                   11763:             $path =~ s{^/}{};
1.1067    raeburn  11764:             if ($path =~ m{^([^/]+)/$}) {
                   11765:                 $topdir = $1;
                   11766:             }
1.1065    raeburn  11767:             if ($path =~ m{^([^/]+)/}) {
                   11768:                 $toplevel{$1} = $path;
                   11769:             } else {
                   11770:                 $toplevel{$path} = $path;
                   11771:             }
                   11772:         }
                   11773:     }
1.1067    raeburn  11774:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  11775:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11776:                         "$topdir/media/",
                   11777:                         "$topdir/media/$topdir.mp4",
                   11778:                         "$topdir/media/FirstFrame.png",
                   11779:                         "$topdir/media/player.swf",
                   11780:                         "$topdir/media/swfobject.js",
                   11781:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  11782:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  11783:                          "$topdir/$topdir.mp4",
                   11784:                          "$topdir/$topdir\_config.xml",
                   11785:                          "$topdir/$topdir\_controller.swf",
                   11786:                          "$topdir/$topdir\_embed.css",
                   11787:                          "$topdir/$topdir\_First_Frame.png",
                   11788:                          "$topdir/$topdir\_player.html",
                   11789:                          "$topdir/$topdir\_Thumbnails.png",
                   11790:                          "$topdir/playerProductInstall.swf",
                   11791:                          "$topdir/scripts/",
                   11792:                          "$topdir/scripts/config_xml.js",
                   11793:                          "$topdir/scripts/handlebars.js",
                   11794:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11795:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11796:                          "$topdir/scripts/modernizr.js",
                   11797:                          "$topdir/scripts/player-min.js",
                   11798:                          "$topdir/scripts/swfobject.js",
                   11799:                          "$topdir/skins/",
                   11800:                          "$topdir/skins/configuration_express.xml",
                   11801:                          "$topdir/skins/express_show/",
                   11802:                          "$topdir/skins/express_show/player-min.css",
                   11803:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  11804:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11805:                          "$topdir/$topdir.mp4",
                   11806:                          "$topdir/$topdir\_config.xml",
                   11807:                          "$topdir/$topdir\_controller.swf",
                   11808:                          "$topdir/$topdir\_embed.css",
                   11809:                          "$topdir/$topdir\_First_Frame.png",
                   11810:                          "$topdir/$topdir\_player.html",
                   11811:                          "$topdir/$topdir\_Thumbnails.png",
                   11812:                          "$topdir/playerProductInstall.swf",
                   11813:                          "$topdir/scripts/",
                   11814:                          "$topdir/scripts/config_xml.js",
                   11815:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11816:                          "$topdir/skins/",
                   11817:                          "$topdir/skins/configuration_express.xml",
                   11818:                          "$topdir/skins/express_show/",
                   11819:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11820:                          "$topdir/skins/express_show/spritesheet.png",
                   11821:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  11822:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11823:         if (@diffs == 0) {
1.1164    raeburn  11824:             $is_camtasia = 6;
                   11825:         } else {
1.1197    raeburn  11826:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  11827:             if (@diffs == 0) {
                   11828:                 $is_camtasia = 8;
1.1197    raeburn  11829:             } else {
                   11830:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11831:                 if (@diffs == 0) {
                   11832:                     $is_camtasia = 8;
                   11833:                 }
1.1164    raeburn  11834:             }
1.1067    raeburn  11835:         }
                   11836:     }
                   11837:     my $output;
                   11838:     if ($is_camtasia) {
                   11839:         $output = <<"ENDCAM";
                   11840: <script type="text/javascript" language="Javascript">
                   11841: // <![CDATA[
                   11842: 
                   11843: function camtasiaToggle() {
                   11844:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11845:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  11846:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11847:                 document.getElementById('camtasia_titles').style.display='block';
                   11848:             } else {
                   11849:                 document.getElementById('camtasia_titles').style.display='none';
                   11850:             }
                   11851:         }
                   11852:     }
                   11853:     return;
                   11854: }
                   11855: 
                   11856: // ]]>
                   11857: </script>
                   11858: <p>$lt{'camt'}</p>
                   11859: ENDCAM
1.1065    raeburn  11860:     } else {
1.1067    raeburn  11861:         $output = '<p>'.$lt{'this'};
                   11862:         if ($info eq '') {
                   11863:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11864:         } else {
                   11865:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11866:                        '<div><pre>'.$info.'</pre></div>';
                   11867:         }
1.1065    raeburn  11868:     }
1.1067    raeburn  11869:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11870:     my $duplicates;
                   11871:     my $num = 0;
                   11872:     if (ref($dirlist) eq 'ARRAY') {
                   11873:         foreach my $item (@{$dirlist}) {
                   11874:             if (ref($item) eq 'ARRAY') {
                   11875:                 if (exists($toplevel{$item->[0]})) {
                   11876:                     $duplicates .= 
                   11877:                         &start_data_table_row().
                   11878:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11879:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11880:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11881:                         'value="1" />'.&mt('Yes').'</label>'.
                   11882:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11883:                         '<td>'.$item->[0].'</td>';
                   11884:                     if ($item->[2]) {
                   11885:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11886:                     } else {
                   11887:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11888:                     }
                   11889:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11890:                                    '<td>'.
                   11891:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11892:                                    '</td>'.
                   11893:                                    &end_data_table_row();
                   11894:                     $num ++;
                   11895:                 }
                   11896:             }
                   11897:         }
                   11898:     }
                   11899:     my $itemcount;
                   11900:     if (@paths > 0) {
                   11901:         $itemcount = scalar(@paths);
                   11902:     } else {
                   11903:         $itemcount = 1;
                   11904:     }
1.1067    raeburn  11905:     if ($is_camtasia) {
                   11906:         $output .= $lt{'auto'}.'<br />'.
                   11907:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  11908:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11909:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11910:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11911:                    $lt{'no'}.'</label></span><br />'.
                   11912:                    '<div id="camtasia_titles" style="display:block">'.
                   11913:                    &Apache::lonhtmlcommon::start_pick_box().
                   11914:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11915:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11916:                    &Apache::lonhtmlcommon::row_closure().
                   11917:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11918:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11919:                    &Apache::lonhtmlcommon::row_closure(1).
                   11920:                    &Apache::lonhtmlcommon::end_pick_box().
                   11921:                    '</div>';
                   11922:     }
1.1065    raeburn  11923:     $output .= 
                   11924:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11925:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11926:         "\n";
1.1065    raeburn  11927:     if ($duplicates ne '') {
                   11928:         $output .= '<p><span class="LC_warning">'.
                   11929:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11930:                    &start_data_table().
                   11931:                    &start_data_table_header_row().
                   11932:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11933:                    '<th>'.&mt('Name').'</th>'.
                   11934:                    '<th>'.&mt('Type').'</th>'.
                   11935:                    '<th>'.&mt('Size').'</th>'.
                   11936:                    '<th>'.&mt('Last modified').'</th>'.
                   11937:                    &end_data_table_header_row().
                   11938:                    $duplicates.
                   11939:                    &end_data_table().
                   11940:                    '</p>';
                   11941:     }
1.1067    raeburn  11942:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11943:     if (ref($hiddenelements) eq 'HASH') {
                   11944:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11945:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11946:         }
                   11947:     }
                   11948:     $output .= <<"END";
1.1067    raeburn  11949: <br />
1.1053    raeburn  11950: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11951: </form>
                   11952: $noextract
                   11953: END
                   11954:     return $output;
                   11955: }
                   11956: 
1.1065    raeburn  11957: sub decompression_utility {
                   11958:     my ($program) = @_;
                   11959:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11960:     my $location;
                   11961:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11962:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11963:                          '/usr/sbin/') {
                   11964:             if (-x $dir.$program) {
                   11965:                 $location = $dir.$program;
                   11966:                 last;
                   11967:             }
                   11968:         }
                   11969:     }
                   11970:     return $location;
                   11971: }
                   11972: 
                   11973: sub list_archive_contents {
                   11974:     my ($file,$pathsref) = @_;
                   11975:     my (@cmd,$output);
                   11976:     my $needsregexp;
                   11977:     if ($file =~ /\.zip$/) {
                   11978:         @cmd = (&decompression_utility('unzip'),"-l");
                   11979:         $needsregexp = 1;
                   11980:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11981:              ($file =~ /\.tgz$/)) {
                   11982:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11983:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11984:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11985:     } elsif ($file =~ m|\.tar$|) {
                   11986:         @cmd = (&decompression_utility('tar'),"-tf");
                   11987:     }
                   11988:     if (@cmd) {
                   11989:         undef($!);
                   11990:         undef($@);
                   11991:         if (open(my $fh,"-|", @cmd, $file)) {
                   11992:             while (my $line = <$fh>) {
                   11993:                 $output .= $line;
                   11994:                 chomp($line);
                   11995:                 my $item;
                   11996:                 if ($needsregexp) {
                   11997:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11998:                 } else {
                   11999:                     $item = $line;
                   12000:                 }
                   12001:                 if ($item ne '') {
                   12002:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12003:                         push(@{$pathsref},$item);
                   12004:                     } 
                   12005:                 }
                   12006:             }
                   12007:             close($fh);
                   12008:         }
                   12009:     }
                   12010:     return $output;
                   12011: }
                   12012: 
1.1053    raeburn  12013: sub decompress_uploaded_file {
                   12014:     my ($file,$dir) = @_;
                   12015:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12016:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12017:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12018:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12019:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12020:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12021:     my $decompressed = $env{'cgi.decompressed'};
                   12022:     &Apache::lonnet::delenv('cgi.file');
                   12023:     &Apache::lonnet::delenv('cgi.dir');
                   12024:     &Apache::lonnet::delenv('cgi.decompressed');
                   12025:     return ($decompressed,$result);
                   12026: }
                   12027: 
1.1055    raeburn  12028: sub process_decompression {
                   12029:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   12030:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12031:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12032:         $error = &mt('Filename not a supported archive file type.').
                   12033:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12034:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12035:     } else {
                   12036:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12037:         if ($docuhome eq 'no_host') {
                   12038:             $error = &mt('Could not determine home server for course.');
                   12039:         } else {
                   12040:             my @ids=&Apache::lonnet::current_machine_ids();
                   12041:             my $currdir = "$dir_root/$destination";
                   12042:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12043:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12044:                        "$dir_root/$destination";
                   12045:             } else {
                   12046:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12047:                        "$dir_root/$docudom/$docuname/$destination";
                   12048:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12049:                     $error = &mt('Archive file not found.');
                   12050:                 }
                   12051:             }
1.1065    raeburn  12052:             my (@to_overwrite,@to_skip);
                   12053:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12054:                 my $total = $env{'form.archive_overwrite_total'};
                   12055:                 for (my $i=0; $i<$total; $i++) {
                   12056:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12057:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12058:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12059:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12060:                     }
                   12061:                 }
                   12062:             }
                   12063:             my $numskip = scalar(@to_skip);
                   12064:             if (($numskip > 0) && 
                   12065:                 ($numskip == $env{'form.archive_itemcount'})) {
                   12066:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12067:             } elsif ($dir eq '') {
1.1055    raeburn  12068:                 $error = &mt('Directory containing archive file unavailable.');
                   12069:             } elsif (!$error) {
1.1065    raeburn  12070:                 my ($decompressed,$display);
                   12071:                 if ($numskip > 0) {
                   12072:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12073:                     mkdir("$dir/$tempdir",0755);
                   12074:                     system("mv $dir/$file $dir/$tempdir/$file");
                   12075:                     ($decompressed,$display) = 
                   12076:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   12077:                     foreach my $item (@to_skip) {
                   12078:                         if (($item ne '') && ($item !~ /\.\./)) {
                   12079:                             if (-f "$dir/$tempdir/$item") { 
                   12080:                                 unlink("$dir/$tempdir/$item");
                   12081:                             } elsif (-d "$dir/$tempdir/$item") {
                   12082:                                 system("rm -rf $dir/$tempdir/$item");
                   12083:                             }
                   12084:                         }
                   12085:                     }
                   12086:                     system("mv $dir/$tempdir/* $dir");
                   12087:                     rmdir("$dir/$tempdir");   
                   12088:                 } else {
                   12089:                     ($decompressed,$display) = 
                   12090:                         &decompress_uploaded_file($file,$dir);
                   12091:                 }
1.1055    raeburn  12092:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12093:                     $output = '<p class="LC_info">'.
                   12094:                               &mt('Files extracted successfully from archive.').
                   12095:                               '</p>'."\n";
1.1055    raeburn  12096:                     my ($warning,$result,@contents);
                   12097:                     my ($newdirlistref,$newlisterror) =
                   12098:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12099:                                                  $docuname,1);
                   12100:                     my (%is_dir,%changes,@newitems);
                   12101:                     my $dirptr = 16384;
1.1065    raeburn  12102:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12103:                         foreach my $dir_line (@{$newdirlistref}) {
                   12104:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  12105:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   12106:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  12107:                                 push(@newitems,$item);
                   12108:                                 if ($dirptr&$testdir) {
                   12109:                                     $is_dir{$item} = 1;
                   12110:                                 }
                   12111:                                 $changes{$item} = 1;
                   12112:                             }
                   12113:                         }
                   12114:                     }
                   12115:                     if (keys(%changes) > 0) {
                   12116:                         foreach my $item (sort(@newitems)) {
                   12117:                             if ($changes{$item}) {
                   12118:                                 push(@contents,$item);
                   12119:                             }
                   12120:                         }
                   12121:                     }
                   12122:                     if (@contents > 0) {
1.1067    raeburn  12123:                         my $wantform;
                   12124:                         unless ($env{'form.autoextract_camtasia'}) {
                   12125:                             $wantform = 1;
                   12126:                         }
1.1056    raeburn  12127:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12128:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12129:                                                                 $currdir,\%is_dir,
                   12130:                                                                 \%children,\%parent,
1.1056    raeburn  12131:                                                                 \@contents,\%dirorder,
                   12132:                                                                 \%titles,$wantform);
1.1055    raeburn  12133:                         if ($datatable ne '') {
                   12134:                             $output .= &archive_options_form('decompressed',$datatable,
                   12135:                                                              $count,$hiddenelem);
1.1065    raeburn  12136:                             my $startcount = 6;
1.1055    raeburn  12137:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12138:                                                            \%titles,\%children);
1.1055    raeburn  12139:                         }
1.1067    raeburn  12140:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  12141:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12142:                             my %displayed;
                   12143:                             my $total = 1;
                   12144:                             $env{'form.archive_directory'} = [];
                   12145:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12146:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12147:                                 $path =~ s{/$}{};
                   12148:                                 my $item;
                   12149:                                 if ($path ne '') {
                   12150:                                     $item = "$path/$titles{$i}";
                   12151:                                 } else {
                   12152:                                     $item = $titles{$i};
                   12153:                                 }
                   12154:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12155:                                 if ($item eq $contents[0]) {
                   12156:                                     push(@{$env{'form.archive_directory'}},$i);
                   12157:                                     $env{'form.archive_'.$i} = 'display';
                   12158:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12159:                                     $displayed{'folder'} = $i;
1.1164    raeburn  12160:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12161:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  12162:                                     $env{'form.archive_'.$i} = 'display';
                   12163:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12164:                                     $displayed{'web'} = $i;
                   12165:                                 } else {
1.1164    raeburn  12166:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12167:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12168:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12169:                                         push(@{$env{'form.archive_directory'}},$i);
                   12170:                                     }
                   12171:                                     $env{'form.archive_'.$i} = 'dependency';
                   12172:                                 }
                   12173:                                 $total ++;
                   12174:                             }
                   12175:                             for (my $i=1; $i<$total; $i++) {
                   12176:                                 next if ($i == $displayed{'web'});
                   12177:                                 next if ($i == $displayed{'folder'});
                   12178:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12179:                             }
                   12180:                             $env{'form.phase'} = 'decompress_cleanup';
                   12181:                             $env{'form.archivedelete'} = 1;
                   12182:                             $env{'form.archive_count'} = $total-1;
                   12183:                             $output .=
                   12184:                                 &process_extracted_files('coursedocs',$docudom,
                   12185:                                                          $docuname,$destination,
                   12186:                                                          $dir_root,$hiddenelem);
                   12187:                         }
1.1055    raeburn  12188:                     } else {
                   12189:                         $warning = &mt('No new items extracted from archive file.');
                   12190:                     }
                   12191:                 } else {
                   12192:                     $output = $display;
                   12193:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12194:                 }
                   12195:             }
                   12196:         }
                   12197:     }
                   12198:     if ($error) {
                   12199:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12200:                    $error.'</p>'."\n";
                   12201:     }
                   12202:     if ($warning) {
                   12203:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12204:     }
                   12205:     return $output;
                   12206: }
                   12207: 
                   12208: sub get_extracted {
1.1056    raeburn  12209:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12210:         $titles,$wantform) = @_;
1.1055    raeburn  12211:     my $count = 0;
                   12212:     my $depth = 0;
                   12213:     my $datatable;
1.1056    raeburn  12214:     my @hierarchy;
1.1055    raeburn  12215:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12216:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12217:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12218:     foreach my $item (@{$contents}) {
                   12219:         $count ++;
1.1056    raeburn  12220:         @{$dirorder->{$count}} = @hierarchy;
                   12221:         $titles->{$count} = $item;
1.1055    raeburn  12222:         &archive_hierarchy($depth,$count,$parent,$children);
                   12223:         if ($wantform) {
                   12224:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12225:                                        $currdir,$depth,$count);
                   12226:         }
                   12227:         if ($is_dir->{$item}) {
                   12228:             $depth ++;
1.1056    raeburn  12229:             push(@hierarchy,$count);
                   12230:             $parent->{$depth} = $count;
1.1055    raeburn  12231:             $datatable .=
                   12232:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12233:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12234:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12235:             $depth --;
1.1056    raeburn  12236:             pop(@hierarchy);
1.1055    raeburn  12237:         }
                   12238:     }
                   12239:     return ($count,$datatable);
                   12240: }
                   12241: 
                   12242: sub recurse_extracted_archive {
1.1056    raeburn  12243:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12244:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12245:     my $result='';
1.1056    raeburn  12246:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12247:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12248:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12249:         return $result;
                   12250:     }
                   12251:     my $dirptr = 16384;
                   12252:     my ($newdirlistref,$newlisterror) =
                   12253:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12254:     if (ref($newdirlistref) eq 'ARRAY') {
                   12255:         foreach my $dir_line (@{$newdirlistref}) {
                   12256:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12257:             unless ($item =~ /^\.+$/) {
                   12258:                 $$count ++;
1.1056    raeburn  12259:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12260:                 $titles->{$$count} = $item;
1.1055    raeburn  12261:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12262: 
1.1055    raeburn  12263:                 my $is_dir;
                   12264:                 if ($dirptr&$testdir) {
                   12265:                     $is_dir = 1;
                   12266:                 }
                   12267:                 if ($wantform) {
                   12268:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12269:                 }
                   12270:                 if ($is_dir) {
                   12271:                     $$depth ++;
1.1056    raeburn  12272:                     push(@{$hierarchy},$$count);
                   12273:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12274:                     $result .=
                   12275:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12276:                                                    $docuname,$depth,$count,
1.1056    raeburn  12277:                                                    $hierarchy,$dirorder,$children,
                   12278:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12279:                     $$depth --;
1.1056    raeburn  12280:                     pop(@{$hierarchy});
1.1055    raeburn  12281:                 }
                   12282:             }
                   12283:         }
                   12284:     }
                   12285:     return $result;
                   12286: }
                   12287: 
                   12288: sub archive_hierarchy {
                   12289:     my ($depth,$count,$parent,$children) =@_;
                   12290:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12291:         if (exists($parent->{$depth})) {
                   12292:              $children->{$parent->{$depth}} .= $count.':';
                   12293:         }
                   12294:     }
                   12295:     return;
                   12296: }
                   12297: 
                   12298: sub archive_row {
                   12299:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12300:     my ($name) = ($item =~ m{([^/]+)$});
                   12301:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12302:                                        'display'    => 'Add as file',
1.1055    raeburn  12303:                                        'dependency' => 'Include as dependency',
                   12304:                                        'discard'    => 'Discard',
                   12305:                                       );
                   12306:     if ($is_dir) {
1.1059    raeburn  12307:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12308:     }
1.1056    raeburn  12309:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12310:     my $offset = 0;
1.1055    raeburn  12311:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12312:         $offset ++;
1.1065    raeburn  12313:         if ($action ne 'display') {
                   12314:             $offset ++;
                   12315:         }  
1.1055    raeburn  12316:         $output .= '<td><span class="LC_nobreak">'.
                   12317:                    '<label><input type="radio" name="archive_'.$count.
                   12318:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12319:         my $text = $choices{$action};
                   12320:         if ($is_dir) {
                   12321:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12322:             if ($action eq 'display') {
1.1059    raeburn  12323:                 $text = &mt('Add as folder');
1.1055    raeburn  12324:             }
1.1056    raeburn  12325:         } else {
                   12326:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12327: 
                   12328:         }
                   12329:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12330:         if ($action eq 'dependency') {
                   12331:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12332:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12333:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12334:                        '<option value=""></option>'."\n".
                   12335:                        '</select>'."\n".
                   12336:                        '</div>';
1.1059    raeburn  12337:         } elsif ($action eq 'display') {
                   12338:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12339:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12340:                        '</div>';
1.1055    raeburn  12341:         }
1.1056    raeburn  12342:         $output .= '</td>';
1.1055    raeburn  12343:     }
                   12344:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12345:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12346:     for (my $i=0; $i<$depth; $i++) {
                   12347:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12348:     }
                   12349:     if ($is_dir) {
                   12350:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12351:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12352:     } else {
                   12353:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12354:     }
                   12355:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12356:                &end_data_table_row();
                   12357:     return $output;
                   12358: }
                   12359: 
                   12360: sub archive_options_form {
1.1065    raeburn  12361:     my ($form,$display,$count,$hiddenelem) = @_;
                   12362:     my %lt = &Apache::lonlocal::texthash(
                   12363:                perm => 'Permanently remove archive file?',
                   12364:                hows => 'How should each extracted item be incorporated in the course?',
                   12365:                cont => 'Content actions for all',
                   12366:                addf => 'Add as folder/file',
                   12367:                incd => 'Include as dependency for a displayed file',
                   12368:                disc => 'Discard',
                   12369:                no   => 'No',
                   12370:                yes  => 'Yes',
                   12371:                save => 'Save',
                   12372:     );
                   12373:     my $output = <<"END";
                   12374: <form name="$form" method="post" action="">
                   12375: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12376: <label>
                   12377:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12378: </label>
                   12379: &nbsp;
                   12380: <label>
                   12381:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12382: </span>
                   12383: </p>
                   12384: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12385: <br />$lt{'hows'}
                   12386: <div class="LC_columnSection">
                   12387:   <fieldset>
                   12388:     <legend>$lt{'cont'}</legend>
                   12389:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12390:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12391:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12392:   </fieldset>
                   12393: </div>
                   12394: END
                   12395:     return $output.
1.1055    raeburn  12396:            &start_data_table()."\n".
1.1065    raeburn  12397:            $display."\n".
1.1055    raeburn  12398:            &end_data_table()."\n".
                   12399:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12400:            $hiddenelem.
1.1065    raeburn  12401:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12402:            '</form>';
                   12403: }
                   12404: 
                   12405: sub archive_javascript {
1.1056    raeburn  12406:     my ($startcount,$numitems,$titles,$children) = @_;
                   12407:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12408:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12409:     my $scripttag = <<START;
                   12410: <script type="text/javascript">
                   12411: // <![CDATA[
                   12412: 
                   12413: function checkAll(form,prefix) {
                   12414:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12415:     for (var i=0; i < form.elements.length; i++) {
                   12416:         var id = form.elements[i].id;
                   12417:         if ((id != '') && (id != undefined)) {
                   12418:             if (idstr.test(id)) {
                   12419:                 if (form.elements[i].type == 'radio') {
                   12420:                     form.elements[i].checked = true;
1.1056    raeburn  12421:                     var nostart = i-$startcount;
1.1059    raeburn  12422:                     var offset = nostart%7;
                   12423:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12424:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12425:                 }
                   12426:             }
                   12427:         }
                   12428:     }
                   12429: }
                   12430: 
                   12431: function propagateCheck(form,count) {
                   12432:     if (count > 0) {
1.1059    raeburn  12433:         var startelement = $startcount + ((count-1) * 7);
                   12434:         for (var j=1; j<6; j++) {
                   12435:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12436:                 var item = startelement + j; 
                   12437:                 if (form.elements[item].type == 'radio') {
                   12438:                     if (form.elements[item].checked) {
                   12439:                         containerCheck(form,count,j);
                   12440:                         break;
                   12441:                     }
1.1055    raeburn  12442:                 }
                   12443:             }
                   12444:         }
                   12445:     }
                   12446: }
                   12447: 
                   12448: numitems = $numitems
1.1056    raeburn  12449: var titles = new Array(numitems);
                   12450: var parents = new Array(numitems);
1.1055    raeburn  12451: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12452:     parents[i] = new Array;
1.1055    raeburn  12453: }
1.1059    raeburn  12454: var maintitle = '$maintitle';
1.1055    raeburn  12455: 
                   12456: START
                   12457: 
1.1056    raeburn  12458:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12459:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12460:         for (my $i=0; $i<@contents; $i ++) {
                   12461:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12462:         }
                   12463:     }
                   12464: 
1.1056    raeburn  12465:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12466:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12467:     }
                   12468: 
1.1055    raeburn  12469:     $scripttag .= <<END;
                   12470: 
                   12471: function containerCheck(form,count,offset) {
                   12472:     if (count > 0) {
1.1056    raeburn  12473:         dependencyCheck(form,count,offset);
1.1059    raeburn  12474:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12475:         form.elements[item].checked = true;
                   12476:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12477:             if (parents[count].length > 0) {
                   12478:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12479:                     containerCheck(form,parents[count][j],offset);
                   12480:                 }
                   12481:             }
                   12482:         }
                   12483:     }
                   12484: }
                   12485: 
                   12486: function dependencyCheck(form,count,offset) {
                   12487:     if (count > 0) {
1.1059    raeburn  12488:         var chosen = (offset+$startcount)+7*(count-1);
                   12489:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12490:         var currtype = form.elements[depitem].type;
                   12491:         if (form.elements[chosen].value == 'dependency') {
                   12492:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12493:             form.elements[depitem].options.length = 0;
                   12494:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  12495:             for (var i=1; i<=numitems; i++) {
                   12496:                 if (i == count) {
                   12497:                     continue;
                   12498:                 }
1.1059    raeburn  12499:                 var startelement = $startcount + (i-1) * 7;
                   12500:                 for (var j=1; j<6; j++) {
                   12501:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12502:                         var item = startelement + j;
                   12503:                         if (form.elements[item].type == 'radio') {
                   12504:                             if (form.elements[item].checked) {
                   12505:                                 if (form.elements[item].value == 'display') {
                   12506:                                     var n = form.elements[depitem].options.length;
                   12507:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12508:                                 }
                   12509:                             }
                   12510:                         }
                   12511:                     }
                   12512:                 }
                   12513:             }
                   12514:         } else {
                   12515:             document.getElementById('arc_depon_'+count).style.display='none';
                   12516:             form.elements[depitem].options.length = 0;
                   12517:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12518:         }
1.1059    raeburn  12519:         titleCheck(form,count,offset);
1.1056    raeburn  12520:     }
                   12521: }
                   12522: 
                   12523: function propagateSelect(form,count,offset) {
                   12524:     if (count > 0) {
1.1065    raeburn  12525:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12526:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12527:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12528:             if (parents[count].length > 0) {
                   12529:                 for (var j=0; j<parents[count].length; j++) {
                   12530:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12531:                 }
                   12532:             }
                   12533:         }
                   12534:     }
                   12535: }
1.1056    raeburn  12536: 
                   12537: function containerSelect(form,count,offset,picked) {
                   12538:     if (count > 0) {
1.1065    raeburn  12539:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12540:         if (form.elements[item].type == 'radio') {
                   12541:             if (form.elements[item].value == 'dependency') {
                   12542:                 if (form.elements[item+1].type == 'select-one') {
                   12543:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12544:                         if (form.elements[item+1].options[i].value == picked) {
                   12545:                             form.elements[item+1].selectedIndex = i;
                   12546:                             break;
                   12547:                         }
                   12548:                     }
                   12549:                 }
                   12550:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12551:                     if (parents[count].length > 0) {
                   12552:                         for (var j=0; j<parents[count].length; j++) {
                   12553:                             containerSelect(form,parents[count][j],offset,picked);
                   12554:                         }
                   12555:                     }
                   12556:                 }
                   12557:             }
                   12558:         }
                   12559:     }
                   12560: }
                   12561: 
1.1059    raeburn  12562: function titleCheck(form,count,offset) {
                   12563:     if (count > 0) {
                   12564:         var chosen = (offset+$startcount)+7*(count-1);
                   12565:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12566:         var currtype = form.elements[depitem].type;
                   12567:         if (form.elements[chosen].value == 'display') {
                   12568:             document.getElementById('arc_title_'+count).style.display='block';
                   12569:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12570:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12571:             }
                   12572:         } else {
                   12573:             document.getElementById('arc_title_'+count).style.display='none';
                   12574:             if (currtype == 'text') { 
                   12575:                 document.getElementById('archive_title_'+count).value='';
                   12576:             }
                   12577:         }
                   12578:     }
                   12579:     return;
                   12580: }
                   12581: 
1.1055    raeburn  12582: // ]]>
                   12583: </script>
                   12584: END
                   12585:     return $scripttag;
                   12586: }
                   12587: 
                   12588: sub process_extracted_files {
1.1067    raeburn  12589:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12590:     my $numitems = $env{'form.archive_count'};
                   12591:     return unless ($numitems);
                   12592:     my @ids=&Apache::lonnet::current_machine_ids();
                   12593:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12594:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12595:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12596:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12597:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12598:         $pathtocheck = "$dir_root/$destination";
                   12599:         $dir = $dir_root;
                   12600:         $ishome = 1;
                   12601:     } else {
                   12602:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12603:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12604:         $dir = "$dir_root/$docudom/$docuname";    
                   12605:     }
                   12606:     my $currdir = "$dir_root/$destination";
                   12607:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12608:     if ($env{'form.folderpath'}) {
                   12609:         my @items = split('&',$env{'form.folderpath'});
                   12610:         $folders{'0'} = $items[-2];
1.1099    raeburn  12611:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12612:             $containers{'0'}='page';
                   12613:         } else {  
                   12614:             $containers{'0'}='sequence';
                   12615:         }
1.1055    raeburn  12616:     }
                   12617:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12618:     if ($numitems) {
                   12619:         for (my $i=1; $i<=$numitems; $i++) {
                   12620:             my $path = $env{'form.archive_content_'.$i};
                   12621:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12622:                 my $item = $1;
                   12623:                 $toplevelitems{$item} = $i;
                   12624:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12625:                     $is_dir{$item} = 1;
                   12626:                 }
                   12627:             }
                   12628:         }
                   12629:     }
1.1067    raeburn  12630:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12631:     if (keys(%toplevelitems) > 0) {
                   12632:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12633:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12634:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12635:     }
1.1066    raeburn  12636:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12637:     if ($numitems) {
                   12638:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  12639:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12640:             my $path = $env{'form.archive_content_'.$i};
                   12641:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12642:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12643:                     if ($prefix ne '' && $path ne '') {
                   12644:                         if (-e $prefix.$path) {
1.1066    raeburn  12645:                             if ((@archdirs > 0) && 
                   12646:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12647:                                 $todeletedir{$prefix.$path} = 1;
                   12648:                             } else {
                   12649:                                 $todelete{$prefix.$path} = 1;
                   12650:                             }
1.1055    raeburn  12651:                         }
                   12652:                     }
                   12653:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12654:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12655:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12656:                     $docstitle = $env{'form.archive_title_'.$i};
                   12657:                     if ($docstitle eq '') {
                   12658:                         $docstitle = $title;
                   12659:                     }
1.1055    raeburn  12660:                     $outer = 0;
1.1056    raeburn  12661:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12662:                         if (@{$dirorder{$i}} > 0) {
                   12663:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12664:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12665:                                     $outer = $item;
                   12666:                                     last;
                   12667:                                 }
                   12668:                             }
                   12669:                         }
                   12670:                     }
                   12671:                     my ($errtext,$fatal) = 
                   12672:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12673:                                                '/'.$folders{$outer}.'.'.
                   12674:                                                $containers{$outer});
                   12675:                     next if ($fatal);
                   12676:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12677:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12678:                             $mapinner{$i} = time;
1.1055    raeburn  12679:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12680:                             $containers{$i} = 'sequence';
                   12681:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12682:                                       $folders{$i}.'.'.$containers{$i};
                   12683:                             my $newidx = &LONCAPA::map::getresidx();
                   12684:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12685:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12686:                             push(@LONCAPA::map::order,$newidx);
                   12687:                             my ($outtext,$errtext) =
                   12688:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12689:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12690:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12691:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12692:                             unless ($errtext) {
                   12693:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12694:                             }
1.1055    raeburn  12695:                         }
                   12696:                     } else {
                   12697:                         if ($context eq 'coursedocs') {
                   12698:                             my $newidx=&LONCAPA::map::getresidx();
                   12699:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12700:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12701:                                       $title;
                   12702:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12703:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12704:                             }
                   12705:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12706:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12707:                             }
                   12708:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12709:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12710:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12711:                                 unless ($ishome) {
                   12712:                                     my $fetch = "$newdest{$i}/$title";
                   12713:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12714:                                     $prompttofetch{$fetch} = 1;
                   12715:                                 }
1.1055    raeburn  12716:                             }
                   12717:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12718:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12719:                             push(@LONCAPA::map::order, $newidx);
                   12720:                             my ($outtext,$errtext)=
                   12721:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12722:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12723:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12724:                             unless ($errtext) {
                   12725:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12726:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12727:                                 }
                   12728:                             }
1.1055    raeburn  12729:                         }
                   12730:                     }
1.1086    raeburn  12731:                 }
                   12732:             } else {
                   12733:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12734:             }
                   12735:         }
                   12736:         for (my $i=1; $i<=$numitems; $i++) {
                   12737:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12738:             my $path = $env{'form.archive_content_'.$i};
                   12739:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12740:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12741:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12742:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12743:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12744:                         my ($itemidx,$fullpath,$relpath);
                   12745:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12746:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12747:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  12748:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12749:                                     $itemidx = $j;
1.1056    raeburn  12750:                                 }
                   12751:                             }
1.1086    raeburn  12752:                         }
                   12753:                         if ($itemidx eq '') {
                   12754:                             $itemidx =  0;
                   12755:                         } 
                   12756:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12757:                             if ($mapinner{$referrer{$i}}) {
                   12758:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12759:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12760:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12761:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12762:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12763:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12764:                                             if (!-e $fullpath) {
                   12765:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12766:                                             }
                   12767:                                         }
1.1086    raeburn  12768:                                     } else {
                   12769:                                         last;
1.1056    raeburn  12770:                                     }
1.1086    raeburn  12771:                                 }
                   12772:                             }
                   12773:                         } elsif ($newdest{$referrer{$i}}) {
                   12774:                             $fullpath = $newdest{$referrer{$i}};
                   12775:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12776:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12777:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12778:                                     last;
                   12779:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12780:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12781:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12782:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12783:                                         if (!-e $fullpath) {
                   12784:                                             mkdir($fullpath,0755);
1.1056    raeburn  12785:                                         }
                   12786:                                     }
1.1086    raeburn  12787:                                 } else {
                   12788:                                     last;
1.1056    raeburn  12789:                                 }
1.1055    raeburn  12790:                             }
                   12791:                         }
1.1086    raeburn  12792:                         if ($fullpath ne '') {
                   12793:                             if (-e "$prefix$path") {
                   12794:                                 system("mv $prefix$path $fullpath/$title");
                   12795:                             }
                   12796:                             if (-e "$fullpath/$title") {
                   12797:                                 my $showpath;
                   12798:                                 if ($relpath ne '') {
                   12799:                                     $showpath = "$relpath/$title";
                   12800:                                 } else {
                   12801:                                     $showpath = "/$title";
                   12802:                                 } 
                   12803:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12804:                             } 
                   12805:                             unless ($ishome) {
                   12806:                                 my $fetch = "$fullpath/$title";
                   12807:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   12808:                                 $prompttofetch{$fetch} = 1;
                   12809:                             }
                   12810:                         }
1.1055    raeburn  12811:                     }
1.1086    raeburn  12812:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12813:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12814:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12815:                 }
                   12816:             } else {
                   12817:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12818:             }
                   12819:         }
                   12820:         if (keys(%todelete)) {
                   12821:             foreach my $key (keys(%todelete)) {
                   12822:                 unlink($key);
1.1066    raeburn  12823:             }
                   12824:         }
                   12825:         if (keys(%todeletedir)) {
                   12826:             foreach my $key (keys(%todeletedir)) {
                   12827:                 rmdir($key);
                   12828:             }
                   12829:         }
                   12830:         foreach my $dir (sort(keys(%is_dir))) {
                   12831:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12832:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12833:             }
                   12834:         }
1.1067    raeburn  12835:         if ($result ne '') {
                   12836:             $output .= '<ul>'."\n".
                   12837:                        $result."\n".
                   12838:                        '</ul>';
                   12839:         }
                   12840:         unless ($ishome) {
                   12841:             my $replicationfail;
                   12842:             foreach my $item (keys(%prompttofetch)) {
                   12843:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12844:                 unless ($fetchresult eq 'ok') {
                   12845:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12846:                 }
                   12847:             }
                   12848:             if ($replicationfail) {
                   12849:                 $output .= '<p class="LC_error">'.
                   12850:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12851:                            $replicationfail.
                   12852:                            '</ul></p>';
                   12853:             }
                   12854:         }
1.1055    raeburn  12855:     } else {
                   12856:         $warning = &mt('No items found in archive.');
                   12857:     }
                   12858:     if ($error) {
                   12859:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12860:                    $error.'</p>'."\n";
                   12861:     }
                   12862:     if ($warning) {
                   12863:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12864:     }
                   12865:     return $output;
                   12866: }
                   12867: 
1.1066    raeburn  12868: sub cleanup_empty_dirs {
                   12869:     my ($path) = @_;
                   12870:     if (($path ne '') && (-d $path)) {
                   12871:         if (opendir(my $dirh,$path)) {
                   12872:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12873:             my $numitems = 0;
                   12874:             foreach my $item (@dircontents) {
                   12875:                 if (-d "$path/$item") {
1.1111    raeburn  12876:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12877:                     if (-e "$path/$item") {
                   12878:                         $numitems ++;
                   12879:                     }
                   12880:                 } else {
                   12881:                     $numitems ++;
                   12882:                 }
                   12883:             }
                   12884:             if ($numitems == 0) {
                   12885:                 rmdir($path);
                   12886:             }
                   12887:             closedir($dirh);
                   12888:         }
                   12889:     }
                   12890:     return;
                   12891: }
                   12892: 
1.41      ng       12893: =pod
1.45      matthew  12894: 
1.1162    raeburn  12895: =item * &get_folder_hierarchy()
1.1068    raeburn  12896: 
                   12897: Provides hierarchy of names of folders/sub-folders containing the current
                   12898: item,
                   12899: 
                   12900: Inputs: 3
                   12901:      - $navmap - navmaps object
                   12902: 
                   12903:      - $map - url for map (either the trigger itself, or map containing
                   12904:                            the resource, which is the trigger).
                   12905: 
                   12906:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12907: 
                   12908: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12909: 
                   12910: =cut
                   12911: 
                   12912: sub get_folder_hierarchy {
                   12913:     my ($navmap,$map,$showitem) = @_;
                   12914:     my @pathitems;
                   12915:     if (ref($navmap)) {
                   12916:         my $mapres = $navmap->getResourceByUrl($map);
                   12917:         if (ref($mapres)) {
                   12918:             my $pcslist = $mapres->map_hierarchy();
                   12919:             if ($pcslist ne '') {
                   12920:                 my @pcs = split(/,/,$pcslist);
                   12921:                 foreach my $pc (@pcs) {
                   12922:                     if ($pc == 1) {
1.1129    raeburn  12923:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12924:                     } else {
                   12925:                         my $res = $navmap->getByMapPc($pc);
                   12926:                         if (ref($res)) {
                   12927:                             my $title = $res->compTitle();
                   12928:                             $title =~ s/\W+/_/g;
                   12929:                             if ($title ne '') {
                   12930:                                 push(@pathitems,$title);
                   12931:                             }
                   12932:                         }
                   12933:                     }
                   12934:                 }
                   12935:             }
1.1071    raeburn  12936:             if ($showitem) {
                   12937:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  12938:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12939:                 } else {
                   12940:                     my $maptitle = $mapres->compTitle();
                   12941:                     $maptitle =~ s/\W+/_/g;
                   12942:                     if ($maptitle ne '') {
                   12943:                         push(@pathitems,$maptitle);
                   12944:                     }
1.1068    raeburn  12945:                 }
                   12946:             }
                   12947:         }
                   12948:     }
                   12949:     return @pathitems;
                   12950: }
                   12951: 
                   12952: =pod
                   12953: 
1.1015    raeburn  12954: =item * &get_turnedin_filepath()
                   12955: 
                   12956: Determines path in a user's portfolio file for storage of files uploaded
                   12957: to a specific essayresponse or dropbox item.
                   12958: 
                   12959: Inputs: 3 required + 1 optional.
                   12960: $symb is symb for resource, $uname and $udom are for current user (required).
                   12961: $caller is optional (can be "submission", if routine is called when storing
                   12962: an upoaded file when "Submit Answer" button was pressed).
                   12963: 
                   12964: Returns array containing $path and $multiresp. 
                   12965: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12966: than one file upload item.  Callers of routine should append partid as a 
                   12967: subdirectory to $path in cases where $multiresp is 1.
                   12968: 
                   12969: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12970: 
                   12971: =cut
                   12972: 
                   12973: sub get_turnedin_filepath {
                   12974:     my ($symb,$uname,$udom,$caller) = @_;
                   12975:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12976:     my $turnindir;
                   12977:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12978:     $turnindir = $userhash{'turnindir'};
                   12979:     my ($path,$multiresp);
                   12980:     if ($turnindir eq '') {
                   12981:         if ($caller eq 'submission') {
                   12982:             $turnindir = &mt('turned in');
                   12983:             $turnindir =~ s/\W+/_/g;
                   12984:             my %newhash = (
                   12985:                             'turnindir' => $turnindir,
                   12986:                           );
                   12987:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12988:         }
                   12989:     }
                   12990:     if ($turnindir ne '') {
                   12991:         $path = '/'.$turnindir.'/';
                   12992:         my ($multipart,$turnin,@pathitems);
                   12993:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12994:         if (defined($navmap)) {
                   12995:             my $mapres = $navmap->getResourceByUrl($map);
                   12996:             if (ref($mapres)) {
                   12997:                 my $pcslist = $mapres->map_hierarchy();
                   12998:                 if ($pcslist ne '') {
                   12999:                     foreach my $pc (split(/,/,$pcslist)) {
                   13000:                         my $res = $navmap->getByMapPc($pc);
                   13001:                         if (ref($res)) {
                   13002:                             my $title = $res->compTitle();
                   13003:                             $title =~ s/\W+/_/g;
                   13004:                             if ($title ne '') {
1.1149    raeburn  13005:                                 if (($pc > 1) && (length($title) > 12)) {
                   13006:                                     $title = substr($title,0,12);
                   13007:                                 }
1.1015    raeburn  13008:                                 push(@pathitems,$title);
                   13009:                             }
                   13010:                         }
                   13011:                     }
                   13012:                 }
                   13013:                 my $maptitle = $mapres->compTitle();
                   13014:                 $maptitle =~ s/\W+/_/g;
                   13015:                 if ($maptitle ne '') {
1.1149    raeburn  13016:                     if (length($maptitle) > 12) {
                   13017:                         $maptitle = substr($maptitle,0,12);
                   13018:                     }
1.1015    raeburn  13019:                     push(@pathitems,$maptitle);
                   13020:                 }
                   13021:                 unless ($env{'request.state'} eq 'construct') {
                   13022:                     my $res = $navmap->getBySymb($symb);
                   13023:                     if (ref($res)) {
                   13024:                         my $partlist = $res->parts();
                   13025:                         my $totaluploads = 0;
                   13026:                         if (ref($partlist) eq 'ARRAY') {
                   13027:                             foreach my $part (@{$partlist}) {
                   13028:                                 my @types = $res->responseType($part);
                   13029:                                 my @ids = $res->responseIds($part);
                   13030:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13031:                                     if ($types[$i] eq 'essay') {
                   13032:                                         my $partid = $part.'_'.$ids[$i];
                   13033:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13034:                                             $totaluploads ++;
                   13035:                                         }
                   13036:                                     }
                   13037:                                 }
                   13038:                             }
                   13039:                             if ($totaluploads > 1) {
                   13040:                                 $multiresp = 1;
                   13041:                             }
                   13042:                         }
                   13043:                     }
                   13044:                 }
                   13045:             } else {
                   13046:                 return;
                   13047:             }
                   13048:         } else {
                   13049:             return;
                   13050:         }
                   13051:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13052:         $restitle =~ s/\W+/_/g;
                   13053:         if ($restitle eq '') {
                   13054:             $restitle = ($resurl =~ m{/[^/]+$});
                   13055:             if ($restitle eq '') {
                   13056:                 $restitle = time;
                   13057:             }
                   13058:         }
1.1149    raeburn  13059:         if (length($restitle) > 12) {
                   13060:             $restitle = substr($restitle,0,12);
                   13061:         }
1.1015    raeburn  13062:         push(@pathitems,$restitle);
                   13063:         $path .= join('/',@pathitems);
                   13064:     }
                   13065:     return ($path,$multiresp);
                   13066: }
                   13067: 
                   13068: =pod
                   13069: 
1.464     albertel 13070: =back
1.41      ng       13071: 
1.112     bowersj2 13072: =head1 CSV Upload/Handling functions
1.38      albertel 13073: 
1.41      ng       13074: =over 4
                   13075: 
1.648     raeburn  13076: =item * &upfile_store($r)
1.41      ng       13077: 
                   13078: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13079: needs $env{'form.upfile'}
1.41      ng       13080: returns $datatoken to be put into hidden field
                   13081: 
                   13082: =cut
1.31      albertel 13083: 
                   13084: sub upfile_store {
                   13085:     my $r=shift;
1.258     albertel 13086:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13087:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13088:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13089:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13090: 
1.258     albertel 13091:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   13092: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 13093:     {
1.158     raeburn  13094:         my $datafile = $r->dir_config('lonDaemons').
                   13095:                            '/tmp/'.$datatoken.'.tmp';
                   13096:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13097:             print $fh $env{'form.upfile'};
1.158     raeburn  13098:             close($fh);
                   13099:         }
1.31      albertel 13100:     }
                   13101:     return $datatoken;
                   13102: }
                   13103: 
1.56      matthew  13104: =pod
                   13105: 
1.648     raeburn  13106: =item * &load_tmp_file($r)
1.41      ng       13107: 
                   13108: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 13109: needs $env{'form.datatoken'},
                   13110: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13111: 
                   13112: =cut
1.31      albertel 13113: 
                   13114: sub load_tmp_file {
                   13115:     my $r=shift;
                   13116:     my @studentdata=();
                   13117:     {
1.158     raeburn  13118:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13119:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13120:         if ( open(my $fh,"<$studentfile") ) {
                   13121:             @studentdata=<$fh>;
                   13122:             close($fh);
                   13123:         }
1.31      albertel 13124:     }
1.258     albertel 13125:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13126: }
                   13127: 
1.56      matthew  13128: =pod
                   13129: 
1.648     raeburn  13130: =item * &upfile_record_sep()
1.41      ng       13131: 
                   13132: Separate uploaded file into records
                   13133: returns array of records,
1.258     albertel 13134: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13135: 
                   13136: =cut
1.31      albertel 13137: 
                   13138: sub upfile_record_sep {
1.258     albertel 13139:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13140:     } else {
1.248     albertel 13141: 	my @records;
1.258     albertel 13142: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13143: 	    if ($line=~/^\s*$/) { next; }
                   13144: 	    push(@records,$line);
                   13145: 	}
                   13146: 	return @records;
1.31      albertel 13147:     }
                   13148: }
                   13149: 
1.56      matthew  13150: =pod
                   13151: 
1.648     raeburn  13152: =item * &record_sep($record)
1.41      ng       13153: 
1.258     albertel 13154: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13155: 
                   13156: =cut
                   13157: 
1.263     www      13158: sub takeleft {
                   13159:     my $index=shift;
                   13160:     return substr('0000'.$index,-4,4);
                   13161: }
                   13162: 
1.31      albertel 13163: sub record_sep {
                   13164:     my $record=shift;
                   13165:     my %components=();
1.258     albertel 13166:     if ($env{'form.upfiletype'} eq 'xml') {
                   13167:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13168:         my $i=0;
1.356     albertel 13169:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13170:             $field=~s/^(\"|\')//;
                   13171:             $field=~s/(\"|\')$//;
1.263     www      13172:             $components{&takeleft($i)}=$field;
1.31      albertel 13173:             $i++;
                   13174:         }
1.258     albertel 13175:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13176:         my $i=0;
1.356     albertel 13177:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13178:             $field=~s/^(\"|\')//;
                   13179:             $field=~s/(\"|\')$//;
1.263     www      13180:             $components{&takeleft($i)}=$field;
1.31      albertel 13181:             $i++;
                   13182:         }
                   13183:     } else {
1.561     www      13184:         my $separator=',';
1.480     banghart 13185:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13186:             $separator=';';
1.480     banghart 13187:         }
1.31      albertel 13188:         my $i=0;
1.561     www      13189: # the character we are looking for to indicate the end of a quote or a record 
                   13190:         my $looking_for=$separator;
                   13191: # do not add the characters to the fields
                   13192:         my $ignore=0;
                   13193: # we just encountered a separator (or the beginning of the record)
                   13194:         my $just_found_separator=1;
                   13195: # store the field we are working on here
                   13196:         my $field='';
                   13197: # work our way through all characters in record
                   13198:         foreach my $character ($record=~/(.)/g) {
                   13199:             if ($character eq $looking_for) {
                   13200:                if ($character ne $separator) {
                   13201: # Found the end of a quote, again looking for separator
                   13202:                   $looking_for=$separator;
                   13203:                   $ignore=1;
                   13204:                } else {
                   13205: # Found a separator, store away what we got
                   13206:                   $components{&takeleft($i)}=$field;
                   13207: 	          $i++;
                   13208:                   $just_found_separator=1;
                   13209:                   $ignore=0;
                   13210:                   $field='';
                   13211:                }
                   13212:                next;
                   13213:             }
                   13214: # single or double quotation marks after a separator indicate beginning of a quote
                   13215: # we are now looking for the end of the quote and need to ignore separators
                   13216:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13217:                $looking_for=$character;
                   13218:                next;
                   13219:             }
                   13220: # ignore would be true after we reached the end of a quote
                   13221:             if ($ignore) { next; }
                   13222:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13223:             $field.=$character;
                   13224:             $just_found_separator=0; 
1.31      albertel 13225:         }
1.561     www      13226: # catch the very last entry, since we never encountered the separator
                   13227:         $components{&takeleft($i)}=$field;
1.31      albertel 13228:     }
                   13229:     return %components;
                   13230: }
                   13231: 
1.144     matthew  13232: ######################################################
                   13233: ######################################################
                   13234: 
1.56      matthew  13235: =pod
                   13236: 
1.648     raeburn  13237: =item * &upfile_select_html()
1.41      ng       13238: 
1.144     matthew  13239: Return HTML code to select a file from the users machine and specify 
                   13240: the file type.
1.41      ng       13241: 
                   13242: =cut
                   13243: 
1.144     matthew  13244: ######################################################
                   13245: ######################################################
1.31      albertel 13246: sub upfile_select_html {
1.144     matthew  13247:     my %Types = (
                   13248:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13249:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13250:                  space => &mt('Space separated'),
                   13251:                  tab   => &mt('Tabulator separated'),
                   13252: #                 xml   => &mt('HTML/XML'),
                   13253:                  );
                   13254:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13255:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13256:     foreach my $type (sort(keys(%Types))) {
                   13257:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13258:     }
                   13259:     $Str .= "</select>\n";
                   13260:     return $Str;
1.31      albertel 13261: }
                   13262: 
1.301     albertel 13263: sub get_samples {
                   13264:     my ($records,$toget) = @_;
                   13265:     my @samples=({});
                   13266:     my $got=0;
                   13267:     foreach my $rec (@$records) {
                   13268: 	my %temp = &record_sep($rec);
                   13269: 	if (! grep(/\S/, values(%temp))) { next; }
                   13270: 	if (%temp) {
                   13271: 	    $samples[$got]=\%temp;
                   13272: 	    $got++;
                   13273: 	    if ($got == $toget) { last; }
                   13274: 	}
                   13275:     }
                   13276:     return \@samples;
                   13277: }
                   13278: 
1.144     matthew  13279: ######################################################
                   13280: ######################################################
                   13281: 
1.56      matthew  13282: =pod
                   13283: 
1.648     raeburn  13284: =item * &csv_print_samples($r,$records)
1.41      ng       13285: 
                   13286: Prints a table of sample values from each column uploaded $r is an
                   13287: Apache Request ref, $records is an arrayref from
                   13288: &Apache::loncommon::upfile_record_sep
                   13289: 
                   13290: =cut
                   13291: 
1.144     matthew  13292: ######################################################
                   13293: ######################################################
1.31      albertel 13294: sub csv_print_samples {
                   13295:     my ($r,$records) = @_;
1.662     bisitz   13296:     my $samples = &get_samples($records,5);
1.301     albertel 13297: 
1.594     raeburn  13298:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13299:               &start_data_table_header_row());
1.356     albertel 13300:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13301:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13302:     $r->print(&end_data_table_header_row());
1.301     albertel 13303:     foreach my $hash (@$samples) {
1.594     raeburn  13304: 	$r->print(&start_data_table_row());
1.356     albertel 13305: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13306: 	    $r->print('<td>');
1.356     albertel 13307: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13308: 	    $r->print('</td>');
                   13309: 	}
1.594     raeburn  13310: 	$r->print(&end_data_table_row());
1.31      albertel 13311:     }
1.594     raeburn  13312:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13313: }
                   13314: 
1.144     matthew  13315: ######################################################
                   13316: ######################################################
                   13317: 
1.56      matthew  13318: =pod
                   13319: 
1.648     raeburn  13320: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13321: 
                   13322: Prints a table to create associations between values and table columns.
1.144     matthew  13323: 
1.41      ng       13324: $r is an Apache Request ref,
                   13325: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13326: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13327: 
                   13328: =cut
                   13329: 
1.144     matthew  13330: ######################################################
                   13331: ######################################################
1.31      albertel 13332: sub csv_print_select_table {
                   13333:     my ($r,$records,$d) = @_;
1.301     albertel 13334:     my $i=0;
                   13335:     my $samples = &get_samples($records,1);
1.144     matthew  13336:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13337: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13338:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13339:               '<th>'.&mt('Column').'</th>'.
                   13340:               &end_data_table_header_row()."\n");
1.356     albertel 13341:     foreach my $array_ref (@$d) {
                   13342: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13343: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13344: 
1.875     bisitz   13345: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13346: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13347: 	$r->print('<option value="none"></option>');
1.356     albertel 13348: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13349: 	    $r->print('<option value="'.$sample.'"'.
                   13350:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13351:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13352: 	}
1.594     raeburn  13353: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13354: 	$i++;
                   13355:     }
1.594     raeburn  13356:     $r->print(&end_data_table());
1.31      albertel 13357:     $i--;
                   13358:     return $i;
                   13359: }
1.56      matthew  13360: 
1.144     matthew  13361: ######################################################
                   13362: ######################################################
                   13363: 
1.56      matthew  13364: =pod
1.31      albertel 13365: 
1.648     raeburn  13366: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13367: 
                   13368: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13369: 
                   13370: $r is an Apache Request ref,
                   13371: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13372: $d is an array of 2 element arrays (internal name, displayed name)
                   13373: 
                   13374: =cut
                   13375: 
1.144     matthew  13376: ######################################################
                   13377: ######################################################
1.31      albertel 13378: sub csv_samples_select_table {
                   13379:     my ($r,$records,$d) = @_;
                   13380:     my $i=0;
1.144     matthew  13381:     #
1.662     bisitz   13382:     my $max_samples = 5;
                   13383:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13384:     $r->print(&start_data_table().
                   13385:               &start_data_table_header_row().'<th>'.
                   13386:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13387:               &end_data_table_header_row());
1.301     albertel 13388: 
                   13389:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13390: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13391: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13392: 	foreach my $option (@$d) {
                   13393: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13394: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13395:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13396:                       $display.'</option>');
1.31      albertel 13397: 	}
                   13398: 	$r->print('</select></td><td>');
1.662     bisitz   13399: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13400: 	    if (defined($samples->[$line]{$key})) { 
                   13401: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13402: 	    }
                   13403: 	}
1.594     raeburn  13404: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13405: 	$i++;
                   13406:     }
1.594     raeburn  13407:     $r->print(&end_data_table());
1.31      albertel 13408:     $i--;
                   13409:     return($i);
1.115     matthew  13410: }
                   13411: 
1.144     matthew  13412: ######################################################
                   13413: ######################################################
                   13414: 
1.115     matthew  13415: =pod
                   13416: 
1.648     raeburn  13417: =item * &clean_excel_name($name)
1.115     matthew  13418: 
                   13419: Returns a replacement for $name which does not contain any illegal characters.
                   13420: 
                   13421: =cut
                   13422: 
1.144     matthew  13423: ######################################################
                   13424: ######################################################
1.115     matthew  13425: sub clean_excel_name {
                   13426:     my ($name) = @_;
                   13427:     $name =~ s/[:\*\?\/\\]//g;
                   13428:     if (length($name) > 31) {
                   13429:         $name = substr($name,0,31);
                   13430:     }
                   13431:     return $name;
1.25      albertel 13432: }
1.84      albertel 13433: 
1.85      albertel 13434: =pod
                   13435: 
1.648     raeburn  13436: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13437: 
                   13438: Returns either 1 or undef
                   13439: 
                   13440: 1 if the part is to be hidden, undef if it is to be shown
                   13441: 
                   13442: Arguments are:
                   13443: 
                   13444: $id the id of the part to be checked
                   13445: $symb, optional the symb of the resource to check
                   13446: $udom, optional the domain of the user to check for
                   13447: $uname, optional the username of the user to check for
                   13448: 
                   13449: =cut
1.84      albertel 13450: 
                   13451: sub check_if_partid_hidden {
                   13452:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13453:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13454: 					 $symb,$udom,$uname);
1.141     albertel 13455:     my $truth=1;
                   13456:     #if the string starts with !, then the list is the list to show not hide
                   13457:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13458:     my @hiddenlist=split(/,/,$hiddenparts);
                   13459:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13460: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13461:     }
1.141     albertel 13462:     return !$truth;
1.84      albertel 13463: }
1.127     matthew  13464: 
1.138     matthew  13465: 
                   13466: ############################################################
                   13467: ############################################################
                   13468: 
                   13469: =pod
                   13470: 
1.157     matthew  13471: =back 
                   13472: 
1.138     matthew  13473: =head1 cgi-bin script and graphing routines
                   13474: 
1.157     matthew  13475: =over 4
                   13476: 
1.648     raeburn  13477: =item * &get_cgi_id()
1.138     matthew  13478: 
                   13479: Inputs: none
                   13480: 
                   13481: Returns an id which can be used to pass environment variables
                   13482: to various cgi-bin scripts.  These environment variables will
                   13483: be removed from the users environment after a given time by
                   13484: the routine &Apache::lonnet::transfer_profile_to_env.
                   13485: 
                   13486: =cut
                   13487: 
                   13488: ############################################################
                   13489: ############################################################
1.152     albertel 13490: my $uniq=0;
1.136     matthew  13491: sub get_cgi_id {
1.154     albertel 13492:     $uniq=($uniq+1)%100000;
1.280     albertel 13493:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13494: }
                   13495: 
1.127     matthew  13496: ############################################################
                   13497: ############################################################
                   13498: 
                   13499: =pod
                   13500: 
1.648     raeburn  13501: =item * &DrawBarGraph()
1.127     matthew  13502: 
1.138     matthew  13503: Facilitates the plotting of data in a (stacked) bar graph.
                   13504: Puts plot definition data into the users environment in order for 
                   13505: graph.png to plot it.  Returns an <img> tag for the plot.
                   13506: The bars on the plot are labeled '1','2',...,'n'.
                   13507: 
                   13508: Inputs:
                   13509: 
                   13510: =over 4
                   13511: 
                   13512: =item $Title: string, the title of the plot
                   13513: 
                   13514: =item $xlabel: string, text describing the X-axis of the plot
                   13515: 
                   13516: =item $ylabel: string, text describing the Y-axis of the plot
                   13517: 
                   13518: =item $Max: scalar, the maximum Y value to use in the plot
                   13519: If $Max is < any data point, the graph will not be rendered.
                   13520: 
1.140     matthew  13521: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13522: they are plotted.  If undefined, default values will be used.
                   13523: 
1.178     matthew  13524: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13525: 
1.138     matthew  13526: =item @Values: An array of array references.  Each array reference holds data
                   13527: to be plotted in a stacked bar chart.
                   13528: 
1.239     matthew  13529: =item If the final element of @Values is a hash reference the key/value
                   13530: pairs will be added to the graph definition.
                   13531: 
1.138     matthew  13532: =back
                   13533: 
                   13534: Returns:
                   13535: 
                   13536: An <img> tag which references graph.png and the appropriate identifying
                   13537: information for the plot.
                   13538: 
1.127     matthew  13539: =cut
                   13540: 
                   13541: ############################################################
                   13542: ############################################################
1.134     matthew  13543: sub DrawBarGraph {
1.178     matthew  13544:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13545:     #
                   13546:     if (! defined($colors)) {
                   13547:         $colors = ['#33ff00', 
                   13548:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13549:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13550:                   ]; 
                   13551:     }
1.228     matthew  13552:     my $extra_settings = {};
                   13553:     if (ref($Values[-1]) eq 'HASH') {
                   13554:         $extra_settings = pop(@Values);
                   13555:     }
1.127     matthew  13556:     #
1.136     matthew  13557:     my $identifier = &get_cgi_id();
                   13558:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13559:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13560:         return '';
                   13561:     }
1.225     matthew  13562:     #
                   13563:     my @Labels;
                   13564:     if (defined($labels)) {
                   13565:         @Labels = @$labels;
                   13566:     } else {
                   13567:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13568:             push (@Labels,$i+1);
                   13569:         }
                   13570:     }
                   13571:     #
1.129     matthew  13572:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13573:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13574:     my %ValuesHash;
                   13575:     my $NumSets=1;
                   13576:     foreach my $array (@Values) {
                   13577:         next if (! ref($array));
1.136     matthew  13578:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13579:             join(',',@$array);
1.129     matthew  13580:     }
1.127     matthew  13581:     #
1.136     matthew  13582:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13583:     if ($NumBars < 3) {
                   13584:         $width = 120+$NumBars*32;
1.220     matthew  13585:         $xskip = 1;
1.225     matthew  13586:         $bar_width = 30;
                   13587:     } elsif ($NumBars < 5) {
                   13588:         $width = 120+$NumBars*20;
                   13589:         $xskip = 1;
                   13590:         $bar_width = 20;
1.220     matthew  13591:     } elsif ($NumBars < 10) {
1.136     matthew  13592:         $width = 120+$NumBars*15;
                   13593:         $xskip = 1;
                   13594:         $bar_width = 15;
                   13595:     } elsif ($NumBars <= 25) {
                   13596:         $width = 120+$NumBars*11;
                   13597:         $xskip = 5;
                   13598:         $bar_width = 8;
                   13599:     } elsif ($NumBars <= 50) {
                   13600:         $width = 120+$NumBars*8;
                   13601:         $xskip = 5;
                   13602:         $bar_width = 4;
                   13603:     } else {
                   13604:         $width = 120+$NumBars*8;
                   13605:         $xskip = 5;
                   13606:         $bar_width = 4;
                   13607:     }
                   13608:     #
1.137     matthew  13609:     $Max = 1 if ($Max < 1);
                   13610:     if ( int($Max) < $Max ) {
                   13611:         $Max++;
                   13612:         $Max = int($Max);
                   13613:     }
1.127     matthew  13614:     $Title  = '' if (! defined($Title));
                   13615:     $xlabel = '' if (! defined($xlabel));
                   13616:     $ylabel = '' if (! defined($ylabel));
1.369     www      13617:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13618:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13619:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13620:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13621:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13622:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13623:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13624:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13625:     $ValuesHash{$id.'.height'}   = $height;
                   13626:     $ValuesHash{$id.'.width'}    = $width;
                   13627:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13628:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13629:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13630:     #
1.228     matthew  13631:     # Deal with other parameters
                   13632:     while (my ($key,$value) = each(%$extra_settings)) {
                   13633:         $ValuesHash{$id.'.'.$key} = $value;
                   13634:     }
                   13635:     #
1.646     raeburn  13636:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13637:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13638: }
                   13639: 
                   13640: ############################################################
                   13641: ############################################################
                   13642: 
                   13643: =pod
                   13644: 
1.648     raeburn  13645: =item * &DrawXYGraph()
1.137     matthew  13646: 
1.138     matthew  13647: Facilitates the plotting of data in an XY graph.
                   13648: Puts plot definition data into the users environment in order for 
                   13649: graph.png to plot it.  Returns an <img> tag for the plot.
                   13650: 
                   13651: Inputs:
                   13652: 
                   13653: =over 4
                   13654: 
                   13655: =item $Title: string, the title of the plot
                   13656: 
                   13657: =item $xlabel: string, text describing the X-axis of the plot
                   13658: 
                   13659: =item $ylabel: string, text describing the Y-axis of the plot
                   13660: 
                   13661: =item $Max: scalar, the maximum Y value to use in the plot
                   13662: If $Max is < any data point, the graph will not be rendered.
                   13663: 
                   13664: =item $colors: Array ref containing the hex color codes for the data to be 
                   13665: plotted in.  If undefined, default values will be used.
                   13666: 
                   13667: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13668: 
                   13669: =item $Ydata: Array ref containing Array refs.  
1.185     www      13670: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13671: 
                   13672: =item %Values: hash indicating or overriding any default values which are 
                   13673: passed to graph.png.  
                   13674: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13675: 
                   13676: =back
                   13677: 
                   13678: Returns:
                   13679: 
                   13680: An <img> tag which references graph.png and the appropriate identifying
                   13681: information for the plot.
                   13682: 
1.137     matthew  13683: =cut
                   13684: 
                   13685: ############################################################
                   13686: ############################################################
                   13687: sub DrawXYGraph {
                   13688:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13689:     #
                   13690:     # Create the identifier for the graph
                   13691:     my $identifier = &get_cgi_id();
                   13692:     my $id = 'cgi.'.$identifier;
                   13693:     #
                   13694:     $Title  = '' if (! defined($Title));
                   13695:     $xlabel = '' if (! defined($xlabel));
                   13696:     $ylabel = '' if (! defined($ylabel));
                   13697:     my %ValuesHash = 
                   13698:         (
1.369     www      13699:          $id.'.title'  => &escape($Title),
                   13700:          $id.'.xlabel' => &escape($xlabel),
                   13701:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13702:          $id.'.y_max_value'=> $Max,
                   13703:          $id.'.labels'     => join(',',@$Xlabels),
                   13704:          $id.'.PlotType'   => 'XY',
                   13705:          );
                   13706:     #
                   13707:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13708:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13709:     }
                   13710:     #
                   13711:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13712:         return '';
                   13713:     }
                   13714:     my $NumSets=1;
1.138     matthew  13715:     foreach my $array (@{$Ydata}){
1.137     matthew  13716:         next if (! ref($array));
                   13717:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13718:     }
1.138     matthew  13719:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13720:     #
                   13721:     # Deal with other parameters
                   13722:     while (my ($key,$value) = each(%Values)) {
                   13723:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13724:     }
                   13725:     #
1.646     raeburn  13726:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13727:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13728: }
                   13729: 
                   13730: ############################################################
                   13731: ############################################################
                   13732: 
                   13733: =pod
                   13734: 
1.648     raeburn  13735: =item * &DrawXYYGraph()
1.138     matthew  13736: 
                   13737: Facilitates the plotting of data in an XY graph with two Y axes.
                   13738: Puts plot definition data into the users environment in order for 
                   13739: graph.png to plot it.  Returns an <img> tag for the plot.
                   13740: 
                   13741: Inputs:
                   13742: 
                   13743: =over 4
                   13744: 
                   13745: =item $Title: string, the title of the plot
                   13746: 
                   13747: =item $xlabel: string, text describing the X-axis of the plot
                   13748: 
                   13749: =item $ylabel: string, text describing the Y-axis of the plot
                   13750: 
                   13751: =item $colors: Array ref containing the hex color codes for the data to be 
                   13752: plotted in.  If undefined, default values will be used.
                   13753: 
                   13754: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13755: 
                   13756: =item $Ydata1: The first data set
                   13757: 
                   13758: =item $Min1: The minimum value of the left Y-axis
                   13759: 
                   13760: =item $Max1: The maximum value of the left Y-axis
                   13761: 
                   13762: =item $Ydata2: The second data set
                   13763: 
                   13764: =item $Min2: The minimum value of the right Y-axis
                   13765: 
                   13766: =item $Max2: The maximum value of the left Y-axis
                   13767: 
                   13768: =item %Values: hash indicating or overriding any default values which are 
                   13769: passed to graph.png.  
                   13770: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13771: 
                   13772: =back
                   13773: 
                   13774: Returns:
                   13775: 
                   13776: An <img> tag which references graph.png and the appropriate identifying
                   13777: information for the plot.
1.136     matthew  13778: 
                   13779: =cut
                   13780: 
                   13781: ############################################################
                   13782: ############################################################
1.137     matthew  13783: sub DrawXYYGraph {
                   13784:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13785:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13786:     #
                   13787:     # Create the identifier for the graph
                   13788:     my $identifier = &get_cgi_id();
                   13789:     my $id = 'cgi.'.$identifier;
                   13790:     #
                   13791:     $Title  = '' if (! defined($Title));
                   13792:     $xlabel = '' if (! defined($xlabel));
                   13793:     $ylabel = '' if (! defined($ylabel));
                   13794:     my %ValuesHash = 
                   13795:         (
1.369     www      13796:          $id.'.title'  => &escape($Title),
                   13797:          $id.'.xlabel' => &escape($xlabel),
                   13798:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13799:          $id.'.labels' => join(',',@$Xlabels),
                   13800:          $id.'.PlotType' => 'XY',
                   13801:          $id.'.NumSets' => 2,
1.137     matthew  13802:          $id.'.two_axes' => 1,
                   13803:          $id.'.y1_max_value' => $Max1,
                   13804:          $id.'.y1_min_value' => $Min1,
                   13805:          $id.'.y2_max_value' => $Max2,
                   13806:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13807:          );
                   13808:     #
1.137     matthew  13809:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13810:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13811:     }
                   13812:     #
                   13813:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13814:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13815:         return '';
                   13816:     }
                   13817:     my $NumSets=1;
1.137     matthew  13818:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13819:         next if (! ref($array));
                   13820:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13821:     }
                   13822:     #
                   13823:     # Deal with other parameters
                   13824:     while (my ($key,$value) = each(%Values)) {
                   13825:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13826:     }
                   13827:     #
1.646     raeburn  13828:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13829:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13830: }
                   13831: 
                   13832: ############################################################
                   13833: ############################################################
                   13834: 
                   13835: =pod
                   13836: 
1.157     matthew  13837: =back 
                   13838: 
1.139     matthew  13839: =head1 Statistics helper routines?  
                   13840: 
                   13841: Bad place for them but what the hell.
                   13842: 
1.157     matthew  13843: =over 4
                   13844: 
1.648     raeburn  13845: =item * &chartlink()
1.139     matthew  13846: 
                   13847: Returns a link to the chart for a specific student.  
                   13848: 
                   13849: Inputs:
                   13850: 
                   13851: =over 4
                   13852: 
                   13853: =item $linktext: The text of the link
                   13854: 
                   13855: =item $sname: The students username
                   13856: 
                   13857: =item $sdomain: The students domain
                   13858: 
                   13859: =back
                   13860: 
1.157     matthew  13861: =back
                   13862: 
1.139     matthew  13863: =cut
                   13864: 
                   13865: ############################################################
                   13866: ############################################################
                   13867: sub chartlink {
                   13868:     my ($linktext, $sname, $sdomain) = @_;
                   13869:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13870:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13871:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13872:        '">'.$linktext.'</a>';
1.153     matthew  13873: }
                   13874: 
                   13875: #######################################################
                   13876: #######################################################
                   13877: 
                   13878: =pod
                   13879: 
                   13880: =head1 Course Environment Routines
1.157     matthew  13881: 
                   13882: =over 4
1.153     matthew  13883: 
1.648     raeburn  13884: =item * &restore_course_settings()
1.153     matthew  13885: 
1.648     raeburn  13886: =item * &store_course_settings()
1.153     matthew  13887: 
                   13888: Restores/Store indicated form parameters from the course environment.
                   13889: Will not overwrite existing values of the form parameters.
                   13890: 
                   13891: Inputs: 
                   13892: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13893: 
                   13894: a hash ref describing the data to be stored.  For example:
                   13895:    
                   13896: %Save_Parameters = ('Status' => 'scalar',
                   13897:     'chartoutputmode' => 'scalar',
                   13898:     'chartoutputdata' => 'scalar',
                   13899:     'Section' => 'array',
1.373     raeburn  13900:     'Group' => 'array',
1.153     matthew  13901:     'StudentData' => 'array',
                   13902:     'Maps' => 'array');
                   13903: 
                   13904: Returns: both routines return nothing
                   13905: 
1.631     raeburn  13906: =back
                   13907: 
1.153     matthew  13908: =cut
                   13909: 
                   13910: #######################################################
                   13911: #######################################################
                   13912: sub store_course_settings {
1.496     albertel 13913:     return &store_settings($env{'request.course.id'},@_);
                   13914: }
                   13915: 
                   13916: sub store_settings {
1.153     matthew  13917:     # save to the environment
                   13918:     # appenv the same items, just to be safe
1.300     albertel 13919:     my $udom  = $env{'user.domain'};
                   13920:     my $uname = $env{'user.name'};
1.496     albertel 13921:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13922:     my %SaveHash;
                   13923:     my %AppHash;
                   13924:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13925:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13926:         my $envname = 'environment.'.$basename;
1.258     albertel 13927:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13928:             # Save this value away
                   13929:             if ($type eq 'scalar' &&
1.258     albertel 13930:                 (! exists($env{$envname}) || 
                   13931:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13932:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13933:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13934:             } elsif ($type eq 'array') {
                   13935:                 my $stored_form;
1.258     albertel 13936:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13937:                     $stored_form = join(',',
                   13938:                                         map {
1.369     www      13939:                                             &escape($_);
1.258     albertel 13940:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13941:                 } else {
                   13942:                     $stored_form = 
1.369     www      13943:                         &escape($env{'form.'.$setting});
1.153     matthew  13944:                 }
                   13945:                 # Determine if the array contents are the same.
1.258     albertel 13946:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13947:                     $SaveHash{$basename} = $stored_form;
                   13948:                     $AppHash{$envname}   = $stored_form;
                   13949:                 }
                   13950:             }
                   13951:         }
                   13952:     }
                   13953:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13954:                                           $udom,$uname);
1.153     matthew  13955:     if ($put_result !~ /^(ok|delayed)/) {
                   13956:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13957:                                  'got error:'.$put_result);
                   13958:     }
                   13959:     # Make sure these settings stick around in this session, too
1.646     raeburn  13960:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13961:     return;
                   13962: }
                   13963: 
                   13964: sub restore_course_settings {
1.499     albertel 13965:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13966: }
                   13967: 
                   13968: sub restore_settings {
                   13969:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13970:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13971:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13972:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13973:             '.'.$setting;
1.258     albertel 13974:         if (exists($env{$envname})) {
1.153     matthew  13975:             if ($type eq 'scalar') {
1.258     albertel 13976:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13977:             } elsif ($type eq 'array') {
1.258     albertel 13978:                 $env{'form.'.$setting} = [ 
1.153     matthew  13979:                                            map { 
1.369     www      13980:                                                &unescape($_); 
1.258     albertel 13981:                                            } split(',',$env{$envname})
1.153     matthew  13982:                                            ];
                   13983:             }
                   13984:         }
                   13985:     }
1.127     matthew  13986: }
                   13987: 
1.618     raeburn  13988: #######################################################
                   13989: #######################################################
                   13990: 
                   13991: =pod
                   13992: 
                   13993: =head1 Domain E-mail Routines  
                   13994: 
                   13995: =over 4
                   13996: 
1.648     raeburn  13997: =item * &build_recipient_list()
1.618     raeburn  13998: 
1.1144    raeburn  13999: Build recipient lists for following types of e-mail:
1.766     raeburn  14000: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14001: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14002: module change checking, student/employee ID conflict checks, as
                   14003: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14004: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14005: 
                   14006: Inputs:
1.619     raeburn  14007: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14008: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14009: requestsmail, updatesmail, or idconflictsmail).
                   14010: 
1.619     raeburn  14011: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14012: 
1.619     raeburn  14013: origmail (scalar - email address of recipient from loncapa.conf, 
                   14014: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  14015: 
1.655     raeburn  14016: Returns: comma separated list of addresses to which to send e-mail.
                   14017: 
                   14018: =back
1.618     raeburn  14019: 
                   14020: =cut
                   14021: 
                   14022: ############################################################
                   14023: ############################################################
                   14024: sub build_recipient_list {
1.619     raeburn  14025:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  14026:     my @recipients;
                   14027:     my $otheremails;
                   14028:     my %domconfig =
                   14029:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   14030:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14031:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14032:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14033:                 my @contacts = ('adminemail','supportemail');
                   14034:                 foreach my $item (@contacts) {
                   14035:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14036:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14037:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14038:                             push(@recipients,$addr);
                   14039:                         }
1.619     raeburn  14040:                     }
1.766     raeburn  14041:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  14042:                 }
                   14043:             }
1.766     raeburn  14044:         } elsif ($origmail ne '') {
                   14045:             push(@recipients,$origmail);
1.618     raeburn  14046:         }
1.619     raeburn  14047:     } elsif ($origmail ne '') {
                   14048:         push(@recipients,$origmail);
1.618     raeburn  14049:     }
1.688     raeburn  14050:     if (defined($defmail)) {
                   14051:         if ($defmail ne '') {
                   14052:             push(@recipients,$defmail);
                   14053:         }
1.618     raeburn  14054:     }
                   14055:     if ($otheremails) {
1.619     raeburn  14056:         my @others;
                   14057:         if ($otheremails =~ /,/) {
                   14058:             @others = split(/,/,$otheremails);
1.618     raeburn  14059:         } else {
1.619     raeburn  14060:             push(@others,$otheremails);
                   14061:         }
                   14062:         foreach my $addr (@others) {
                   14063:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14064:                 push(@recipients,$addr);
                   14065:             }
1.618     raeburn  14066:         }
                   14067:     }
1.619     raeburn  14068:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  14069:     return $recipientlist;
                   14070: }
                   14071: 
1.127     matthew  14072: ############################################################
                   14073: ############################################################
1.154     albertel 14074: 
1.655     raeburn  14075: =pod
                   14076: 
1.1224    musolffc 14077: =over 4
                   14078: 
1.1223    musolffc 14079: =item * &mime_email()
                   14080: 
                   14081: Sends an email with a possible attachment
                   14082: 
                   14083: Inputs:
                   14084: 
                   14085: =over 4
                   14086: 
                   14087: from -              Sender's email address
                   14088: 
                   14089: to -                Email address of recipient
                   14090: 
                   14091: subject -           Subject of email
                   14092: 
                   14093: body -              Body of email
                   14094: 
                   14095: cc_string -         Carbon copy email address
                   14096: 
                   14097: bcc -               Blind carbon copy email address
                   14098: 
                   14099: type -              File type of attachment
                   14100: 
                   14101: attachment_path -   Path of file to be attached
                   14102: 
                   14103: file_name -         Name of file to be attached
                   14104: 
                   14105: attachment_text -   The body of an attachment of type "TEXT"
                   14106: 
                   14107: =back
                   14108: 
                   14109: =back
                   14110: 
                   14111: =cut
                   14112: 
                   14113: ############################################################
                   14114: ############################################################
                   14115: 
                   14116: sub mime_email {
                   14117:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   14118:         $file_name, $attachment_text) = @_;
                   14119:     my $msg = MIME::Lite->new(
                   14120:              From    => $from,
                   14121:              To      => $to,
                   14122:              Subject => $subject,
                   14123:              Type    =>'TEXT',
                   14124:              Data    => $body,
                   14125:              );
                   14126:     if ($cc_string ne '') {
                   14127:         $msg->add("Cc" => $cc_string);
                   14128:     }
                   14129:     if ($bcc ne '') {
                   14130:         $msg->add("Bcc" => $bcc);
                   14131:     }
                   14132:     $msg->attr("content-type"         => "text/plain");
                   14133:     $msg->attr("content-type.charset" => "UTF-8");
                   14134:     # Attach file if given
                   14135:     if ($attachment_path) {
                   14136:         unless ($file_name) {
                   14137:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   14138:         }
                   14139:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   14140:         $msg->attach(Type     => $type,
                   14141:                      Path     => $attachment_path,
                   14142:                      Filename => $file_name
                   14143:                      );
                   14144:     # Otherwise attach text if given
                   14145:     } elsif ($attachment_text) {
                   14146:         $msg->attach(Type => 'TEXT',
                   14147:                      Data => $attachment_text);
                   14148:     }
                   14149:     # Send it
                   14150:     $msg->send('sendmail');
                   14151: }
                   14152: 
                   14153: ############################################################
                   14154: ############################################################
                   14155: 
                   14156: =pod
                   14157: 
1.655     raeburn  14158: =head1 Course Catalog Routines
                   14159: 
                   14160: =over 4
                   14161: 
                   14162: =item * &gather_categories()
                   14163: 
                   14164: Converts category definitions - keys of categories hash stored in  
                   14165: coursecategories in configuration.db on the primary library server in a 
                   14166: domain - to an array.  Also generates javascript and idx hash used to 
                   14167: generate Domain Coordinator interface for editing Course Categories.
                   14168: 
                   14169: Inputs:
1.663     raeburn  14170: 
1.655     raeburn  14171: categories (reference to hash of category definitions).
1.663     raeburn  14172: 
1.655     raeburn  14173: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14174:       categories and subcategories).
1.663     raeburn  14175: 
1.655     raeburn  14176: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14177:       editing Course Categories).
1.663     raeburn  14178: 
1.655     raeburn  14179: jsarray (reference to array of categories used to create Javascript arrays for
                   14180:          Domain Coordinator interface for editing Course Categories).
                   14181: 
                   14182: Returns: nothing
                   14183: 
                   14184: Side effects: populates cats, idx and jsarray. 
                   14185: 
                   14186: =cut
                   14187: 
                   14188: sub gather_categories {
                   14189:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14190:     my %counters;
                   14191:     my $num = 0;
                   14192:     foreach my $item (keys(%{$categories})) {
                   14193:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14194:         if ($container eq '' && $depth == 0) {
                   14195:             $cats->[$depth][$categories->{$item}] = $cat;
                   14196:         } else {
                   14197:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14198:         }
                   14199:         my ($escitem,$tail) = split(/:/,$item,2);
                   14200:         if ($counters{$tail} eq '') {
                   14201:             $counters{$tail} = $num;
                   14202:             $num ++;
                   14203:         }
                   14204:         if (ref($idx) eq 'HASH') {
                   14205:             $idx->{$item} = $counters{$tail};
                   14206:         }
                   14207:         if (ref($jsarray) eq 'ARRAY') {
                   14208:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14209:         }
                   14210:     }
                   14211:     return;
                   14212: }
                   14213: 
                   14214: =pod
                   14215: 
                   14216: =item * &extract_categories()
                   14217: 
                   14218: Used to generate breadcrumb trails for course categories.
                   14219: 
                   14220: Inputs:
1.663     raeburn  14221: 
1.655     raeburn  14222: categories (reference to hash of category definitions).
1.663     raeburn  14223: 
1.655     raeburn  14224: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14225:       categories and subcategories).
1.663     raeburn  14226: 
1.655     raeburn  14227: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14228: 
1.655     raeburn  14229: allitems (reference to hash - key is category key 
                   14230:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14231: 
1.655     raeburn  14232: idx (reference to hash of counters used in Domain Coordinator interface for
                   14233:       editing Course Categories).
1.663     raeburn  14234: 
1.655     raeburn  14235: jsarray (reference to array of categories used to create Javascript arrays for
                   14236:          Domain Coordinator interface for editing Course Categories).
                   14237: 
1.665     raeburn  14238: subcats (reference to hash of arrays containing all subcategories within each 
                   14239:          category, -recursive)
                   14240: 
1.655     raeburn  14241: Returns: nothing
                   14242: 
                   14243: Side effects: populates trails and allitems hash references.
                   14244: 
                   14245: =cut
                   14246: 
                   14247: sub extract_categories {
1.665     raeburn  14248:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14249:     if (ref($categories) eq 'HASH') {
                   14250:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14251:         if (ref($cats->[0]) eq 'ARRAY') {
                   14252:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14253:                 my $name = $cats->[0][$i];
                   14254:                 my $item = &escape($name).'::0';
                   14255:                 my $trailstr;
                   14256:                 if ($name eq 'instcode') {
                   14257:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14258:                 } elsif ($name eq 'communities') {
                   14259:                     $trailstr = &mt('Communities');
1.655     raeburn  14260:                 } else {
                   14261:                     $trailstr = $name;
                   14262:                 }
                   14263:                 if ($allitems->{$item} eq '') {
                   14264:                     push(@{$trails},$trailstr);
                   14265:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14266:                 }
                   14267:                 my @parents = ($name);
                   14268:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14269:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14270:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14271:                         if (ref($subcats) eq 'HASH') {
                   14272:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14273:                         }
                   14274:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14275:                     }
                   14276:                 } else {
                   14277:                     if (ref($subcats) eq 'HASH') {
                   14278:                         $subcats->{$item} = [];
1.655     raeburn  14279:                     }
                   14280:                 }
                   14281:             }
                   14282:         }
                   14283:     }
                   14284:     return;
                   14285: }
                   14286: 
                   14287: =pod
                   14288: 
1.1162    raeburn  14289: =item * &recurse_categories()
1.655     raeburn  14290: 
                   14291: Recursively used to generate breadcrumb trails for course categories.
                   14292: 
                   14293: Inputs:
1.663     raeburn  14294: 
1.655     raeburn  14295: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14296:       categories and subcategories).
1.663     raeburn  14297: 
1.655     raeburn  14298: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14299: 
                   14300: category (current course category, for which breadcrumb trail is being generated).
                   14301: 
                   14302: trails (reference to array of breadcrumb trails for each category).
                   14303: 
1.655     raeburn  14304: allitems (reference to hash - key is category key
                   14305:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14306: 
1.655     raeburn  14307: parents (array containing containers directories for current category, 
                   14308:          back to top level). 
                   14309: 
                   14310: Returns: nothing
                   14311: 
                   14312: Side effects: populates trails and allitems hash references
                   14313: 
                   14314: =cut
                   14315: 
                   14316: sub recurse_categories {
1.665     raeburn  14317:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14318:     my $shallower = $depth - 1;
                   14319:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14320:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14321:             my $name = $cats->[$depth]{$category}[$k];
                   14322:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14323:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14324:             if ($allitems->{$item} eq '') {
                   14325:                 push(@{$trails},$trailstr);
                   14326:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14327:             }
                   14328:             my $deeper = $depth+1;
                   14329:             push(@{$parents},$category);
1.665     raeburn  14330:             if (ref($subcats) eq 'HASH') {
                   14331:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14332:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14333:                     my $higher;
                   14334:                     if ($j > 0) {
                   14335:                         $higher = &escape($parents->[$j]).':'.
                   14336:                                   &escape($parents->[$j-1]).':'.$j;
                   14337:                     } else {
                   14338:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14339:                     }
                   14340:                     push(@{$subcats->{$higher}},$subcat);
                   14341:                 }
                   14342:             }
                   14343:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14344:                                 $subcats);
1.655     raeburn  14345:             pop(@{$parents});
                   14346:         }
                   14347:     } else {
                   14348:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14349:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14350:         if ($allitems->{$item} eq '') {
                   14351:             push(@{$trails},$trailstr);
                   14352:             $allitems->{$item} = scalar(@{$trails})-1;
                   14353:         }
                   14354:     }
                   14355:     return;
                   14356: }
                   14357: 
1.663     raeburn  14358: =pod
                   14359: 
1.1162    raeburn  14360: =item * &assign_categories_table()
1.663     raeburn  14361: 
                   14362: Create a datatable for display of hierarchical categories in a domain,
                   14363: with checkboxes to allow a course to be categorized. 
                   14364: 
                   14365: Inputs:
                   14366: 
                   14367: cathash - reference to hash of categories defined for the domain (from
                   14368:           configuration.db)
                   14369: 
                   14370: currcat - scalar with an & separated list of categories assigned to a course. 
                   14371: 
1.919     raeburn  14372: type    - scalar contains course type (Course or Community).
                   14373: 
1.663     raeburn  14374: Returns: $output (markup to be displayed) 
                   14375: 
                   14376: =cut
                   14377: 
                   14378: sub assign_categories_table {
1.919     raeburn  14379:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  14380:     my $output;
                   14381:     if (ref($cathash) eq 'HASH') {
                   14382:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14383:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14384:         $maxdepth = scalar(@cats);
                   14385:         if (@cats > 0) {
                   14386:             my $itemcount = 0;
                   14387:             if (ref($cats[0]) eq 'ARRAY') {
                   14388:                 my @currcategories;
                   14389:                 if ($currcat ne '') {
                   14390:                     @currcategories = split('&',$currcat);
                   14391:                 }
1.919     raeburn  14392:                 my $table;
1.663     raeburn  14393:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14394:                     my $parent = $cats[0][$i];
1.919     raeburn  14395:                     next if ($parent eq 'instcode');
                   14396:                     if ($type eq 'Community') {
                   14397:                         next unless ($parent eq 'communities');
                   14398:                     } else {
                   14399:                         next if ($parent eq 'communities');
                   14400:                     }
1.663     raeburn  14401:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14402:                     my $item = &escape($parent).'::0';
                   14403:                     my $checked = '';
                   14404:                     if (@currcategories > 0) {
                   14405:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14406:                             $checked = ' checked="checked"';
1.663     raeburn  14407:                         }
                   14408:                     }
1.919     raeburn  14409:                     my $parent_title = $parent;
                   14410:                     if ($parent eq 'communities') {
                   14411:                         $parent_title = &mt('Communities');
                   14412:                     }
                   14413:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14414:                               '<input type="checkbox" name="usecategory" value="'.
                   14415:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   14416:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14417:                     my $depth = 1;
                   14418:                     push(@path,$parent);
1.919     raeburn  14419:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  14420:                     pop(@path);
1.919     raeburn  14421:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14422:                     $itemcount ++;
                   14423:                 }
1.919     raeburn  14424:                 if ($itemcount) {
                   14425:                     $output = &Apache::loncommon::start_data_table().
                   14426:                               $table.
                   14427:                               &Apache::loncommon::end_data_table();
                   14428:                 }
1.663     raeburn  14429:             }
                   14430:         }
                   14431:     }
                   14432:     return $output;
                   14433: }
                   14434: 
                   14435: =pod
                   14436: 
1.1162    raeburn  14437: =item * &assign_category_rows()
1.663     raeburn  14438: 
                   14439: Create a datatable row for display of nested categories in a domain,
                   14440: with checkboxes to allow a course to be categorized,called recursively.
                   14441: 
                   14442: Inputs:
                   14443: 
                   14444: itemcount - track row number for alternating colors
                   14445: 
                   14446: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14447:       categories and subcategories.
                   14448: 
                   14449: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14450: 
                   14451: parent - parent of current category item
                   14452: 
                   14453: path - Array containing all categories back up through the hierarchy from the
                   14454:        current category to the top level.
                   14455: 
                   14456: currcategories - reference to array of current categories assigned to the course
                   14457: 
                   14458: Returns: $output (markup to be displayed).
                   14459: 
                   14460: =cut
                   14461: 
                   14462: sub assign_category_rows {
                   14463:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   14464:     my ($text,$name,$item,$chgstr);
                   14465:     if (ref($cats) eq 'ARRAY') {
                   14466:         my $maxdepth = scalar(@{$cats});
                   14467:         if (ref($cats->[$depth]) eq 'HASH') {
                   14468:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14469:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14470:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  14471:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14472:                 for (my $j=0; $j<$numchildren; $j++) {
                   14473:                     $name = $cats->[$depth]{$parent}[$j];
                   14474:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14475:                     my $deeper = $depth+1;
                   14476:                     my $checked = '';
                   14477:                     if (ref($currcategories) eq 'ARRAY') {
                   14478:                         if (@{$currcategories} > 0) {
                   14479:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14480:                                 $checked = ' checked="checked"';
1.663     raeburn  14481:                             }
                   14482:                         }
                   14483:                     }
1.664     raeburn  14484:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14485:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  14486:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   14487:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14488:                              '</td><td>';
1.663     raeburn  14489:                     if (ref($path) eq 'ARRAY') {
                   14490:                         push(@{$path},$name);
                   14491:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   14492:                         pop(@{$path});
                   14493:                     }
                   14494:                     $text .= '</td></tr>';
                   14495:                 }
                   14496:                 $text .= '</table></td>';
                   14497:             }
                   14498:         }
                   14499:     }
                   14500:     return $text;
                   14501: }
                   14502: 
1.1181    raeburn  14503: =pod
                   14504: 
                   14505: =back
                   14506: 
                   14507: =cut
                   14508: 
1.655     raeburn  14509: ############################################################
                   14510: ############################################################
                   14511: 
                   14512: 
1.443     albertel 14513: sub commit_customrole {
1.664     raeburn  14514:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14515:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14516:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14517:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14518:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14519:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14520:                  '</b><br />';
                   14521:     return $output;
                   14522: }
                   14523: 
                   14524: sub commit_standardrole {
1.1116    raeburn  14525:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14526:     my ($output,$logmsg,$linefeed);
                   14527:     if ($context eq 'auto') {
                   14528:         $linefeed = "\n";
                   14529:     } else {
                   14530:         $linefeed = "<br />\n";
                   14531:     }  
1.443     albertel 14532:     if ($three eq 'st') {
1.541     raeburn  14533:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  14534:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14535:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14536:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14537:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14538:         } else {
1.541     raeburn  14539:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14540:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14541:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14542:             if ($context eq 'auto') {
                   14543:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14544:             } else {
                   14545:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14546:                &mt('Add to classlist').': <b>ok</b>';
                   14547:             }
                   14548:             $output .= $linefeed;
1.443     albertel 14549:         }
                   14550:     } else {
                   14551:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14552:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14553:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14554:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14555:         if ($context eq 'auto') {
                   14556:             $output .= $result.$linefeed;
                   14557:         } else {
                   14558:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14559:         }
1.443     albertel 14560:     }
                   14561:     return $output;
                   14562: }
                   14563: 
                   14564: sub commit_studentrole {
1.1116    raeburn  14565:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14566:         $credits) = @_;
1.626     raeburn  14567:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14568:     if ($context eq 'auto') {
                   14569:         $linefeed = "\n";
                   14570:     } else {
                   14571:         $linefeed = '<br />'."\n";
                   14572:     }
1.443     albertel 14573:     if (defined($one) && defined($two)) {
                   14574:         my $cid=$one.'_'.$two;
                   14575:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14576:         my $secchange = 0;
                   14577:         my $expire_role_result;
                   14578:         my $modify_section_result;
1.628     raeburn  14579:         if ($oldsec ne '-1') { 
                   14580:             if ($oldsec ne $sec) {
1.443     albertel 14581:                 $secchange = 1;
1.628     raeburn  14582:                 my $now = time;
1.443     albertel 14583:                 my $uurl='/'.$cid;
                   14584:                 $uurl=~s/\_/\//g;
                   14585:                 if ($oldsec) {
                   14586:                     $uurl.='/'.$oldsec;
                   14587:                 }
1.626     raeburn  14588:                 $oldsecurl = $uurl;
1.628     raeburn  14589:                 $expire_role_result = 
1.652     raeburn  14590:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14591:                 if ($env{'request.course.sec'} ne '') { 
                   14592:                     if ($expire_role_result eq 'refused') {
                   14593:                         my @roles = ('st');
                   14594:                         my @statuses = ('previous');
                   14595:                         my @roledoms = ($one);
                   14596:                         my $withsec = 1;
                   14597:                         my %roleshash = 
                   14598:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14599:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14600:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14601:                             my ($oldstart,$oldend) = 
                   14602:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14603:                             if ($oldend > 0 && $oldend <= $now) {
                   14604:                                 $expire_role_result = 'ok';
                   14605:                             }
                   14606:                         }
                   14607:                     }
                   14608:                 }
1.443     albertel 14609:                 $result = $expire_role_result;
                   14610:             }
                   14611:         }
                   14612:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  14613:             $modify_section_result = 
                   14614:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14615:                                                            undef,undef,undef,$sec,
                   14616:                                                            $end,$start,'','',$cid,
                   14617:                                                            '',$context,$credits);
1.443     albertel 14618:             if ($modify_section_result =~ /^ok/) {
                   14619:                 if ($secchange == 1) {
1.628     raeburn  14620:                     if ($sec eq '') {
                   14621:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14622:                     } else {
                   14623:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14624:                     }
1.443     albertel 14625:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14626:                     if ($sec eq '') {
                   14627:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14628:                     } else {
                   14629:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14630:                     }
1.443     albertel 14631:                 } else {
1.628     raeburn  14632:                     if ($sec eq '') {
                   14633:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14634:                     } else {
                   14635:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14636:                     }
1.443     albertel 14637:                 }
                   14638:             } else {
1.1115    raeburn  14639:                 if ($secchange) { 
1.628     raeburn  14640:                     $$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;
                   14641:                 } else {
                   14642:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14643:                 }
1.443     albertel 14644:             }
                   14645:             $result = $modify_section_result;
                   14646:         } elsif ($secchange == 1) {
1.628     raeburn  14647:             if ($oldsec eq '') {
1.1103    raeburn  14648:                 $$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  14649:             } else {
                   14650:                 $$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;
                   14651:             }
1.626     raeburn  14652:             if ($expire_role_result eq 'refused') {
                   14653:                 my $newsecurl = '/'.$cid;
                   14654:                 $newsecurl =~ s/\_/\//g;
                   14655:                 if ($sec ne '') {
                   14656:                     $newsecurl.='/'.$sec;
                   14657:                 }
                   14658:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14659:                     if ($sec eq '') {
                   14660:                         $$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;
                   14661:                     } else {
                   14662:                         $$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;
                   14663:                     }
                   14664:                 }
                   14665:             }
1.443     albertel 14666:         }
                   14667:     } else {
1.626     raeburn  14668:         $$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 14669:         $result = "error: incomplete course id\n";
                   14670:     }
                   14671:     return $result;
                   14672: }
                   14673: 
1.1108    raeburn  14674: sub show_role_extent {
                   14675:     my ($scope,$context,$role) = @_;
                   14676:     $scope =~ s{^/}{};
                   14677:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14678:     push(@courseroles,'co');
                   14679:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14680:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14681:         $scope =~ s{/}{_};
                   14682:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14683:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14684:         my ($audom,$auname) = split(/\//,$scope);
                   14685:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14686:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14687:     } else {
                   14688:         $scope =~ s{/$}{};
                   14689:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14690:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14691:     }
                   14692: }
                   14693: 
1.443     albertel 14694: ############################################################
                   14695: ############################################################
                   14696: 
1.566     albertel 14697: sub check_clone {
1.578     raeburn  14698:     my ($args,$linefeed) = @_;
1.566     albertel 14699:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14700:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14701:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14702:     my $clonemsg;
                   14703:     my $can_clone = 0;
1.944     raeburn  14704:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14705:     if ($lctype ne 'community') {
                   14706:         $lctype = 'course';
                   14707:     }
1.566     albertel 14708:     if ($clonehome eq 'no_host') {
1.944     raeburn  14709:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14710:             $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'});
                   14711:         } else {
                   14712:             $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'});
                   14713:         }     
1.566     albertel 14714:     } else {
                   14715: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14716:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14717:             if ($clonedesc{'type'} ne 'Community') {
                   14718:                  $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'});
                   14719:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14720:             }
                   14721:         }
1.882     raeburn  14722: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   14723:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14724: 	    $can_clone = 1;
                   14725: 	} else {
1.1221    raeburn  14726: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 14727: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  14728:             if ($clonehash{'cloners'} eq '') {
                   14729:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   14730:                 if ($domdefs{'canclone'}) {
                   14731:                     unless ($domdefs{'canclone'} eq 'none') {
                   14732:                         if ($domdefs{'canclone'} eq 'domain') {
                   14733:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   14734:                                 $can_clone = 1;
                   14735:                             }
                   14736:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   14737:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   14738:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   14739:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   14740:                                 $can_clone = 1;
                   14741:                             }
                   14742:                         }
                   14743:                     }
                   14744:                 }
1.578     raeburn  14745:             } else {
1.1221    raeburn  14746: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   14747:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  14748:                     $can_clone = 1;
1.1221    raeburn  14749:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  14750:                     $can_clone = 1;
1.1225    raeburn  14751:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14752:                     $can_clone = 1;
1.1221    raeburn  14753:                 }
                   14754:                 unless ($can_clone) {
1.1225    raeburn  14755:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   14756:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  14757:                         my (%gotdomdefaults,%gotcodedefaults);
                   14758:                         foreach my $cloner (@cloners) {
                   14759:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   14760:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   14761:                                 my (%codedefaults,@code_order);
                   14762:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   14763:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   14764:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   14765:                                     }
                   14766:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   14767:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   14768:                                     }
                   14769:                                 } else {
                   14770:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   14771:                                                                             \%codedefaults,
                   14772:                                                                             \@code_order);
                   14773:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   14774:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   14775:                                 }
                   14776:                                 if (@code_order > 0) {
                   14777:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   14778:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   14779:                                                                                 $args->{'crscode'})) {
                   14780:                                         $can_clone = 1;
                   14781:                                         last;
                   14782:                                     }
                   14783:                                 }
                   14784:                             }
                   14785:                         }
                   14786:                     }
1.1225    raeburn  14787:                 }
                   14788:             }
                   14789:             unless ($can_clone) {
                   14790:                 my $ccrole = 'cc';
                   14791:                 if ($args->{'crstype'} eq 'Community') {
                   14792:                     $ccrole = 'co';
                   14793:                 }
                   14794: 	        my %roleshash =
                   14795: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14796: 					          $args->{'ccdomain'},
                   14797:                                                   'userroles',['active'],[$ccrole],
                   14798: 					          [$args->{'clonedomain'}]);
                   14799: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   14800:                     $can_clone = 1;
                   14801:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   14802:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   14803:                     $can_clone = 1;
1.1221    raeburn  14804:                 }
                   14805:             }
                   14806:             unless ($can_clone) {
                   14807:                 if ($args->{'crstype'} eq 'Community') {
                   14808:                     $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  14809:                 } else {
1.1221    raeburn  14810:                     $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'});
                   14811:                 }
1.566     albertel 14812: 	    }
1.578     raeburn  14813:         }
1.566     albertel 14814:     }
                   14815:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14816: }
                   14817: 
1.444     albertel 14818: sub construct_course {
1.1166    raeburn  14819:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 14820:     my $outcome;
1.541     raeburn  14821:     my $linefeed =  '<br />'."\n";
                   14822:     if ($context eq 'auto') {
                   14823:         $linefeed = "\n";
                   14824:     }
1.566     albertel 14825: 
                   14826: #
                   14827: # Are we cloning?
                   14828: #
                   14829:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14830:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14831: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14832: 	if ($context ne 'auto') {
1.578     raeburn  14833:             if ($clonemsg ne '') {
                   14834: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14835:             }
1.566     albertel 14836: 	}
                   14837: 	$outcome .= $clonemsg.$linefeed;
                   14838: 
                   14839:         if (!$can_clone) {
                   14840: 	    return (0,$outcome);
                   14841: 	}
                   14842:     }
                   14843: 
1.444     albertel 14844: #
                   14845: # Open course
                   14846: #
                   14847:     my $crstype = lc($args->{'crstype'});
                   14848:     my %cenv=();
                   14849:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14850:                                              $args->{'cdescr'},
                   14851:                                              $args->{'curl'},
                   14852:                                              $args->{'course_home'},
                   14853:                                              $args->{'nonstandard'},
                   14854:                                              $args->{'crscode'},
                   14855:                                              $args->{'ccuname'}.':'.
                   14856:                                              $args->{'ccdomain'},
1.882     raeburn  14857:                                              $args->{'crstype'},
1.885     raeburn  14858:                                              $cnum,$context,$category);
1.444     albertel 14859: 
                   14860:     # Note: The testing routines depend on this being output; see 
                   14861:     # Utils::Course. This needs to at least be output as a comment
                   14862:     # if anyone ever decides to not show this, and Utils::Course::new
                   14863:     # will need to be suitably modified.
1.541     raeburn  14864:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14865:     if ($$courseid =~ /^error:/) {
                   14866:         return (0,$outcome);
                   14867:     }
                   14868: 
1.444     albertel 14869: #
                   14870: # Check if created correctly
                   14871: #
1.479     albertel 14872:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14873:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14874:     if ($crsuhome eq 'no_host') {
                   14875:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14876:         return (0,$outcome);
                   14877:     }
1.541     raeburn  14878:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14879: 
1.444     albertel 14880: #
1.566     albertel 14881: # Do the cloning
                   14882: #   
                   14883:     if ($can_clone && $cloneid) {
                   14884: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14885: 	if ($context ne 'auto') {
                   14886: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14887: 	}
                   14888: 	$outcome .= $clonemsg.$linefeed;
                   14889: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14890: # Copy all files
1.637     www      14891: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14892: # Restore URL
1.566     albertel 14893: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14894: # Restore title
1.566     albertel 14895: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14896: # Restore creation date, creator and creation context.
                   14897:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14898:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14899:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14900: # Mark as cloned
1.566     albertel 14901: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14902: # Need to clone grading mode
                   14903:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14904:         $cenv{'grading'}=$newenv{'grading'};
                   14905: # Do not clone these environment entries
                   14906:         &Apache::lonnet::del('environment',
                   14907:                   ['default_enrollment_start_date',
                   14908:                    'default_enrollment_end_date',
                   14909:                    'question.email',
                   14910:                    'policy.email',
                   14911:                    'comment.email',
                   14912:                    'pch.users.denied',
1.725     raeburn  14913:                    'plc.users.denied',
                   14914:                    'hidefromcat',
1.1121    raeburn  14915:                    'checkforpriv',
1.1166    raeburn  14916:                    'categories',
                   14917:                    'internal.uniquecode'],
1.638     www      14918:                    $$crsudom,$$crsunum);
1.1170    raeburn  14919:         if ($args->{'textbook'}) {
                   14920:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14921:         }
1.444     albertel 14922:     }
1.566     albertel 14923: 
1.444     albertel 14924: #
                   14925: # Set environment (will override cloned, if existing)
                   14926: #
                   14927:     my @sections = ();
                   14928:     my @xlists = ();
                   14929:     if ($args->{'crstype'}) {
                   14930:         $cenv{'type'}=$args->{'crstype'};
                   14931:     }
                   14932:     if ($args->{'crsid'}) {
                   14933:         $cenv{'courseid'}=$args->{'crsid'};
                   14934:     }
                   14935:     if ($args->{'crscode'}) {
                   14936:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14937:     }
                   14938:     if ($args->{'crsquota'} ne '') {
                   14939:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14940:     } else {
                   14941:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14942:     }
                   14943:     if ($args->{'ccuname'}) {
                   14944:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14945:                                         ':'.$args->{'ccdomain'};
                   14946:     } else {
                   14947:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14948:     }
1.1116    raeburn  14949:     if ($args->{'defaultcredits'}) {
                   14950:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14951:     }
1.444     albertel 14952:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14953:     if ($args->{'crssections'}) {
                   14954:         $cenv{'internal.sectionnums'} = '';
                   14955:         if ($args->{'crssections'} =~ m/,/) {
                   14956:             @sections = split/,/,$args->{'crssections'};
                   14957:         } else {
                   14958:             $sections[0] = $args->{'crssections'};
                   14959:         }
                   14960:         if (@sections > 0) {
                   14961:             foreach my $item (@sections) {
                   14962:                 my ($sec,$gp) = split/:/,$item;
                   14963:                 my $class = $args->{'crscode'}.$sec;
                   14964:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14965:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14966:                 unless ($addcheck eq 'ok') {
                   14967:                     push @badclasses, $class;
                   14968:                 }
                   14969:             }
                   14970:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14971:         }
                   14972:     }
                   14973: # do not hide course coordinator from staff listing, 
                   14974: # even if privileged
                   14975:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  14976: # add course coordinator's domain to domains to check for privileged users
                   14977: # if different to course domain
                   14978:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14979:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14980:     }
1.444     albertel 14981: # add crosslistings
                   14982:     if ($args->{'crsxlist'}) {
                   14983:         $cenv{'internal.crosslistings'}='';
                   14984:         if ($args->{'crsxlist'} =~ m/,/) {
                   14985:             @xlists = split/,/,$args->{'crsxlist'};
                   14986:         } else {
                   14987:             $xlists[0] = $args->{'crsxlist'};
                   14988:         }
                   14989:         if (@xlists > 0) {
                   14990:             foreach my $item (@xlists) {
                   14991:                 my ($xl,$gp) = split/:/,$item;
                   14992:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14993:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14994:                 unless ($addcheck eq 'ok') {
                   14995:                     push @badclasses, $xl;
                   14996:                 }
                   14997:             }
                   14998:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14999:         }
                   15000:     }
                   15001:     if ($args->{'autoadds'}) {
                   15002:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15003:     }
                   15004:     if ($args->{'autodrops'}) {
                   15005:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15006:     }
                   15007: # check for notification of enrollment changes
                   15008:     my @notified = ();
                   15009:     if ($args->{'notify_owner'}) {
                   15010:         if ($args->{'ccuname'} ne '') {
                   15011:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15012:         }
                   15013:     }
                   15014:     if ($args->{'notify_dc'}) {
                   15015:         if ($uname ne '') { 
1.630     raeburn  15016:             push(@notified,$uname.':'.$udom);
1.444     albertel 15017:         }
                   15018:     }
                   15019:     if (@notified > 0) {
                   15020:         my $notifylist;
                   15021:         if (@notified > 1) {
                   15022:             $notifylist = join(',',@notified);
                   15023:         } else {
                   15024:             $notifylist = $notified[0];
                   15025:         }
                   15026:         $cenv{'internal.notifylist'} = $notifylist;
                   15027:     }
                   15028:     if (@badclasses > 0) {
                   15029:         my %lt=&Apache::lonlocal::texthash(
                   15030:                 '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',
                   15031:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   15032:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   15033:         );
1.541     raeburn  15034:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   15035:                            ' ('.$lt{'adby'}.')';
                   15036:         if ($context eq 'auto') {
                   15037:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 15038:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  15039:             foreach my $item (@badclasses) {
                   15040:                 if ($context eq 'auto') {
                   15041:                     $outcome .= " - $item\n";
                   15042:                 } else {
                   15043:                     $outcome .= "<li>$item</li>\n";
                   15044:                 }
                   15045:             }
                   15046:             if ($context eq 'auto') {
                   15047:                 $outcome .= $linefeed;
                   15048:             } else {
1.566     albertel 15049:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  15050:             }
                   15051:         } 
1.444     albertel 15052:     }
                   15053:     if ($args->{'no_end_date'}) {
                   15054:         $args->{'endaccess'} = 0;
                   15055:     }
                   15056:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15057:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15058:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15059:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15060:     if ($args->{'showphotos'}) {
                   15061:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15062:     }
                   15063:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15064:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15065:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15066:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15067:             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'); 
                   15068:             if ($context eq 'auto') {
                   15069:                 $outcome .= $krb_msg;
                   15070:             } else {
1.566     albertel 15071:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15072:             }
                   15073:             $outcome .= $linefeed;
1.444     albertel 15074:         }
                   15075:     }
                   15076:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15077:        if ($args->{'setpolicy'}) {
                   15078:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15079:        }
                   15080:        if ($args->{'setcontent'}) {
                   15081:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15082:        }
                   15083:     }
                   15084:     if ($args->{'reshome'}) {
                   15085: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15086: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15087:     }
                   15088: #
                   15089: # course has keyed access
                   15090: #
                   15091:     if ($args->{'setkeys'}) {
                   15092:        $cenv{'keyaccess'}='yes';
                   15093:     }
                   15094: # if specified, key authority is not course, but user
                   15095: # only active if keyaccess is yes
                   15096:     if ($args->{'keyauth'}) {
1.487     albertel 15097: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15098: 	$user = &LONCAPA::clean_username($user);
                   15099: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15100: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15101: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15102: 	}
                   15103:     }
                   15104: 
1.1166    raeburn  15105: #
1.1167    raeburn  15106: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  15107: #
                   15108:     if ($args->{'uniquecode'}) {
                   15109:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15110:         if ($code) {
                   15111:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  15112:             my %crsinfo =
                   15113:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15114:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15115:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15116:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15117:             } 
1.1166    raeburn  15118:             if (ref($coderef)) {
                   15119:                 $$coderef = $code;
                   15120:             }
                   15121:         }
                   15122:     }
                   15123: 
1.444     albertel 15124:     if ($args->{'disresdis'}) {
                   15125:         $cenv{'pch.roles.denied'}='st';
                   15126:     }
                   15127:     if ($args->{'disablechat'}) {
                   15128:         $cenv{'plc.roles.denied'}='st';
                   15129:     }
                   15130: 
                   15131:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15132:     # course
                   15133:     $cenv{'course.helper.not.run'} = 1;
                   15134:     #
                   15135:     # Use new Randomseed
                   15136:     #
                   15137:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15138:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15139:     #
                   15140:     # The encryption code and receipt prefix for this course
                   15141:     #
                   15142:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15143:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15144:     #
                   15145:     # By default, use standard grading
                   15146:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15147: 
1.541     raeburn  15148:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15149:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15150: #
                   15151: # Open all assignments
                   15152: #
                   15153:     if ($args->{'openall'}) {
                   15154:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15155:        my %storecontent = ($storeunder         => time,
                   15156:                            $storeunder.'.type' => 'date_start');
                   15157:        
                   15158:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15159:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15160:    }
                   15161: #
                   15162: # Set first page
                   15163: #
                   15164:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15165: 	    || ($cloneid)) {
1.445     albertel 15166: 	use LONCAPA::map;
1.444     albertel 15167: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15168: 
                   15169: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15170:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15171: 
1.444     albertel 15172:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15173:         my $title; my $url;
                   15174:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15175: 	    $title=&mt('Syllabus');
1.444     albertel 15176:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15177:         } else {
1.963     raeburn  15178:             $title=&mt('Table of Contents');
1.444     albertel 15179:             $url='/adm/navmaps';
                   15180:         }
1.445     albertel 15181: 
                   15182:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15183: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15184: 
                   15185: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15186:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15187:     }
1.566     albertel 15188: 
                   15189:     return (1,$outcome);
1.444     albertel 15190: }
                   15191: 
1.1166    raeburn  15192: sub make_unique_code {
                   15193:     my ($cdom,$cnum) = @_;
                   15194:     # get lock on uniquecodes db
                   15195:     my $lockhash = {
                   15196:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15197:                                                   ':'.$env{'user.domain'},
                   15198:                    };
                   15199:     my $tries = 0;
                   15200:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15201:     my ($code,$error);
                   15202:   
                   15203:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15204:         $tries ++;
                   15205:         sleep 1;
                   15206:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15207:     }
                   15208:     if ($gotlock eq 'ok') {
                   15209:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15210:         my $gotcode;
                   15211:         my $attempts = 0;
                   15212:         while ((!$gotcode) && ($attempts < 100)) {
                   15213:             $code = &generate_code();
                   15214:             if (!exists($currcodes{$code})) {
                   15215:                 $gotcode = 1;
                   15216:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15217:                     $error = 'nostore';
                   15218:                 }
                   15219:             }
                   15220:             $attempts ++;
                   15221:         }
                   15222:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15223:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15224:     } else {
                   15225:         $error = 'nolock';
                   15226:     }
                   15227:     return ($code,$error);
                   15228: }
                   15229: 
                   15230: sub generate_code {
                   15231:     my $code;
                   15232:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15233:     for (my $i=0; $i<6; $i++) {
                   15234:         my $lettnum = int (rand 2);
                   15235:         my $item = '';
                   15236:         if ($lettnum) {
                   15237:             $item = $letts[int( rand(18) )];
                   15238:         } else {
                   15239:             $item = 1+int( rand(8) );
                   15240:         }
                   15241:         $code .= $item;
                   15242:     }
                   15243:     return $code;
                   15244: }
                   15245: 
1.444     albertel 15246: ############################################################
                   15247: ############################################################
                   15248: 
1.953     droeschl 15249: #SD
                   15250: # only Community and Course, or anything else?
1.378     raeburn  15251: sub course_type {
                   15252:     my ($cid) = @_;
                   15253:     if (!defined($cid)) {
                   15254:         $cid = $env{'request.course.id'};
                   15255:     }
1.404     albertel 15256:     if (defined($env{'course.'.$cid.'.type'})) {
                   15257:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15258:     } else {
                   15259:         return 'Course';
1.377     raeburn  15260:     }
                   15261: }
1.156     albertel 15262: 
1.406     raeburn  15263: sub group_term {
                   15264:     my $crstype = &course_type();
                   15265:     my %names = (
                   15266:                   'Course' => 'group',
1.865     raeburn  15267:                   'Community' => 'group',
1.406     raeburn  15268:                 );
                   15269:     return $names{$crstype};
                   15270: }
                   15271: 
1.902     raeburn  15272: sub course_types {
1.1165    raeburn  15273:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15274:     my %typename = (
                   15275:                          official   => 'Official course',
                   15276:                          unofficial => 'Unofficial course',
                   15277:                          community  => 'Community',
1.1165    raeburn  15278:                          textbook   => 'Textbook course',
1.902     raeburn  15279:                    );
                   15280:     return (\@types,\%typename);
                   15281: }
                   15282: 
1.156     albertel 15283: sub icon {
                   15284:     my ($file)=@_;
1.505     albertel 15285:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15286:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15287:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15288:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15289: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15290: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15291: 	            $curfext.".gif") {
                   15292: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15293: 		$curfext.".gif";
                   15294: 	}
                   15295:     }
1.249     albertel 15296:     return &lonhttpdurl($iconname);
1.154     albertel 15297: } 
1.84      albertel 15298: 
1.575     albertel 15299: sub lonhttpdurl {
1.692     www      15300: #
                   15301: # Had been used for "small fry" static images on separate port 8080.
                   15302: # Modify here if lightweight http functionality desired again.
                   15303: # Currently eliminated due to increasing firewall issues.
                   15304: #
1.575     albertel 15305:     my ($url)=@_;
1.692     www      15306:     return $url;
1.215     albertel 15307: }
                   15308: 
1.213     albertel 15309: sub connection_aborted {
                   15310:     my ($r)=@_;
                   15311:     $r->print(" ");$r->rflush();
                   15312:     my $c = $r->connection;
                   15313:     return $c->aborted();
                   15314: }
                   15315: 
1.221     foxr     15316: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15317: #    strings as 'strings'.
                   15318: sub escape_single {
1.221     foxr     15319:     my ($input) = @_;
1.223     albertel 15320:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15321:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15322:     return $input;
                   15323: }
1.223     albertel 15324: 
1.222     foxr     15325: #  Same as escape_single, but escape's "'s  This 
                   15326: #  can be used for  "strings"
                   15327: sub escape_double {
                   15328:     my ($input) = @_;
                   15329:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15330:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15331:     return $input;
                   15332: }
1.223     albertel 15333:  
1.222     foxr     15334: #   Escapes the last element of a full URL.
                   15335: sub escape_url {
                   15336:     my ($url)   = @_;
1.238     raeburn  15337:     my @urlslices = split(/\//, $url,-1);
1.369     www      15338:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  15339:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15340: }
1.462     albertel 15341: 
1.820     raeburn  15342: sub compare_arrays {
                   15343:     my ($arrayref1,$arrayref2) = @_;
                   15344:     my (@difference,%count);
                   15345:     @difference = ();
                   15346:     %count = ();
                   15347:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15348:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15349:         foreach my $element (keys(%count)) {
                   15350:             if ($count{$element} == 1) {
                   15351:                 push(@difference,$element);
                   15352:             }
                   15353:         }
                   15354:     }
                   15355:     return @difference;
                   15356: }
                   15357: 
1.817     bisitz   15358: # -------------------------------------------------------- Initialize user login
1.462     albertel 15359: sub init_user_environment {
1.463     albertel 15360:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15361:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15362: 
                   15363:     my $public=($username eq 'public' && $domain eq 'public');
                   15364: 
                   15365: # See if old ID present, if so, remove
                   15366: 
1.1062    raeburn  15367:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15368:     my $now=time;
                   15369: 
                   15370:     if ($public) {
                   15371: 	my $max_public=100;
                   15372: 	my $oldest;
                   15373: 	my $oldest_time=0;
                   15374: 	for(my $next=1;$next<=$max_public;$next++) {
                   15375: 	    if (-e $lonids."/publicuser_$next.id") {
                   15376: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15377: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15378: 		    $oldest_time=$mtime;
                   15379: 		    $oldest=$next;
                   15380: 		}
                   15381: 	    } else {
                   15382: 		$cookie="publicuser_$next";
                   15383: 		last;
                   15384: 	    }
                   15385: 	}
                   15386: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15387:     } else {
1.463     albertel 15388: 	# if this isn't a robot, kill any existing non-robot sessions
                   15389: 	if (!$args->{'robot'}) {
                   15390: 	    opendir(DIR,$lonids);
                   15391: 	    while ($filename=readdir(DIR)) {
                   15392: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   15393: 		    unlink($lonids.'/'.$filename);
                   15394: 		}
1.462     albertel 15395: 	    }
1.463     albertel 15396: 	    closedir(DIR);
1.1204    raeburn  15397: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15398:             my $namespace = 'nohist_courseeditor';
                   15399:             my $lockingkey = 'paste'."\0".'locked_num';
                   15400:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15401:                                                 $domain,$username);
                   15402:             if (exists($lockhash{$lockingkey})) {
                   15403:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15404:                 unless ($delresult eq 'ok') {
                   15405:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15406:                 }
                   15407:             }
1.462     albertel 15408: 	}
                   15409: # Give them a new cookie
1.463     albertel 15410: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15411: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15412: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15413:     
                   15414: # Initialize roles
                   15415: 
1.1062    raeburn  15416: 	($userroles,$firstaccenv,$timerintenv) = 
                   15417:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15418:     }
                   15419: # ------------------------------------ Check browser type and MathML capability
                   15420: 
1.1194    raeburn  15421:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15422:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15423: 
                   15424: # ------------------------------------------------------------- Get environment
                   15425: 
                   15426:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15427:     my ($tmp) = keys(%userenv);
                   15428:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15429:     } else {
                   15430: 	undef(%userenv);
                   15431:     }
                   15432:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15433: 	$form->{'interface'}=$userenv{'interface'};
                   15434:     }
                   15435:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15436: 
                   15437: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15438:     foreach my $option ('interface','localpath','localres') {
                   15439:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15440:     }
                   15441: # --------------------------------------------------------- Write first profile
                   15442: 
                   15443:     {
                   15444: 	my %initial_env = 
                   15445: 	    ("user.name"          => $username,
                   15446: 	     "user.domain"        => $domain,
                   15447: 	     "user.home"          => $authhost,
                   15448: 	     "browser.type"       => $clientbrowser,
                   15449: 	     "browser.version"    => $clientversion,
                   15450: 	     "browser.mathml"     => $clientmathml,
                   15451: 	     "browser.unicode"    => $clientunicode,
                   15452: 	     "browser.os"         => $clientos,
1.1137    raeburn  15453:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  15454:              "browser.info"       => $clientinfo,
1.1194    raeburn  15455:              "browser.osversion"  => $clientosversion,
1.462     albertel 15456: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15457: 	     "request.course.fn"  => '',
                   15458: 	     "request.course.uri" => '',
                   15459: 	     "request.course.sec" => '',
                   15460: 	     "request.role"       => 'cm',
                   15461: 	     "request.role.adv"   => $env{'user.adv'},
                   15462: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15463: 
                   15464:         if ($form->{'localpath'}) {
                   15465: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15466: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15467:         }
                   15468: 	
                   15469: 	if ($form->{'interface'}) {
                   15470: 	    $form->{'interface'}=~s/\W//gs;
                   15471: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15472: 	    $env{'browser.interface'}=$form->{'interface'};
                   15473: 	}
                   15474: 
1.1157    raeburn  15475:         if ($form->{'iptoken'}) {
                   15476:             my $lonhost = $r->dir_config('lonHostID');
                   15477:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15478:             $env{'user.noloadbalance'} = $lonhost;
                   15479:         }
                   15480: 
1.981     raeburn  15481:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  15482:         my %domdef;
                   15483:         unless ($domain eq 'public') {
                   15484:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   15485:         }
1.980     raeburn  15486: 
1.1081    raeburn  15487:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  15488:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  15489:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15490:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  15491:         }
                   15492: 
1.1165    raeburn  15493:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  15494:             $userenv{'canrequest.'.$crstype} =
                   15495:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  15496:                                                   'reload','requestcourses',
                   15497:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  15498:         }
                   15499: 
1.1092    raeburn  15500:         $userenv{'canrequest.author'} =
                   15501:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15502:                                         'reload','requestauthor',
                   15503:                                         \%userenv,\%domdef,\%is_adv);
                   15504:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15505:                                              $domain,$username);
                   15506:         my $reqstatus = $reqauthor{'author_status'};
                   15507:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   15508:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   15509:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15510:                                                   $reqauthor{'author'}{'timestamp'};
                   15511:             }
                   15512:         }
                   15513: 
1.462     albertel 15514: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15515: 
1.462     albertel 15516: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15517: 		 &GDBM_WRCREAT(),0640)) {
                   15518: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15519: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15520: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15521:             if (ref($firstaccenv) eq 'HASH') {
                   15522:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15523:             }
                   15524:             if (ref($timerintenv) eq 'HASH') {
                   15525:                 &_add_to_env(\%disk_env,$timerintenv);
                   15526:             }
1.463     albertel 15527: 	    if (ref($args->{'extra_env'})) {
                   15528: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15529: 	    }
1.462     albertel 15530: 	    untie(%disk_env);
                   15531: 	} else {
1.705     tempelho 15532: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15533: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15534: 	    return 'error: '.$!;
                   15535: 	}
                   15536:     }
                   15537:     $env{'request.role'}='cm';
                   15538:     $env{'request.role.adv'}=$env{'user.adv'};
                   15539:     $env{'browser.type'}=$clientbrowser;
                   15540: 
                   15541:     return $cookie;
                   15542: 
                   15543: }
                   15544: 
                   15545: sub _add_to_env {
                   15546:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15547:     if (ref($env_data) eq 'HASH') {
                   15548:         while (my ($key,$value) = each(%$env_data)) {
                   15549: 	    $idf->{$prefix.$key} = $value;
                   15550: 	    $env{$prefix.$key}   = $value;
                   15551:         }
1.462     albertel 15552:     }
                   15553: }
                   15554: 
1.685     tempelho 15555: # --- Get the symbolic name of a problem and the url
                   15556: sub get_symb {
                   15557:     my ($request,$silent) = @_;
1.726     raeburn  15558:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15559:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15560:     if ($symb eq '') {
                   15561:         if (!$silent) {
1.1071    raeburn  15562:             if (ref($request)) { 
                   15563:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15564:             }
1.685     tempelho 15565:             return ();
                   15566:         }
                   15567:     }
                   15568:     &Apache::lonenc::check_decrypt(\$symb);
                   15569:     return ($symb);
                   15570: }
                   15571: 
                   15572: # --------------------------------------------------------------Get annotation
                   15573: 
                   15574: sub get_annotation {
                   15575:     my ($symb,$enc) = @_;
                   15576: 
                   15577:     my $key = $symb;
                   15578:     if (!$enc) {
                   15579:         $key =
                   15580:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15581:     }
                   15582:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15583:     return $annotation{$key};
                   15584: }
                   15585: 
                   15586: sub clean_symb {
1.731     raeburn  15587:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15588: 
                   15589:     &Apache::lonenc::check_decrypt(\$symb);
                   15590:     my $enc = $env{'request.enc'};
1.731     raeburn  15591:     if ($delete_enc) {
1.730     raeburn  15592:         delete($env{'request.enc'});
                   15593:     }
1.685     tempelho 15594: 
                   15595:     return ($symb,$enc);
                   15596: }
1.462     albertel 15597: 
1.1181    raeburn  15598: ############################################################
                   15599: ############################################################
                   15600: 
                   15601: =pod
                   15602: 
                   15603: =head1 Routines for building display used to search for courses
                   15604: 
                   15605: 
                   15606: =over 4
                   15607: 
                   15608: =item * &build_filters()
                   15609: 
                   15610: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  15611: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15612: and quotacheck.pl
                   15613: 
1.1181    raeburn  15614: 
                   15615: Inputs:
                   15616: 
                   15617: filterlist - anonymous array of fields to include as potential filters 
                   15618: 
                   15619: crstype - course type
                   15620: 
                   15621: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15622:               to pop-open a course selector (will contain "extra element"). 
                   15623: 
                   15624: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15625: 
                   15626: filter - anonymous hash of criteria and their values
                   15627: 
                   15628: action - form action
                   15629: 
                   15630: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15631: 
1.1182    raeburn  15632: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  15633: 
                   15634: cloneruname - username of owner of new course who wants to clone
                   15635: 
                   15636: clonerudom - domain of owner of new course who wants to clone
                   15637: 
                   15638: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   15639: 
                   15640: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15641: 
                   15642: codedom - domain
                   15643: 
                   15644: formname - value of form element named "form". 
                   15645: 
                   15646: fixeddom - domain, if fixed.
                   15647: 
                   15648: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   15649: 
                   15650: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   15651: 
                   15652: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15653: 
                   15654: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15655: 
                   15656: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15657: 
                   15658: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15659: 
                   15660: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15661: 
1.1182    raeburn  15662: 
1.1181    raeburn  15663: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15664: 
1.1182    raeburn  15665: 
1.1181    raeburn  15666: Side Effects: None
                   15667: 
                   15668: =cut
                   15669: 
                   15670: # ---------------------------------------------- search for courses based on last activity etc.
                   15671: 
                   15672: sub build_filters {
                   15673:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15674:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15675:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15676:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15677:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  15678:     my ($list,$jscript);
1.1181    raeburn  15679:     my $onchange = 'javascript:updateFilters(this)';
                   15680:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15681:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15682:         $typeselectform,$instcodetitle);
                   15683:     if ($formname eq '') {
                   15684:         $formname = $caller;
                   15685:     }
                   15686:     foreach my $item (@{$filterlist}) {
                   15687:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15688:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15689:             if ($item eq 'domainfilter') {
                   15690:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15691:             } elsif ($item eq 'coursefilter') {
                   15692:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15693:             } elsif ($item eq 'ownerfilter') {
                   15694:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15695:             } elsif ($item eq 'ownerdomfilter') {
                   15696:                 $filter->{'ownerdomfilter'} =
                   15697:                     &LONCAPA::clean_domain($filter->{$item});
                   15698:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15699:                                                        'ownerdomfilter',1);
                   15700:             } elsif ($item eq 'personfilter') {
                   15701:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15702:             } elsif ($item eq 'persondomfilter') {
                   15703:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15704:                                                         'persondomfilter',1);
                   15705:             } else {
                   15706:                 $filter->{$item} =~ s/\W//g;
                   15707:             }
                   15708:             if (!$filter->{$item}) {
                   15709:                 $filter->{$item} = '';
                   15710:             }
                   15711:         }
                   15712:         if ($item eq 'domainfilter') {
                   15713:             my $allow_blank = 1;
                   15714:             if ($formname eq 'portform') {
                   15715:                 $allow_blank=0;
                   15716:             } elsif ($formname eq 'studentform') {
                   15717:                 $allow_blank=0;
                   15718:             }
                   15719:             if ($fixeddom) {
                   15720:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15721:                                     ' value="'.$codedom.'" />'.
                   15722:                                     &Apache::lonnet::domain($codedom,'description');
                   15723:             } else {
                   15724:                 $domainselectform = &select_dom_form($filter->{$item},
                   15725:                                                      'domainfilter',
                   15726:                                                       $allow_blank,'',$onchange);
                   15727:             }
                   15728:         } else {
                   15729:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15730:         }
                   15731:     }
                   15732: 
                   15733:     # last course activity filter and selection
                   15734:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15735: 
                   15736:     # course created filter and selection
                   15737:     if (exists($filter->{'createdfilter'})) {
                   15738:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15739:     }
                   15740: 
                   15741:     my %lt = &Apache::lonlocal::texthash(
                   15742:                 'cac' => "$crstype Activity",
                   15743:                 'ccr' => "$crstype Created",
                   15744:                 'cde' => "$crstype Title",
                   15745:                 'cdo' => "$crstype Domain",
                   15746:                 'ins' => 'Institutional Code',
                   15747:                 'inc' => 'Institutional Categorization',
                   15748:                 'cow' => "$crstype Owner/Co-owner",
                   15749:                 'cop' => "$crstype Personnel Includes",
                   15750:                 'cog' => 'Type',
                   15751:              );
                   15752: 
                   15753:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15754:         my $typeval = 'Course';
                   15755:         if ($crstype eq 'Community') {
                   15756:             $typeval = 'Community';
                   15757:         }
                   15758:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15759:     } else {
                   15760:         $typeselectform =  '<select name="type" size="1"';
                   15761:         if ($onchange) {
                   15762:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15763:         }
                   15764:         $typeselectform .= '>'."\n";
                   15765:         foreach my $posstype ('Course','Community') {
                   15766:             $typeselectform.='<option value="'.$posstype.'"'.
                   15767:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15768:         }
                   15769:         $typeselectform.="</select>";
                   15770:     }
                   15771: 
                   15772:     my ($cloneableonlyform,$cloneabletitle);
                   15773:     if (exists($filter->{'cloneableonly'})) {
                   15774:         my $cloneableon = '';
                   15775:         my $cloneableoff = ' checked="checked"';
                   15776:         if ($filter->{'cloneableonly'}) {
                   15777:             $cloneableon = $cloneableoff;
                   15778:             $cloneableoff = '';
                   15779:         }
                   15780:         $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>';
                   15781:         if ($formname eq 'ccrs') {
1.1187    bisitz   15782:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  15783:         } else {
                   15784:             $cloneabletitle = &mt('Cloneable by you');
                   15785:         }
                   15786:     }
                   15787:     my $officialjs;
                   15788:     if ($crstype eq 'Course') {
                   15789:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  15790: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15791: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15792:             if ($codedom) { 
1.1181    raeburn  15793:                 $officialjs = 1;
                   15794:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15795:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15796:                                                                   $officialjs,$codetitlesref);
                   15797:                 if ($jscript) {
1.1182    raeburn  15798:                     $jscript = '<script type="text/javascript">'."\n".
                   15799:                                '// <![CDATA['."\n".
                   15800:                                $jscript."\n".
                   15801:                                '// ]]>'."\n".
                   15802:                                '</script>'."\n";
1.1181    raeburn  15803:                 }
                   15804:             }
                   15805:             if ($instcodeform eq '') {
                   15806:                 $instcodeform =
                   15807:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15808:                     $list->{'instcodefilter'}.'" />';
                   15809:                 $instcodetitle = $lt{'ins'};
                   15810:             } else {
                   15811:                 $instcodetitle = $lt{'inc'};
                   15812:             }
                   15813:             if ($fixeddom) {
                   15814:                 $instcodetitle .= '<br />('.$codedom.')';
                   15815:             }
                   15816:         }
                   15817:     }
                   15818:     my $output = qq|
                   15819: <form method="post" name="filterpicker" action="$action">
                   15820: <input type="hidden" name="form" value="$formname" />
                   15821: |;
                   15822:     if ($formname eq 'modifycourse') {
                   15823:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15824:                    '<input type="hidden" name="prevphase" value="'.
                   15825:                    $prevphase.'" />'."\n";
1.1198    musolffc 15826:     } elsif ($formname eq 'quotacheck') {
                   15827:         $output .= qq|
                   15828: <input type="hidden" name="sortby" value="" />
                   15829: <input type="hidden" name="sortorder" value="" />
                   15830: |;
                   15831:     } else {
1.1181    raeburn  15832:         my $name_input;
                   15833:         if ($cnameelement ne '') {
                   15834:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15835:                           $cnameelement.'" />';
                   15836:         }
                   15837:         $output .= qq|
1.1182    raeburn  15838: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15839: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  15840: $name_input
                   15841: $roleelement
                   15842: $multelement
                   15843: $typeelement
                   15844: |;
                   15845:         if ($formname eq 'portform') {
                   15846:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15847:         }
                   15848:     }
                   15849:     if ($fixeddom) {
                   15850:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15851:     }
                   15852:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15853:     if ($sincefilterform) {
                   15854:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15855:                   .$sincefilterform
                   15856:                   .&Apache::lonhtmlcommon::row_closure();
                   15857:     }
                   15858:     if ($createdfilterform) {
                   15859:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15860:                   .$createdfilterform
                   15861:                   .&Apache::lonhtmlcommon::row_closure();
                   15862:     }
                   15863:     if ($domainselectform) {
                   15864:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15865:                   .$domainselectform
                   15866:                   .&Apache::lonhtmlcommon::row_closure();
                   15867:     }
                   15868:     if ($typeselectform) {
                   15869:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15870:             $output .= $typeselectform;
                   15871:         } else {
                   15872:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15873:                       .$typeselectform
                   15874:                       .&Apache::lonhtmlcommon::row_closure();
                   15875:         }
                   15876:     }
                   15877:     if ($instcodeform) {
                   15878:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15879:                   .$instcodeform
                   15880:                   .&Apache::lonhtmlcommon::row_closure();
                   15881:     }
                   15882:     if (exists($filter->{'ownerfilter'})) {
                   15883:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15884:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15885:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15886:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15887:                    $ownerdomselectform.'</td></tr></table>'.
                   15888:                    &Apache::lonhtmlcommon::row_closure();
                   15889:     }
                   15890:     if (exists($filter->{'personfilter'})) {
                   15891:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15892:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15893:                    '<input type="text" name="personfilter" size="20" value="'.
                   15894:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15895:                    $persondomselectform.'</td></tr></table>'.
                   15896:                    &Apache::lonhtmlcommon::row_closure();
                   15897:     }
                   15898:     if (exists($filter->{'coursefilter'})) {
                   15899:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15900:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15901:                   .$list->{'coursefilter'}.'" />'
                   15902:                   .&Apache::lonhtmlcommon::row_closure();
                   15903:     }
                   15904:     if ($cloneableonlyform) {
                   15905:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15906:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15907:     }
                   15908:     if (exists($filter->{'descriptfilter'})) {
                   15909:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15910:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15911:                   .$list->{'descriptfilter'}.'" />'
                   15912:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15913:     }
                   15914:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15915:                '<input type="hidden" name="updater" value="" />'."\n".
                   15916:                '<input type="submit" name="gosearch" value="'.
                   15917:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15918:     return $jscript.$clonewarning.$output;
                   15919: }
                   15920: 
                   15921: =pod 
                   15922: 
                   15923: =item * &timebased_select_form()
                   15924: 
1.1182    raeburn  15925: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  15926: filter e.g., Course Activity, Course Created, when searching for courses
                   15927: or communities
                   15928: 
                   15929: Inputs:
                   15930: 
                   15931: item - name of form element (sincefilter or createdfilter)
                   15932: 
                   15933: filter - anonymous hash of criteria and their values
                   15934: 
                   15935: Returns: HTML for a select box contained a blank, then six time selections,
                   15936:          with value set in incoming form variables currently selected. 
                   15937: 
                   15938: Side Effects: None
                   15939: 
                   15940: =cut
                   15941: 
                   15942: sub timebased_select_form {
                   15943:     my ($item,$filter) = @_;
                   15944:     if (ref($filter) eq 'HASH') {
                   15945:         $filter->{$item} =~ s/[^\d-]//g;
                   15946:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15947:         return &select_form(
                   15948:                             $filter->{$item},
                   15949:                             $item,
                   15950:                             {      '-1' => '',
                   15951:                                 '86400' => &mt('today'),
                   15952:                                '604800' => &mt('last week'),
                   15953:                               '2592000' => &mt('last month'),
                   15954:                               '7776000' => &mt('last three months'),
                   15955:                              '15552000' => &mt('last six months'),
                   15956:                              '31104000' => &mt('last year'),
                   15957:                     'select_form_order' =>
                   15958:                            ['-1','86400','604800','2592000','7776000',
                   15959:                             '15552000','31104000']});
                   15960:     }
                   15961: }
                   15962: 
                   15963: =pod
                   15964: 
                   15965: =item * &js_changer()
                   15966: 
                   15967: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  15968: when course type or domain is changed, and also to hide 'Searching ...' on
                   15969: page load completion for page showing search result.
1.1181    raeburn  15970: 
                   15971: Inputs: None
                   15972: 
1.1183    raeburn  15973: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  15974: 
                   15975: Side Effects: None
                   15976: 
                   15977: =cut
                   15978: 
                   15979: sub js_changer {
                   15980:     return <<ENDJS;
                   15981: <script type="text/javascript">
                   15982: // <![CDATA[
                   15983: function updateFilters(caller) {
                   15984:     if (typeof(caller) != "undefined") {
                   15985:         document.filterpicker.updater.value = caller.name;
                   15986:     }
                   15987:     document.filterpicker.submit();
                   15988: }
1.1183    raeburn  15989: 
                   15990: function hideSearching() {
                   15991:     if (document.getElementById('searching')) {
                   15992:         document.getElementById('searching').style.display = 'none';
                   15993:     }
                   15994:     return;
                   15995: }
                   15996: 
1.1181    raeburn  15997: // ]]>
                   15998: </script>
                   15999: 
                   16000: ENDJS
                   16001: }
                   16002: 
                   16003: =pod
                   16004: 
1.1182    raeburn  16005: =item * &search_courses()
                   16006: 
                   16007: Process selected filters form course search form and pass to lonnet::courseiddump
                   16008: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16009: 
                   16010: Inputs:
                   16011: 
                   16012: dom - domain being searched 
                   16013: 
                   16014: type - course type ('Course' or 'Community' or '.' if any).
                   16015: 
                   16016: filter - anonymous hash of criteria and their values
                   16017: 
                   16018: numtitles - for institutional codes - number of categories
                   16019: 
                   16020: cloneruname - optional username of new course owner
                   16021: 
                   16022: clonerudom - optional domain of new course owner
                   16023: 
1.1221    raeburn  16024: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  16025:             (used when DC is using course creation form)
                   16026: 
                   16027: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16028: 
1.1221    raeburn  16029: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16030:            (and so can clone automatically)
                   16031: 
                   16032: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16033: 
                   16034: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   16035:               courses to clone 
1.1182    raeburn  16036: 
                   16037: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16038: 
                   16039: 
                   16040: Side Effects: None
                   16041: 
                   16042: =cut
                   16043: 
                   16044: 
                   16045: sub search_courses {
1.1221    raeburn  16046:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16047:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  16048:     my (%courses,%showcourses,$cloner);
                   16049:     if (($filter->{'ownerfilter'} ne '') ||
                   16050:         ($filter->{'ownerdomfilter'} ne '')) {
                   16051:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16052:                                        $filter->{'ownerdomfilter'};
                   16053:     }
                   16054:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16055:         if (!$filter->{$item}) {
                   16056:             $filter->{$item}='.';
                   16057:         }
                   16058:     }
                   16059:     my $now = time;
                   16060:     my $timefilter =
                   16061:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16062:     my ($createdbefore,$createdafter);
                   16063:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16064:         $createdbefore = $now;
                   16065:         $createdafter = $now-$filter->{'createdfilter'};
                   16066:     }
                   16067:     my ($instcodefilter,$regexpok);
                   16068:     if ($numtitles) {
                   16069:         if ($env{'form.official'} eq 'on') {
                   16070:             $instcodefilter =
                   16071:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16072:             $regexpok = 1;
                   16073:         } elsif ($env{'form.official'} eq 'off') {
                   16074:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16075:             unless ($instcodefilter eq '') {
                   16076:                 $regexpok = -1;
                   16077:             }
                   16078:         }
                   16079:     } else {
                   16080:         $instcodefilter = $filter->{'instcodefilter'};
                   16081:     }
                   16082:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16083:     if ($type eq '') { $type = '.'; }
                   16084: 
                   16085:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16086:         $cloner = $cloneruname.':'.$clonerudom;
                   16087:     }
                   16088:     %courses = &Apache::lonnet::courseiddump($dom,
                   16089:                                              $filter->{'descriptfilter'},
                   16090:                                              $timefilter,
                   16091:                                              $instcodefilter,
                   16092:                                              $filter->{'combownerfilter'},
                   16093:                                              $filter->{'coursefilter'},
                   16094:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  16095:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  16096:                                              $filter->{'cloneableonly'},
                   16097:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  16098:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  16099:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16100:         my $ccrole;
                   16101:         if ($type eq 'Community') {
                   16102:             $ccrole = 'co';
                   16103:         } else {
                   16104:             $ccrole = 'cc';
                   16105:         }
                   16106:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16107:                                                      $filter->{'persondomfilter'},
                   16108:                                                      'userroles',undef,
                   16109:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16110:                                                      $dom);
                   16111:         foreach my $role (keys(%rolehash)) {
                   16112:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16113:             my $cid = $cdom.'_'.$cnum;
                   16114:             if (exists($courses{$cid})) {
                   16115:                 if (ref($courses{$cid}) eq 'HASH') {
                   16116:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16117:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   16118:                             push (@{$courses{$cid}{roles}},$courserole);
                   16119:                         }
                   16120:                     } else {
                   16121:                         $courses{$cid}{roles} = [$courserole];
                   16122:                     }
                   16123:                     $showcourses{$cid} = $courses{$cid};
                   16124:                 }
                   16125:             }
                   16126:         }
                   16127:         %courses = %showcourses;
                   16128:     }
                   16129:     return %courses;
                   16130: }
                   16131: 
                   16132: =pod
                   16133: 
1.1181    raeburn  16134: =back
                   16135: 
1.1207    raeburn  16136: =head1 Routines for version requirements for current course.
                   16137: 
                   16138: =over 4
                   16139: 
                   16140: =item * &check_release_required()
                   16141: 
                   16142: Compares required LON-CAPA version with version on server, and
                   16143: if required version is newer looks for a server with the required version.
                   16144: 
                   16145: Looks first at servers in user's owen domain; if none suitable, looks at
                   16146: servers in course's domain are permitted to host sessions for user's domain.
                   16147: 
                   16148: Inputs:
                   16149: 
                   16150: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16151: 
                   16152: $courseid - Course ID of current course
                   16153: 
                   16154: $rolecode - User's current role in course (for switchserver query string).
                   16155: 
                   16156: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16157: 
                   16158: 
                   16159: Returns:
                   16160: 
                   16161: $switchserver - query string tp append to /adm/switchserver call (if 
                   16162:                 current server's LON-CAPA version is too old. 
                   16163: 
                   16164: $warning - Message is displayed if no suitable server could be found.
                   16165: 
                   16166: =cut
                   16167: 
                   16168: sub check_release_required {
                   16169:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16170:     my ($switchserver,$warning);
                   16171:     if ($required ne '') {
                   16172:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16173:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16174:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16175:             my $otherserver;
                   16176:             if (($major eq '' && $minor eq '') ||
                   16177:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16178:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16179:                 my $switchlcrev =
                   16180:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16181:                                                            $userdomserver);
                   16182:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16183:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16184:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16185:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16186:                     if ($cdom ne $env{'user.domain'}) {
                   16187:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16188:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16189:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16190:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16191:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16192:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16193:                         my $canhost =
                   16194:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16195:                                                               $coursedomserver,
                   16196:                                                               $remoterev,
                   16197:                                                               $udomdefaults{'remotesessions'},
                   16198:                                                               $defdomdefaults{'hostedsessions'});
                   16199: 
                   16200:                         if ($canhost) {
                   16201:                             $otherserver = $coursedomserver;
                   16202:                         } else {
                   16203:                             $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.");
                   16204:                         }
                   16205:                     } else {
                   16206:                         $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).");
                   16207:                     }
                   16208:                 } else {
                   16209:                     $otherserver = $userdomserver;
                   16210:                 }
                   16211:             }
                   16212:             if ($otherserver ne '') {
                   16213:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16214:             }
                   16215:         }
                   16216:     }
                   16217:     return ($switchserver,$warning);
                   16218: }
                   16219: 
                   16220: =pod
                   16221: 
                   16222: =item * &check_release_result()
                   16223: 
                   16224: Inputs:
                   16225: 
                   16226: $switchwarning - Warning message if no suitable server found to host session.
                   16227: 
                   16228: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16229:                 and current role.
                   16230: 
                   16231: Returns: HTML to display with information about requirement to switch server.
                   16232:          Either displaying warning with link to Roles/Courses screen or
                   16233:          display link to switchserver.
                   16234: 
1.1181    raeburn  16235: =cut
                   16236: 
1.1207    raeburn  16237: sub check_release_result {
                   16238:     my ($switchwarning,$switchserver) = @_;
                   16239:     my $output = &start_page('Selected course unavailable on this server').
                   16240:                  '<p class="LC_warning">';
                   16241:     if ($switchwarning) {
                   16242:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16243:         if (&show_course()) {
                   16244:             $output .= &mt('Display courses');
                   16245:         } else {
                   16246:             $output .= &mt('Display roles');
                   16247:         }
                   16248:         $output .= '</a>';
                   16249:     } elsif ($switchserver) {
                   16250:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16251:                    '<br />'.
                   16252:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16253:                    &mt('Switch Server').
                   16254:                    '</a>';
                   16255:     }
                   16256:     $output .= '</p>'.&end_page();
                   16257:     return $output;
                   16258: }
                   16259: 
                   16260: =pod
                   16261: 
                   16262: =item * &needs_coursereinit()
                   16263: 
                   16264: Determine if course contents stored for user's session needs to be
                   16265: refreshed, because content has changed since "Big Hash" last tied.
                   16266: 
                   16267: Check for change is made if time last checked is more than 10 minutes ago
                   16268: (by default).
                   16269: 
                   16270: Inputs:
                   16271: 
                   16272: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16273: 
                   16274: $interval (optional) - Time which may elapse (in s) between last check for content
                   16275:                        change in current course. (default: 600 s).  
                   16276: 
                   16277: Returns: an array; first element is:
                   16278: 
                   16279: =over 4
                   16280: 
                   16281: 'switch' - if content updates mean user's session
                   16282:            needs to be switched to a server running a newer LON-CAPA version
                   16283:  
                   16284: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16285:            on current server hosting user's session                
                   16286: 
                   16287: ''       - if no action required.
                   16288: 
                   16289: =back
                   16290: 
                   16291: If first item element is 'switch':
                   16292: 
                   16293: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   16294: 
                   16295: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16296:                               and current role. 
                   16297: 
                   16298: otherwise: no other elements returned.
                   16299: 
                   16300: =back
                   16301: 
                   16302: =cut
                   16303: 
                   16304: sub needs_coursereinit {
                   16305:     my ($loncaparev,$interval) = @_;
                   16306:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16307:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16308:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16309:     my $now = time;
                   16310:     if ($interval eq '') {
                   16311:         $interval = 600;
                   16312:     }
                   16313:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16314:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16315:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16316:         if ($lastchange > $env{'request.course.tied'}) {
                   16317:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16318:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16319:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16320:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16321:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16322:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16323:                     my ($switchserver,$switchwarning) =
                   16324:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16325:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16326:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16327:                         return ('switch',$switchwarning,$switchserver);
                   16328:                     }
                   16329:                 }
                   16330:             }
                   16331:             return ('update');
                   16332:         }
                   16333:     }
                   16334:     return ();
                   16335: }
1.1181    raeburn  16336: 
1.1083    raeburn  16337: sub update_content_constraints {
                   16338:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16339:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16340:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16341:     my %checkresponsetypes;
                   16342:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1219    raeburn  16343:         my ($item,$name,$value,$valmatch) = split(/:/,$key);
1.1083    raeburn  16344:         if ($item eq 'resourcetag') {
                   16345:             if ($name eq 'responsetype') {
                   16346:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16347:             }
                   16348:         }
                   16349:     }
                   16350:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16351:     if (defined($navmap)) {
                   16352:         my %allresponses;
                   16353:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16354:             my %responses = $res->responseTypes();
                   16355:             foreach my $key (keys(%responses)) {
                   16356:                 next unless(exists($checkresponsetypes{$key}));
                   16357:                 $allresponses{$key} += $responses{$key};
                   16358:             }
                   16359:         }
                   16360:         foreach my $key (keys(%allresponses)) {
                   16361:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16362:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16363:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16364:             }
                   16365:         }
                   16366:         undef($navmap);
                   16367:     }
                   16368:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16369:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16370:     }
                   16371:     return;
                   16372: }
                   16373: 
1.1110    raeburn  16374: sub allmaps_incourse {
                   16375:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16376:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16377:         $cid = $env{'request.course.id'};
                   16378:         $cdom = $env{'course.'.$cid.'.domain'};
                   16379:         $cnum = $env{'course.'.$cid.'.num'};
                   16380:         $chome = $env{'course.'.$cid.'.home'};
                   16381:     }
                   16382:     my %allmaps = ();
                   16383:     my $lastchange =
                   16384:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16385:     if ($lastchange > $env{'request.course.tied'}) {
                   16386:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16387:         unless ($ferr) {
                   16388:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16389:         }
                   16390:     }
                   16391:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16392:     if (defined($navmap)) {
                   16393:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16394:             $allmaps{$res->src()} = 1;
                   16395:         }
                   16396:     }
                   16397:     return \%allmaps;
                   16398: }
                   16399: 
1.1083    raeburn  16400: sub parse_supplemental_title {
                   16401:     my ($title) = @_;
                   16402: 
                   16403:     my ($foldertitle,$renametitle);
                   16404:     if ($title =~ /&amp;&amp;&amp;/) {
                   16405:         $title = &HTML::Entites::decode($title);
                   16406:     }
                   16407:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16408:         $renametitle=$4;
                   16409:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16410:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16411:         my $name =  &plainname($uname,$udom);
                   16412:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16413:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16414:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16415:             $name.': <br />'.$foldertitle;
                   16416:     }
                   16417:     if (wantarray) {
                   16418:         return ($title,$foldertitle,$renametitle);
                   16419:     }
                   16420:     return $title;
                   16421: }
                   16422: 
1.1143    raeburn  16423: sub recurse_supplemental {
                   16424:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16425:     if ($suppmap) {
                   16426:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16427:         if ($fatal) {
                   16428:             $errors ++;
                   16429:         } else {
                   16430:             if ($#LONCAPA::map::resources > 0) {
                   16431:                 foreach my $res (@LONCAPA::map::resources) {
                   16432:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16433:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  16434:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16435:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  16436:                         } else {
                   16437:                             $numfiles ++;
                   16438:                         }
                   16439:                     }
                   16440:                 }
                   16441:             }
                   16442:         }
                   16443:     }
                   16444:     return ($numfiles,$errors);
                   16445: }
                   16446: 
1.1101    raeburn  16447: sub symb_to_docspath {
                   16448:     my ($symb) = @_;
                   16449:     return unless ($symb);
                   16450:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16451:     if ($resurl=~/\.(sequence|page)$/) {
                   16452:         $mapurl=$resurl;
                   16453:     } elsif ($resurl eq 'adm/navmaps') {
                   16454:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16455:     }
                   16456:     my $mapresobj;
                   16457:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16458:     if (ref($navmap)) {
                   16459:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   16460:     }
                   16461:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16462:     my $type=$2;
                   16463:     my $path;
                   16464:     if (ref($mapresobj)) {
                   16465:         my $pcslist = $mapresobj->map_hierarchy();
                   16466:         if ($pcslist ne '') {
                   16467:             foreach my $pc (split(/,/,$pcslist)) {
                   16468:                 next if ($pc <= 1);
                   16469:                 my $res = $navmap->getByMapPc($pc);
                   16470:                 if (ref($res)) {
                   16471:                     my $thisurl = $res->src();
                   16472:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16473:                     my $thistitle = $res->title();
                   16474:                     $path .= '&'.
                   16475:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  16476:                              &escape($thistitle).
1.1101    raeburn  16477:                              ':'.$res->randompick().
                   16478:                              ':'.$res->randomout().
                   16479:                              ':'.$res->encrypted().
                   16480:                              ':'.$res->randomorder().
                   16481:                              ':'.$res->is_page();
                   16482:                 }
                   16483:             }
                   16484:         }
                   16485:         $path =~ s/^\&//;
                   16486:         my $maptitle = $mapresobj->title();
                   16487:         if ($mapurl eq 'default') {
1.1129    raeburn  16488:             $maptitle = 'Main Content';
1.1101    raeburn  16489:         }
                   16490:         $path .= (($path ne '')? '&' : '').
                   16491:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16492:                  &escape($maptitle).
1.1101    raeburn  16493:                  ':'.$mapresobj->randompick().
                   16494:                  ':'.$mapresobj->randomout().
                   16495:                  ':'.$mapresobj->encrypted().
                   16496:                  ':'.$mapresobj->randomorder().
                   16497:                  ':'.$mapresobj->is_page();
                   16498:     } else {
                   16499:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16500:         my $ispage = (($type eq 'page')? 1 : '');
                   16501:         if ($mapurl eq 'default') {
1.1129    raeburn  16502:             $maptitle = 'Main Content';
1.1101    raeburn  16503:         }
                   16504:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16505:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  16506:     }
                   16507:     unless ($mapurl eq 'default') {
                   16508:         $path = 'default&'.
1.1146    raeburn  16509:                 &escape('Main Content').
1.1101    raeburn  16510:                 ':::::&'.$path;
                   16511:     }
                   16512:     return $path;
                   16513: }
                   16514: 
1.1094    raeburn  16515: sub captcha_display {
                   16516:     my ($context,$lonhost) = @_;
                   16517:     my ($output,$error);
                   16518:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  16519:     if ($captcha eq 'original') {
1.1094    raeburn  16520:         $output = &create_captcha();
                   16521:         unless ($output) {
1.1172    raeburn  16522:             $error = 'captcha';
1.1094    raeburn  16523:         }
                   16524:     } elsif ($captcha eq 'recaptcha') {
                   16525:         $output = &create_recaptcha($pubkey);
                   16526:         unless ($output) {
1.1172    raeburn  16527:             $error = 'recaptcha';
1.1094    raeburn  16528:         }
                   16529:     }
1.1176    raeburn  16530:     return ($output,$error,$captcha);
1.1094    raeburn  16531: }
                   16532: 
                   16533: sub captcha_response {
                   16534:     my ($context,$lonhost) = @_;
                   16535:     my ($captcha_chk,$captcha_error);
                   16536:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  16537:     if ($captcha eq 'original') {
1.1094    raeburn  16538:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16539:     } elsif ($captcha eq 'recaptcha') {
                   16540:         $captcha_chk = &check_recaptcha($privkey);
                   16541:     } else {
                   16542:         $captcha_chk = 1;
                   16543:     }
                   16544:     return ($captcha_chk,$captcha_error);
                   16545: }
                   16546: 
                   16547: sub get_captcha_config {
                   16548:     my ($context,$lonhost) = @_;
1.1095    raeburn  16549:     my ($captcha,$pubkey,$privkey,$hashtocheck);
1.1094    raeburn  16550:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16551:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16552:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  16553:     if ($context eq 'usercreation') {
                   16554:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16555:         if (ref($domconfig{$context}) eq 'HASH') {
                   16556:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16557:             if (ref($hashtocheck) eq 'HASH') {
                   16558:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16559:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16560:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16561:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16562:                     }
                   16563:                     if ($privkey && $pubkey) {
                   16564:                         $captcha = 'recaptcha';
                   16565:                     } else {
                   16566:                         $captcha = 'original';
                   16567:                     }
                   16568:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16569:                     $captcha = 'original';
                   16570:                 }
1.1094    raeburn  16571:             }
1.1095    raeburn  16572:         } else {
                   16573:             $captcha = 'captcha';
                   16574:         }
                   16575:     } elsif ($context eq 'login') {
                   16576:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16577:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16578:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16579:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  16580:             if ($privkey && $pubkey) {
                   16581:                 $captcha = 'recaptcha';
1.1095    raeburn  16582:             } else {
                   16583:                 $captcha = 'original';
1.1094    raeburn  16584:             }
1.1095    raeburn  16585:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16586:             $captcha = 'original';
1.1094    raeburn  16587:         }
                   16588:     }
                   16589:     return ($captcha,$pubkey,$privkey);
                   16590: }
                   16591: 
                   16592: sub create_captcha {
                   16593:     my %captcha_params = &captcha_settings();
                   16594:     my ($output,$maxtries,$tries) = ('',10,0);
                   16595:     while ($tries < $maxtries) {
                   16596:         $tries ++;
                   16597:         my $captcha = Authen::Captcha->new (
                   16598:                                            output_folder => $captcha_params{'output_dir'},
                   16599:                                            data_folder   => $captcha_params{'db_dir'},
                   16600:                                           );
                   16601:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16602: 
                   16603:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16604:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16605:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  16606:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16607:                       '<br />'.
                   16608:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  16609:             last;
                   16610:         }
                   16611:     }
                   16612:     return $output;
                   16613: }
                   16614: 
                   16615: sub captcha_settings {
                   16616:     my %captcha_params = (
                   16617:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16618:                            www_output_dir => "/captchaspool",
                   16619:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16620:                            numchars       => '5',
                   16621:                          );
                   16622:     return %captcha_params;
                   16623: }
                   16624: 
                   16625: sub check_captcha {
                   16626:     my ($captcha_chk,$captcha_error);
                   16627:     my $code = $env{'form.code'};
                   16628:     my $md5sum = $env{'form.crypt'};
                   16629:     my %captcha_params = &captcha_settings();
                   16630:     my $captcha = Authen::Captcha->new(
                   16631:                       output_folder => $captcha_params{'output_dir'},
                   16632:                       data_folder   => $captcha_params{'db_dir'},
                   16633:                   );
1.1109    raeburn  16634:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  16635:     my %captcha_hash = (
                   16636:                         0       => 'Code not checked (file error)',
                   16637:                        -1      => 'Failed: code expired',
                   16638:                        -2      => 'Failed: invalid code (not in database)',
                   16639:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16640:     );
                   16641:     if ($captcha_chk != 1) {
                   16642:         $captcha_error = $captcha_hash{$captcha_chk}
                   16643:     }
                   16644:     return ($captcha_chk,$captcha_error);
                   16645: }
                   16646: 
                   16647: sub create_recaptcha {
                   16648:     my ($pubkey) = @_;
1.1153    raeburn  16649:     my $use_ssl;
                   16650:     if ($ENV{'SERVER_PORT'} == 443) {
                   16651:         $use_ssl = 1;
                   16652:     }
1.1094    raeburn  16653:     my $captcha = Captcha::reCAPTCHA->new;
                   16654:     return $captcha->get_options_setter({theme => 'white'})."\n".
1.1153    raeburn  16655:            $captcha->get_html($pubkey,undef,$use_ssl).
1.1213    raeburn  16656:            &mt('If the text is hard to read, [_1] will replace them.',
1.1133    raeburn  16657:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1094    raeburn  16658:            '<br /><br />';
                   16659: }
                   16660: 
                   16661: sub check_recaptcha {
                   16662:     my ($privkey) = @_;
                   16663:     my $captcha_chk;
                   16664:     my $captcha = Captcha::reCAPTCHA->new;
                   16665:     my $captcha_result =
                   16666:         $captcha->check_answer(
                   16667:                                 $privkey,
                   16668:                                 $ENV{'REMOTE_ADDR'},
                   16669:                                 $env{'form.recaptcha_challenge_field'},
                   16670:                                 $env{'form.recaptcha_response_field'},
                   16671:                               );
                   16672:     if ($captcha_result->{is_valid}) {
                   16673:         $captcha_chk = 1;
                   16674:     }
                   16675:     return $captcha_chk;
                   16676: }
                   16677: 
1.1174    raeburn  16678: sub emailusername_info {
1.1177    raeburn  16679:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
1.1174    raeburn  16680:     my %titles = &Apache::lonlocal::texthash (
                   16681:                      lastname      => 'Last Name',
                   16682:                      firstname     => 'First Name',
                   16683:                      institution   => 'School/college/university',
                   16684:                      location      => "School's city, state/province, country",
                   16685:                      web           => "School's web address",
                   16686:                      officialemail => 'E-mail address at institution (if different)',
                   16687:                  );
                   16688:     return (\@fields,\%titles);
                   16689: }
                   16690: 
1.1161    raeburn  16691: sub cleanup_html {
                   16692:     my ($incoming) = @_;
                   16693:     my $outgoing;
                   16694:     if ($incoming ne '') {
                   16695:         $outgoing = $incoming;
                   16696:         $outgoing =~ s/;/&#059;/g;
                   16697:         $outgoing =~ s/\#/&#035;/g;
                   16698:         $outgoing =~ s/\&/&#038;/g;
                   16699:         $outgoing =~ s/</&#060;/g;
                   16700:         $outgoing =~ s/>/&#062;/g;
                   16701:         $outgoing =~ s/\(/&#040/g;
                   16702:         $outgoing =~ s/\)/&#041;/g;
                   16703:         $outgoing =~ s/"/&#034;/g;
                   16704:         $outgoing =~ s/'/&#039;/g;
                   16705:         $outgoing =~ s/\$/&#036;/g;
                   16706:         $outgoing =~ s{/}{&#047;}g;
                   16707:         $outgoing =~ s/=/&#061;/g;
                   16708:         $outgoing =~ s/\\/&#092;/g
                   16709:     }
                   16710:     return $outgoing;
                   16711: }
                   16712: 
1.1190    musolffc 16713: # Checks for critical messages and returns a redirect url if one exists.
                   16714: # $interval indicates how often to check for messages.
                   16715: sub critical_redirect {
                   16716:     my ($interval) = @_;
                   16717:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16718:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   16719:                                         $env{'user.name'});
                   16720:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  16721:         my $redirecturl;
1.1190    musolffc 16722:         if ($what[0]) {
                   16723: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16724: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  16725: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16726:                 return (1, $url);
1.1190    musolffc 16727:             }
1.1191    raeburn  16728:         }
                   16729:     } 
                   16730:     return ();
1.1190    musolffc 16731: }
                   16732: 
1.1174    raeburn  16733: # Use:
                   16734: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16735: #
                   16736: ##################################################
                   16737: #          password associated functions         #
                   16738: ##################################################
                   16739: sub des_keys {
                   16740:     # Make a new key for DES encryption.
                   16741:     # Each key has two parts which are returned separately.
                   16742:     # Please note:  Each key must be passed through the &hex function
                   16743:     # before it is output to the web browser.  The hex versions cannot
                   16744:     # be used to decrypt.
                   16745:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16746:                 '8','9','a','b','c','d','e','f');
                   16747:     my $lkey='';
                   16748:     for (0..7) {
                   16749:         $lkey.=$hexstr[rand(15)];
                   16750:     }
                   16751:     my $ukey='';
                   16752:     for (0..7) {
                   16753:         $ukey.=$hexstr[rand(15)];
                   16754:     }
                   16755:     return ($lkey,$ukey);
                   16756: }
                   16757: 
                   16758: sub des_decrypt {
                   16759:     my ($key,$cyphertext) = @_;
                   16760:     my $keybin=pack("H16",$key);
                   16761:     my $cypher;
                   16762:     if ($Crypt::DES::VERSION>=2.03) {
                   16763:         $cypher=new Crypt::DES $keybin;
                   16764:     } else {
                   16765:         $cypher=new DES $keybin;
                   16766:     }
                   16767:     my $plaintext=
                   16768:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
                   16769:     $plaintext.=
                   16770:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
                   16771:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
                   16772:     return $plaintext;
                   16773: }
                   16774: 
1.112     bowersj2 16775: 1;
                   16776: __END__;
1.41      ng       16777: 

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