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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1306  ! raeburn     4: # $Id: loncommon.pm,v 1.1305 2017/12/22 02:00:46 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1280    raeburn    74: use LONCAPA::LWPReq;
1.657     raeburn    75: use DateTime::TimeZone;
1.1241    raeburn    76: use DateTime::Locale;
1.1220    raeburn    77: use Encode();
1.1091    foxr       78: use Text::Aspell;
1.1094    raeburn    79: use Authen::Captcha;
                     80: use Captcha::reCAPTCHA;
1.1234    raeburn    81: use JSON::DWIW;
                     82: use LWP::UserAgent;
1.1174    raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   85: use MIME::Lite;
                     86: use MIME::Types;
1.1292    raeburn    87: use File::Copy();
1.1300    raeburn    88: use File::Path();
1.117     www        89: 
1.517     raeburn    90: # ---------------------------------------------- Designs
                     91: use vars qw(%defaultdesign);
                     92: 
1.22      www        93: my $readit;
                     94: 
1.517     raeburn    95: 
1.157     matthew    96: ##
                     97: ## Global Variables
                     98: ##
1.46      matthew    99: 
1.643     foxr      100: 
                    101: # ----------------------------------------------- SSI with retries:
                    102: #
                    103: 
                    104: =pod
                    105: 
1.648     raeburn   106: =head1 Server Side include with retries:
1.643     foxr      107: 
                    108: =over 4
                    109: 
1.648     raeburn   110: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      111: 
                    112: Performs an ssi with some number of retries.  Retries continue either
                    113: until the result is ok or until the retry count supplied by the
                    114: caller is exhausted.  
                    115: 
                    116: Inputs:
1.648     raeburn   117: 
                    118: =over 4
                    119: 
1.643     foxr      120: resource   - Identifies the resource to insert.
1.648     raeburn   121: 
1.643     foxr      122: retries    - Count of the number of retries allowed.
1.648     raeburn   123: 
1.643     foxr      124: form       - Hash that identifies the rendering options.
                    125: 
1.648     raeburn   126: =back
                    127: 
                    128: Returns:
                    129: 
                    130: =over 4
                    131: 
1.643     foxr      132: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   133: 
1.643     foxr      134: response   - The response from the last attempt (which may or may not have been successful.
                    135: 
1.648     raeburn   136: =back
                    137: 
                    138: =back
                    139: 
1.643     foxr      140: =cut
                    141: 
                    142: sub ssi_with_retries {
                    143:     my ($resource, $retries, %form) = @_;
                    144: 
                    145: 
                    146:     my $ok = 0;			# True if we got a good response.
                    147:     my $content;
                    148:     my $response;
                    149: 
                    150:     # Try to get the ssi done. within the retries count:
                    151: 
                    152:     do {
                    153: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    154: 	$ok      = $response->is_success;
1.650     www       155:         if (!$ok) {
                    156:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    157:         }
1.643     foxr      158: 	$retries--;
                    159:     } while (!$ok && ($retries > 0));
                    160: 
                    161:     if (!$ok) {
                    162: 	$content = '';		# On error return an empty content.
                    163:     }
                    164:     return ($content, $response);
                    165: 
                    166: }
                    167: 
                    168: 
                    169: 
1.20      www       170: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  171: my %language;
1.124     www       172: my %supported_language;
1.1088    foxr      173: my %supported_codes;
1.1048    foxr      174: my %latex_language;		# For choosing hyphenation in <transl..>
                    175: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  176: my %cprtag;
1.192     taceyjo1  177: my %scprtag;
1.351     www       178: my %fe; my %fd; my %fm;
1.41      ng        179: my %category_extensions;
1.12      harris41  180: 
1.46      matthew   181: # ---------------------------------------------- Thesaurus variables
1.144     matthew   182: #
                    183: # %Keywords:
                    184: #      A hash used by &keyword to determine if a word is considered a keyword.
                    185: # $thesaurus_db_file 
                    186: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   187: 
                    188: my %Keywords;
                    189: my $thesaurus_db_file;
                    190: 
1.144     matthew   191: #
                    192: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    193: # thesaurus.tab, and filecategories.tab.
                    194: #
1.18      www       195: BEGIN {
1.46      matthew   196:     # Variable initialization
                    197:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    198:     #
1.22      www       199:     unless ($readit) {
1.12      harris41  200: # ------------------------------------------------------------------- languages
                    201:     {
1.158     raeburn   202:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    203:                                    '/language.tab';
                    204:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  205:             while (my $line = <$fh>) {
                    206:                 next if ($line=~/^\#/);
                    207:                 chomp($line);
1.1088    foxr      208:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   209:                 $language{$key}=$val.' - '.$enc;
                    210:                 if ($sup) {
                    211:                     $supported_language{$key}=$sup;
1.1088    foxr      212: 		    $supported_codes{$key}   = $code;
1.158     raeburn   213:                 }
1.1048    foxr      214: 		if ($latex) {
                    215: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      216: 		    $latex_language{$code} = $latex;
1.1048    foxr      217: 		}
1.158     raeburn   218:             }
                    219:             close($fh);
                    220:         }
1.12      harris41  221:     }
                    222: # ------------------------------------------------------------------ copyrights
                    223:     {
1.158     raeburn   224:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    225:                                   '/copyright.tab';
                    226:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  227:             while (my $line = <$fh>) {
                    228:                 next if ($line=~/^\#/);
                    229:                 chomp($line);
                    230:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   231:                 $cprtag{$key}=$val;
                    232:             }
                    233:             close($fh);
                    234:         }
1.12      harris41  235:     }
1.351     www       236: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  237:     {
                    238:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    239:                                   '/source_copyright.tab';
                    240:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  241:             while (my $line = <$fh>) {
                    242:                 next if ($line =~ /^\#/);
                    243:                 chomp($line);
                    244:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  245:                 $scprtag{$key}=$val;
                    246:             }
                    247:             close($fh);
                    248:         }
                    249:     }
1.63      www       250: 
1.517     raeburn   251: # -------------------------------------------------------------- default domain designs
1.63      www       252:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   253:     my $designfile = $designdir.'/default.tab';
                    254:     if ( open (my $fh,"<$designfile") ) {
                    255:         while (my $line = <$fh>) {
                    256:             next if ($line =~ /^\#/);
                    257:             chomp($line);
                    258:             my ($key,$val)=(split(/\=/,$line));
                    259:             if ($val) { $defaultdesign{$key}=$val; }
                    260:         }
                    261:         close($fh);
1.63      www       262:     }
                    263: 
1.15      harris41  264: # ------------------------------------------------------------- file categories
                    265:     {
1.158     raeburn   266:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    267:                                   '/filecategories.tab';
                    268:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  269: 	    while (my $line = <$fh>) {
                    270: 		next if ($line =~ /^\#/);
                    271: 		chomp($line);
                    272:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   273:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   274:             }
                    275:             close($fh);
                    276:         }
                    277: 
1.15      harris41  278:     }
1.12      harris41  279: # ------------------------------------------------------------------ file types
                    280:     {
1.158     raeburn   281:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    282:                '/filetypes.tab';
                    283:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  284:             while (my $line = <$fh>) {
                    285: 		next if ($line =~ /^\#/);
                    286: 		chomp($line);
                    287:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   288:                 if ($descr ne '') {
                    289:                     $fe{$ending}=lc($emb);
                    290:                     $fd{$ending}=$descr;
1.351     www       291:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   292:                 }
                    293:             }
                    294:             close($fh);
                    295:         }
1.12      harris41  296:     }
1.22      www       297:     &Apache::lonnet::logthis(
1.705     tempelho  298:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       299:     $readit=1;
1.46      matthew   300:     }  # end of unless($readit) 
1.32      matthew   301:     
                    302: }
1.112     bowersj2  303: 
1.42      matthew   304: ###############################################################
                    305: ##           HTML and Javascript Helper Functions            ##
                    306: ###############################################################
                    307: 
                    308: =pod 
                    309: 
1.112     bowersj2  310: =head1 HTML and Javascript Functions
1.42      matthew   311: 
1.112     bowersj2  312: =over 4
                    313: 
1.648     raeburn   314: =item * &browser_and_searcher_javascript()
1.112     bowersj2  315: 
                    316: X<browsing, javascript>X<searching, javascript>Returns a string
                    317: containing javascript with two functions, C<openbrowser> and
                    318: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    319: tags.
1.42      matthew   320: 
1.648     raeburn   321: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   322: 
                    323: inputs: formname, elementname, only, omit
                    324: 
                    325: formname and elementname indicate the name of the html form and name of
                    326: the element that the results of the browsing selection are to be placed in. 
                    327: 
                    328: Specifying 'only' will restrict the browser to displaying only files
1.185     www       329: with the given extension.  Can be a comma separated list.
1.42      matthew   330: 
                    331: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       332: with the given extension.  Can be a comma separated list.
1.42      matthew   333: 
1.648     raeburn   334: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   335: 
                    336: Inputs: formname, elementname
                    337: 
                    338: formname and elementname specify the name of the html form and the name
                    339: of the element the selection from the search results will be placed in.
1.542     raeburn   340: 
1.42      matthew   341: =cut
                    342: 
                    343: sub browser_and_searcher_javascript {
1.199     albertel  344:     my ($mode)=@_;
                    345:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  346:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   347:     return <<END;
1.219     albertel  348: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   349:     var editbrowser = null;
1.135     albertel  350:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       351:         var url = '$resurl/?';
1.42      matthew   352:         if (editbrowser == null) {
                    353:             url += 'launch=1&';
                    354:         }
                    355:         url += 'catalogmode=interactive&';
1.199     albertel  356:         url += 'mode=$mode&';
1.611     albertel  357:         url += 'inhibitmenu=yes&';
1.42      matthew   358:         url += 'form=' + formname + '&';
                    359:         if (only != null) {
                    360:             url += 'only=' + only + '&';
1.217     albertel  361:         } else {
                    362:             url += 'only=&';
                    363: 	}
1.42      matthew   364:         if (omit != null) {
                    365:             url += 'omit=' + omit + '&';
1.217     albertel  366:         } else {
                    367:             url += 'omit=&';
                    368: 	}
1.135     albertel  369:         if (titleelement != null) {
                    370:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  371:         } else {
                    372: 	    url += 'titleelement=&';
                    373: 	}
1.42      matthew   374:         url += 'element=' + elementname + '';
                    375:         var title = 'Browser';
1.435     albertel  376:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   377:         options += ',width=700,height=600';
                    378:         editbrowser = open(url,title,options,'1');
                    379:         editbrowser.focus();
                    380:     }
                    381:     var editsearcher;
1.135     albertel  382:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   383:         var url = '/adm/searchcat?';
                    384:         if (editsearcher == null) {
                    385:             url += 'launch=1&';
                    386:         }
                    387:         url += 'catalogmode=interactive&';
1.199     albertel  388:         url += 'mode=$mode&';
1.42      matthew   389:         url += 'form=' + formname + '&';
1.135     albertel  390:         if (titleelement != null) {
                    391:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  392:         } else {
                    393: 	    url += 'titleelement=&';
                    394: 	}
1.42      matthew   395:         url += 'element=' + elementname + '';
                    396:         var title = 'Search';
1.435     albertel  397:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   398:         options += ',width=700,height=600';
                    399:         editsearcher = open(url,title,options,'1');
                    400:         editsearcher.focus();
                    401:     }
1.219     albertel  402: // END LON-CAPA Internal -->
1.42      matthew   403: END
1.170     www       404: }
                    405: 
                    406: sub lastresurl {
1.258     albertel  407:     if ($env{'environment.lastresurl'}) {
                    408: 	return $env{'environment.lastresurl'}
1.170     www       409:     } else {
                    410: 	return '/res';
                    411:     }
                    412: }
                    413: 
                    414: sub storeresurl {
                    415:     my $resurl=&Apache::lonnet::clutter(shift);
                    416:     unless ($resurl=~/^\/res/) { return 0; }
                    417:     $resurl=~s/\/$//;
                    418:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   419:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       420:     return 1;
1.42      matthew   421: }
                    422: 
1.74      www       423: sub studentbrowser_javascript {
1.111     www       424:    unless (
1.258     albertel  425:             (($env{'request.course.id'}) && 
1.302     albertel  426:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    427: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    428: 					  '/'.$env{'request.course.sec'})
                    429: 	      ))
1.258     albertel  430:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       431:           ) { return ''; }  
1.74      www       432:    return (<<'ENDSTDBRW');
1.776     bisitz    433: <script type="text/javascript" language="Javascript">
1.824     bisitz    434: // <![CDATA[
1.74      www       435:     var stdeditbrowser;
1.999     www       436:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       437:         var url = '/adm/pickstudent?';
                    438:         var filter;
1.558     albertel  439: 	if (!ignorefilter) {
                    440: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    441: 	}
1.74      www       442:         if (filter != null) {
                    443:            if (filter != '') {
                    444:                url += 'filter='+filter+'&';
                    445: 	   }
                    446:         }
                    447:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       448:                                     '&udomelement='+udom+
                    449:                                     '&clicker='+clicker;
1.111     www       450: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   451:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       452:         var title = 'Student_Browser';
1.74      www       453:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    454:         options += ',width=700,height=600';
                    455:         stdeditbrowser = open(url,title,options,'1');
                    456:         stdeditbrowser.focus();
                    457:     }
1.824     bisitz    458: // ]]>
1.74      www       459: </script>
                    460: ENDSTDBRW
                    461: }
1.42      matthew   462: 
1.1003    www       463: sub resourcebrowser_javascript {
                    464:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       465:    return (<<'ENDRESBRW');
1.1003    www       466: <script type="text/javascript" language="Javascript">
                    467: // <![CDATA[
                    468:     var reseditbrowser;
1.1004    www       469:     function openresbrowser(formname,reslink) {
1.1005    www       470:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       471:         var title = 'Resource_Browser';
                    472:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       473:         options += ',width=700,height=500';
1.1004    www       474:         reseditbrowser = open(url,title,options,'1');
                    475:         reseditbrowser.focus();
1.1003    www       476:     }
                    477: // ]]>
                    478: </script>
1.1004    www       479: ENDRESBRW
1.1003    www       480: }
                    481: 
1.74      www       482: sub selectstudent_link {
1.999     www       483:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    484:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    485:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    486:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  487:    if ($env{'request.course.id'}) {  
1.302     albertel  488:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    489: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    490: 					'/'.$env{'request.course.sec'})) {
1.111     www       491: 	   return '';
                    492:        }
1.999     www       493:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   494:        if ($courseadvonly)  {
                    495:            $callargs .= ",'',1,1";
                    496:        }
                    497:        return '<span class="LC_nobreak">'.
                    498:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    499:               &mt('Select User').'</a></span>';
1.74      www       500:    }
1.258     albertel  501:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       502:        $callargs .= ",'',1"; 
1.793     raeburn   503:        return '<span class="LC_nobreak">'.
                    504:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    505:               &mt('Select User').'</a></span>';
1.111     www       506:    }
                    507:    return '';
1.91      www       508: }
                    509: 
1.1004    www       510: sub selectresource_link {
                    511:    my ($form,$reslink,$arg)=@_;
                    512:    
                    513:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    514:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    515:    unless ($env{'request.course.id'}) { return $arg; }
                    516:    return '<span class="LC_nobreak">'.
                    517:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    518:               $arg.'</a></span>';
                    519: }
                    520: 
                    521: 
                    522: 
1.653     raeburn   523: sub authorbrowser_javascript {
                    524:     return <<"ENDAUTHORBRW";
1.776     bisitz    525: <script type="text/javascript" language="JavaScript">
1.824     bisitz    526: // <![CDATA[
1.653     raeburn   527: var stdeditbrowser;
                    528: 
                    529: function openauthorbrowser(formname,udom) {
                    530:     var url = '/adm/pickauthor?';
                    531:     url += 'form='+formname+'&roledom='+udom;
                    532:     var title = 'Author_Browser';
                    533:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    534:     options += ',width=700,height=600';
                    535:     stdeditbrowser = open(url,title,options,'1');
                    536:     stdeditbrowser.focus();
                    537: }
                    538: 
1.824     bisitz    539: // ]]>
1.653     raeburn   540: </script>
                    541: ENDAUTHORBRW
                    542: }
                    543: 
1.91      www       544: sub coursebrowser_javascript {
1.1116    raeburn   545:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   546:         $credits_element,$instcode) = @_;
1.932     raeburn   547:     my $wintitle = 'Course_Browser';
1.931     raeburn   548:     if ($crstype eq 'Community') {
1.932     raeburn   549:         $wintitle = 'Community_Browser';
1.909     raeburn   550:     }
1.876     raeburn   551:     my $id_functions = &javascript_index_functions();
                    552:     my $output = '
1.776     bisitz    553: <script type="text/javascript" language="JavaScript">
1.824     bisitz    554: // <![CDATA[
1.468     raeburn   555:     var stdeditbrowser;'."\n";
1.876     raeburn   556: 
                    557:     $output .= <<"ENDSTDBRW";
1.909     raeburn   558:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       559:         var url = '/adm/pickcourse?';
1.895     raeburn   560:         var formid = getFormIdByName(formname);
1.876     raeburn   561:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  562:         if (domainfilter != null) {
                    563:            if (domainfilter != '') {
                    564:                url += 'domainfilter='+domainfilter+'&';
                    565: 	   }
                    566:         }
1.91      www       567:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  568: 	                            '&cdomelement='+udom+
                    569:                                     '&cnameelement='+desc;
1.468     raeburn   570:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   571:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   572:                 url += '&roleelement='+extra_element;
                    573:                 if (domainfilter == null || domainfilter == '') {
                    574:                     url += '&domainfilter='+extra_element;
                    575:                 }
1.234     raeburn   576:             }
1.468     raeburn   577:             else {
                    578:                 if (formname == 'portform') {
                    579:                     url += '&setroles='+extra_element;
1.800     raeburn   580:                 } else {
                    581:                     if (formname == 'rules') {
                    582:                         url += '&fixeddom='+extra_element; 
                    583:                     }
1.468     raeburn   584:                 }
                    585:             }     
1.230     raeburn   586:         }
1.909     raeburn   587:         if (type != null && type != '') {
                    588:             url += '&type='+type;
                    589:         }
                    590:         if (type_elem != null && type_elem != '') {
                    591:             url += '&typeelement='+type_elem;
                    592:         }
1.872     raeburn   593:         if (formname == 'ccrs') {
                    594:             var ownername = document.forms[formid].ccuname.value;
                    595:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   596:             url += '&cloner='+ownername+':'+ownerdom;
                    597:             if (type == 'Course') {
                    598:                 url += '&crscode='+document.forms[formid].crscode.value;
                    599:             }
1.1221    raeburn   600:         }
                    601:         if (formname == 'requestcrs') {
                    602:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   603:         }
1.293     raeburn   604:         if (multflag !=null && multflag != '') {
                    605:             url += '&multiple='+multflag;
                    606:         }
1.909     raeburn   607:         var title = '$wintitle';
1.91      www       608:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    609:         options += ',width=700,height=600';
                    610:         stdeditbrowser = open(url,title,options,'1');
                    611:         stdeditbrowser.focus();
                    612:     }
1.876     raeburn   613: $id_functions
                    614: ENDSTDBRW
1.1116    raeburn   615:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    616:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    617:                                       $credits_element);
1.876     raeburn   618:     }
                    619:     $output .= '
                    620: // ]]>
                    621: </script>';
                    622:     return $output;
                    623: }
                    624: 
                    625: sub javascript_index_functions {
                    626:     return <<"ENDJS";
                    627: 
                    628: function getFormIdByName(formname) {
                    629:     for (var i=0;i<document.forms.length;i++) {
                    630:         if (document.forms[i].name == formname) {
                    631:             return i;
                    632:         }
                    633:     }
                    634:     return -1;
                    635: }
                    636: 
                    637: function getIndexByName(formid,item) {
                    638:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    639:         if (document.forms[formid].elements[i].name == item) {
                    640:             return i;
                    641:         }
                    642:     }
                    643:     return -1;
                    644: }
1.468     raeburn   645: 
1.876     raeburn   646: function getDomainFromSelectbox(formname,udom) {
                    647:     var userdom;
                    648:     var formid = getFormIdByName(formname);
                    649:     if (formid > -1) {
                    650:         var domid = getIndexByName(formid,udom);
                    651:         if (domid > -1) {
                    652:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    653:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    654:             }
                    655:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    656:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   657:             }
                    658:         }
                    659:     }
1.876     raeburn   660:     return userdom;
                    661: }
                    662: 
                    663: ENDJS
1.468     raeburn   664: 
1.876     raeburn   665: }
                    666: 
1.1017    raeburn   667: sub javascript_array_indexof {
1.1018    raeburn   668:     return <<ENDJS;
1.1017    raeburn   669: <script type="text/javascript" language="JavaScript">
                    670: // <![CDATA[
                    671: 
                    672: if (!Array.prototype.indexOf) {
                    673:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    674:         "use strict";
                    675:         if (this === void 0 || this === null) {
                    676:             throw new TypeError();
                    677:         }
                    678:         var t = Object(this);
                    679:         var len = t.length >>> 0;
                    680:         if (len === 0) {
                    681:             return -1;
                    682:         }
                    683:         var n = 0;
                    684:         if (arguments.length > 0) {
                    685:             n = Number(arguments[1]);
1.1088    foxr      686:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   687:                 n = 0;
                    688:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    689:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    690:             }
                    691:         }
                    692:         if (n >= len) {
                    693:             return -1;
                    694:         }
                    695:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    696:         for (; k < len; k++) {
                    697:             if (k in t && t[k] === searchElement) {
                    698:                 return k;
                    699:             }
                    700:         }
                    701:         return -1;
                    702:     }
                    703: }
                    704: 
                    705: // ]]>
                    706: </script>
                    707: 
                    708: ENDJS
                    709: 
                    710: }
                    711: 
1.876     raeburn   712: sub userbrowser_javascript {
                    713:     my $id_functions = &javascript_index_functions();
                    714:     return <<"ENDUSERBRW";
                    715: 
1.888     raeburn   716: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   717:     var url = '/adm/pickuser?';
                    718:     var userdom = getDomainFromSelectbox(formname,udom);
                    719:     if (userdom != null) {
                    720:        if (userdom != '') {
                    721:            url += 'srchdom='+userdom+'&';
                    722:        }
                    723:     }
                    724:     url += 'form=' + formname + '&unameelement='+uname+
                    725:                                 '&udomelement='+udom+
                    726:                                 '&ulastelement='+ulast+
                    727:                                 '&ufirstelement='+ufirst+
                    728:                                 '&uemailelement='+uemail+
1.881     raeburn   729:                                 '&hideudomelement='+hideudom+
                    730:                                 '&coursedom='+crsdom;
1.888     raeburn   731:     if ((caller != null) && (caller != undefined)) {
                    732:         url += '&caller='+caller;
                    733:     }
1.876     raeburn   734:     var title = 'User_Browser';
                    735:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    736:     options += ',width=700,height=600';
                    737:     var stdeditbrowser = open(url,title,options,'1');
                    738:     stdeditbrowser.focus();
                    739: }
                    740: 
1.888     raeburn   741: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   742:     var formid = getFormIdByName(formname);
                    743:     if (formid > -1) {
1.888     raeburn   744:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   745:         var domid = getIndexByName(formid,udom);
                    746:         var hidedomid = getIndexByName(formid,origdom);
                    747:         if (hidedomid > -1) {
                    748:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   749:             var unameval = document.forms[formid].elements[unameid].value;
                    750:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    751:                 if (domid > -1) {
                    752:                     var slct = document.forms[formid].elements[domid];
                    753:                     if (slct.type == 'select-one') {
                    754:                         var i;
                    755:                         for (i=0;i<slct.length;i++) {
                    756:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    757:                         }
                    758:                     }
                    759:                     if (slct.type == 'hidden') {
                    760:                         slct.value = fixeddom;
1.876     raeburn   761:                     }
                    762:                 }
1.468     raeburn   763:             }
                    764:         }
                    765:     }
1.876     raeburn   766:     return;
                    767: }
                    768: 
                    769: $id_functions
                    770: ENDUSERBRW
1.468     raeburn   771: }
                    772: 
                    773: sub setsec_javascript {
1.1116    raeburn   774:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   775:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    776:         $communityrolestr);
                    777:     if ($role_element ne '') {
                    778:         my @allroles = ('st','ta','ep','in','ad');
                    779:         foreach my $crstype ('Course','Community') {
                    780:             if ($crstype eq 'Community') {
                    781:                 foreach my $role (@allroles) {
                    782:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    783:                 }
                    784:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    785:             } else {
                    786:                 foreach my $role (@allroles) {
                    787:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    788:                 }
                    789:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    790:             }
                    791:         }
                    792:         $rolestr = '"'.join('","',@allroles).'"';
                    793:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    794:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    795:     }
1.468     raeburn   796:     my $setsections = qq|
                    797: function setSect(sectionlist) {
1.629     raeburn   798:     var sectionsArray = new Array();
                    799:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    800:         sectionsArray = sectionlist.split(",");
                    801:     }
1.468     raeburn   802:     var numSections = sectionsArray.length;
                    803:     document.$formname.$sec_element.length = 0;
                    804:     if (numSections == 0) {
                    805:         document.$formname.$sec_element.multiple=false;
                    806:         document.$formname.$sec_element.size=1;
                    807:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    808:     } else {
                    809:         if (numSections == 1) {
                    810:             document.$formname.$sec_element.multiple=false;
                    811:             document.$formname.$sec_element.size=1;
                    812:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    813:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    814:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    815:         } else {
                    816:             for (var i=0; i<numSections; i++) {
                    817:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    818:             }
                    819:             document.$formname.$sec_element.multiple=true
                    820:             if (numSections < 3) {
                    821:                 document.$formname.$sec_element.size=numSections;
                    822:             } else {
                    823:                 document.$formname.$sec_element.size=3;
                    824:             }
                    825:             document.$formname.$sec_element.options[0].selected = false
                    826:         }
                    827:     }
1.91      www       828: }
1.905     raeburn   829: 
                    830: function setRole(crstype) {
1.468     raeburn   831: |;
1.905     raeburn   832:     if ($role_element eq '') {
                    833:         $setsections .= '    return;
                    834: }
                    835: ';
                    836:     } else {
                    837:         $setsections .= qq|
                    838:     var elementLength = document.$formname.$role_element.length;
                    839:     var allroles = Array($rolestr);
                    840:     var courserolenames = Array($courserolestr);
                    841:     var communityrolenames = Array($communityrolestr);
                    842:     if (elementLength != undefined) {
                    843:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    844:             if (crstype == 'Course') {
                    845:                 return;
                    846:             } else {
                    847:                 allroles[5] = 'co';
                    848:                 for (var i=0; i<6; i++) {
                    849:                     document.$formname.$role_element.options[i].value = allroles[i];
                    850:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    851:                 }
                    852:             }
                    853:         } else {
                    854:             if (crstype == 'Community') {
                    855:                 return;
                    856:             } else {
                    857:                 allroles[5] = 'cc';
                    858:                 for (var i=0; i<6; i++) {
                    859:                     document.$formname.$role_element.options[i].value = allroles[i];
                    860:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    861:                 }
                    862:             }
                    863:         }
                    864:     }
                    865:     return;
                    866: }
                    867: |;
                    868:     }
1.1116    raeburn   869:     if ($credits_element) {
                    870:         $setsections .= qq|
                    871: function setCredits(defaultcredits) {
                    872:     document.$formname.$credits_element.value = defaultcredits;
                    873:     return;
                    874: }
                    875: |;
                    876:     }
1.468     raeburn   877:     return $setsections;
                    878: }
                    879: 
1.91      www       880: sub selectcourse_link {
1.909     raeburn   881:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    882:        $typeelement) = @_;
                    883:    my $type = $selecttype;
1.871     raeburn   884:    my $linktext = &mt('Select Course');
                    885:    if ($selecttype eq 'Community') {
1.909     raeburn   886:        $linktext = &mt('Select Community');
1.1239    raeburn   887:    } elsif ($selecttype eq 'Placement') {
                    888:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   889:    } elsif ($selecttype eq 'Course/Community') {
                    890:        $linktext = &mt('Select Course/Community');
1.909     raeburn   891:        $type = '';
1.1019    raeburn   892:    } elsif ($selecttype eq 'Select') {
                    893:        $linktext = &mt('Select');
                    894:        $type = '';
1.871     raeburn   895:    }
1.787     bisitz    896:    return '<span class="LC_nobreak">'
                    897:          ."<a href='"
                    898:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    899:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   900:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   901:          ."'>".$linktext.'</a>'
1.787     bisitz    902:          .'</span>';
1.74      www       903: }
1.42      matthew   904: 
1.653     raeburn   905: sub selectauthor_link {
                    906:    my ($form,$udom)=@_;
                    907:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    908:           &mt('Select Author').'</a>';
                    909: }
                    910: 
1.876     raeburn   911: sub selectuser_link {
1.881     raeburn   912:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   913:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   914:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   915:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   916:            ');">'.$linktext.'</a>';
1.876     raeburn   917: }
                    918: 
1.273     raeburn   919: sub check_uncheck_jscript {
                    920:     my $jscript = <<"ENDSCRT";
                    921: function checkAll(field) {
                    922:     if (field.length > 0) {
                    923:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   924:             if (!field[i].disabled) { 
                    925:                 field[i].checked = true;
                    926:             }
1.273     raeburn   927:         }
                    928:     } else {
1.1093    raeburn   929:         if (!field.disabled) { 
                    930:             field.checked = true;
                    931:         }
1.273     raeburn   932:     }
                    933: }
                    934:  
                    935: function uncheckAll(field) {
                    936:     if (field.length > 0) {
                    937:         for (i = 0; i < field.length; i++) {
                    938:             field[i].checked = false ;
1.543     albertel  939:         }
                    940:     } else {
1.273     raeburn   941:         field.checked = false ;
                    942:     }
                    943: }
                    944: ENDSCRT
                    945:     return $jscript;
                    946: }
                    947: 
1.656     www       948: sub select_timezone {
1.1256    raeburn   949:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    950:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   951:    if ($includeempty) {
                    952:        $output .= '<option value=""';
                    953:        if (($selected eq '') || ($selected eq 'local')) {
                    954:            $output .= ' selected="selected" ';
                    955:        }
                    956:        $output .= '> </option>';
                    957:    }
1.657     raeburn   958:    my @timezones = DateTime::TimeZone->all_names;
                    959:    foreach my $tzone (@timezones) {
                    960:        $output.= '<option value="'.$tzone.'"';
                    961:        if ($tzone eq $selected) {
                    962:            $output.=' selected="selected"';
                    963:        }
                    964:        $output.=">$tzone</option>\n";
1.656     www       965:    }
                    966:    $output.="</select>";
                    967:    return $output;
                    968: }
1.273     raeburn   969: 
1.687     raeburn   970: sub select_datelocale {
1.1256    raeburn   971:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    972:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   973:     if ($includeempty) {
                    974:         $output .= '<option value=""';
                    975:         if ($selected eq '') {
                    976:             $output .= ' selected="selected" ';
                    977:         }
                    978:         $output .= '> </option>';
                    979:     }
1.1241    raeburn   980:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   981:     my (@possibles,%locale_names);
1.1241    raeburn   982:     my @locales = DateTime::Locale->ids();
                    983:     foreach my $id (@locales) {
                    984:         if ($id ne '') {
                    985:             my ($en_terr,$native_terr);
                    986:             my $loc = DateTime::Locale->load($id);
                    987:             if (ref($loc)) {
                    988:                 $en_terr = $loc->name();
                    989:                 $native_terr = $loc->native_name();
1.687     raeburn   990:                 if (grep(/^en$/,@languages) || !@languages) {
                    991:                     if ($en_terr ne '') {
                    992:                         $locale_names{$id} = '('.$en_terr.')';
                    993:                     } elsif ($native_terr ne '') {
                    994:                         $locale_names{$id} = $native_terr;
                    995:                     }
                    996:                 } else {
                    997:                     if ($native_terr ne '') {
                    998:                         $locale_names{$id} = $native_terr.' ';
                    999:                     } elsif ($en_terr ne '') {
                   1000:                         $locale_names{$id} = '('.$en_terr.')';
                   1001:                     }
                   1002:                 }
1.1220    raeburn  1003:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1004:                 push(@possibles,$id);
                   1005:             } 
1.687     raeburn  1006:         }
                   1007:     }
                   1008:     foreach my $item (sort(@possibles)) {
                   1009:         $output.= '<option value="'.$item.'"';
                   1010:         if ($item eq $selected) {
                   1011:             $output.=' selected="selected"';
                   1012:         }
                   1013:         $output.=">$item";
                   1014:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1015:             $output.='  '.$locale_names{$item};
1.687     raeburn  1016:         }
                   1017:         $output.="</option>\n";
                   1018:     }
                   1019:     $output.="</select>";
                   1020:     return $output;
                   1021: }
                   1022: 
1.792     raeburn  1023: sub select_language {
1.1256    raeburn  1024:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1025:     my %langchoices;
                   1026:     if ($includeempty) {
1.1117    raeburn  1027:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1028:     }
                   1029:     foreach my $id (&languageids()) {
                   1030:         my $code = &supportedlanguagecode($id);
                   1031:         if ($code) {
                   1032:             $langchoices{$code} = &plainlanguagedescription($id);
                   1033:         }
                   1034:     }
1.1117    raeburn  1035:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1036:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1037: }
                   1038: 
1.42      matthew  1039: =pod
1.36      matthew  1040: 
1.1088    foxr     1041: 
                   1042: =item * &list_languages()
                   1043: 
                   1044: Returns an array reference that is suitable for use in language prompters.
                   1045: Each array element is itself a two element array.  The first element
                   1046: is the language code.  The second element a descsriptiuon of the 
                   1047: language itself.  This is suitable for use in e.g.
                   1048: &Apache::edit::select_arg (once dereferenced that is).
                   1049: 
                   1050: =cut 
                   1051: 
                   1052: sub list_languages {
                   1053:     my @lang_choices;
                   1054: 
                   1055:     foreach my $id (&languageids()) {
                   1056: 	my $code = &supportedlanguagecode($id);
                   1057: 	if ($code) {
                   1058: 	    my $selector    = $supported_codes{$id};
                   1059: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1060: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1061: 	}
                   1062:     }
                   1063:     return \@lang_choices;
                   1064: }
                   1065: 
                   1066: =pod
                   1067: 
1.648     raeburn  1068: =item * &linked_select_forms(...)
1.36      matthew  1069: 
                   1070: linked_select_forms returns a string containing a <script></script> block
                   1071: and html for two <select> menus.  The select menus will be linked in that
                   1072: changing the value of the first menu will result in new values being placed
                   1073: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1074: order unless a defined order is provided.
1.36      matthew  1075: 
                   1076: linked_select_forms takes the following ordered inputs:
                   1077: 
                   1078: =over 4
                   1079: 
1.112     bowersj2 1080: =item * $formname, the name of the <form> tag
1.36      matthew  1081: 
1.112     bowersj2 1082: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1083: 
1.112     bowersj2 1084: =item * $firstdefault, the default value for the first menu
1.36      matthew  1085: 
1.112     bowersj2 1086: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1087: 
1.112     bowersj2 1088: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1089: 
1.112     bowersj2 1090: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1091: 
1.609     raeburn  1092: =item * $menuorder, the order of values in the first menu
                   1093: 
1.1115    raeburn  1094: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1095:         event for the first <select> tag
                   1096: 
                   1097: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1098:         event for the second <select> tag
                   1099: 
1.1245    raeburn  1100: =item * $suffix, to differentiate separate uses of select2data javascript
                   1101:         objects in a page.
                   1102: 
1.41      ng       1103: =back 
                   1104: 
1.36      matthew  1105: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1106: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1107: values for the first select menu.  The text that coincides with the 
1.41      ng       1108: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1109: and text for the second menu are given in the hash pointed to by 
                   1110: $menu{$choice1}->{'select2'}.  
                   1111: 
1.112     bowersj2 1112:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1113:                        default => "B3",
                   1114:                        select2 => { 
                   1115:                            B1 => "Choice B1",
                   1116:                            B2 => "Choice B2",
                   1117:                            B3 => "Choice B3",
                   1118:                            B4 => "Choice B4"
1.609     raeburn  1119:                            },
                   1120:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1121:                    },
                   1122:                A2 => { text =>"Choice A2" ,
                   1123:                        default => "C2",
                   1124:                        select2 => { 
                   1125:                            C1 => "Choice C1",
                   1126:                            C2 => "Choice C2",
                   1127:                            C3 => "Choice C3"
1.609     raeburn  1128:                            },
                   1129:                        order => ['C2','C1','C3'],
1.112     bowersj2 1130:                    },
                   1131:                A3 => { text =>"Choice A3" ,
                   1132:                        default => "D6",
                   1133:                        select2 => { 
                   1134:                            D1 => "Choice D1",
                   1135:                            D2 => "Choice D2",
                   1136:                            D3 => "Choice D3",
                   1137:                            D4 => "Choice D4",
                   1138:                            D5 => "Choice D5",
                   1139:                            D6 => "Choice D6",
                   1140:                            D7 => "Choice D7"
1.609     raeburn  1141:                            },
                   1142:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1143:                    }
                   1144:                );
1.36      matthew  1145: 
                   1146: =cut
                   1147: 
                   1148: sub linked_select_forms {
                   1149:     my ($formname,
                   1150:         $middletext,
                   1151:         $firstdefault,
                   1152:         $firstselectname,
                   1153:         $secondselectname, 
1.609     raeburn  1154:         $hashref,
                   1155:         $menuorder,
1.1115    raeburn  1156:         $onchangefirst,
1.1245    raeburn  1157:         $onchangesecond,
                   1158:         $suffix
1.36      matthew  1159:         ) = @_;
                   1160:     my $second = "document.$formname.$secondselectname";
                   1161:     my $first = "document.$formname.$firstselectname";
                   1162:     # output the javascript to do the changing
                   1163:     my $result = '';
1.776     bisitz   1164:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1165:     $result.="// <![CDATA[\n";
1.1245    raeburn  1166:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1167:     $" = '","';
                   1168:     my $debug = '';
                   1169:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1170:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1171:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1172:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1173:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1174:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1175:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1176:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1177:         }
1.36      matthew  1178:         $result.="\"@s2values\");\n";
1.1245    raeburn  1179:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1180:         my @s2texts;
                   1181:         foreach my $value (@s2values) {
1.1263    raeburn  1182:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1183:         }
                   1184:         $result.="\"@s2texts\");\n";
                   1185:     }
                   1186:     $"=' ';
                   1187:     $result.= <<"END";
                   1188: 
1.1245    raeburn  1189: function select1${suffix}_changed() {
1.36      matthew  1190:     // Determine new choice
1.1245    raeburn  1191:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1192:     // update select2
1.1245    raeburn  1193:     var values     = select2data${suffix}[newvalue].values;
                   1194:     var texts      = select2data${suffix}[newvalue].texts;
                   1195:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1196:     var i;
                   1197:     // out with the old
1.1245    raeburn  1198:     $second.options.length = 0;
                   1199:     // in with the new
1.36      matthew  1200:     for (i=0;i<values.length; i++) {
                   1201:         $second.options[i] = new Option(values[i]);
1.143     matthew  1202:         $second.options[i].value = values[i];
1.36      matthew  1203:         $second.options[i].text = texts[i];
                   1204:         if (values[i] == select2def) {
                   1205:             $second.options[i].selected = true;
                   1206:         }
                   1207:     }
                   1208: }
1.824     bisitz   1209: // ]]>
1.36      matthew  1210: </script>
                   1211: END
                   1212:     # output the initial values for the selection lists
1.1245    raeburn  1213:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1214:     my @order = sort(keys(%{$hashref}));
                   1215:     if (ref($menuorder) eq 'ARRAY') {
                   1216:         @order = @{$menuorder};
                   1217:     }
                   1218:     foreach my $value (@order) {
1.36      matthew  1219:         $result.="    <option value=\"$value\" ";
1.253     albertel 1220:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1221:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1222:     }
                   1223:     $result .= "</select>\n";
                   1224:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1225:     $result .= $middletext;
1.1115    raeburn  1226:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1227:     if ($onchangesecond) {
                   1228:         $result .= ' onchange="'.$onchangesecond.'"';
                   1229:     }
                   1230:     $result .= ">\n";
1.36      matthew  1231:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1232:     
                   1233:     my @secondorder = sort(keys(%select2));
                   1234:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1235:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1236:     }
                   1237:     foreach my $value (@secondorder) {
1.36      matthew  1238:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1239:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1240:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1241:     }
                   1242:     $result .= "</select>\n";
                   1243:     #    return $debug;
                   1244:     return $result;
                   1245: }   #  end of sub linked_select_forms {
                   1246: 
1.45      matthew  1247: =pod
1.44      bowersj2 1248: 
1.973     raeburn  1249: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1250: 
1.112     bowersj2 1251: Returns a string corresponding to an HTML link to the given help
                   1252: $topic, where $topic corresponds to the name of a .tex file in
                   1253: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1254: spaces. 
                   1255: 
                   1256: $text will optionally be linked to the same topic, allowing you to
                   1257: link text in addition to the graphic. If you do not want to link
                   1258: text, but wish to specify one of the later parameters, pass an
                   1259: empty string. 
                   1260: 
                   1261: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1262: the link will not open a new window. If false, the link will open
                   1263: a new window using Javascript. (Default is false.) 
                   1264: 
                   1265: $width and $height are optional numerical parameters that will
                   1266: override the width and height of the popped up window, which may
1.973     raeburn  1267: be useful for certain help topics with big pictures included.
                   1268: 
                   1269: $imgid is the id of the img tag used for the help icon. This may be
                   1270: used in a javascript call to switch the image src.  See 
                   1271: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1272: 
                   1273: =cut
                   1274: 
                   1275: sub help_open_topic {
1.973     raeburn  1276:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1277:     $text = "" if (not defined $text);
1.44      bowersj2 1278:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1279:     $width = 500 if (not defined $width);
1.44      bowersj2 1280:     $height = 400 if (not defined $height);
                   1281:     my $filename = $topic;
                   1282:     $filename =~ s/ /_/g;
                   1283: 
1.48      bowersj2 1284:     my $template = "";
                   1285:     my $link;
1.572     banghart 1286:     
1.159     www      1287:     $topic=~s/\W/\_/g;
1.44      bowersj2 1288: 
1.572     banghart 1289:     if (!$stayOnPage) {
1.1033    www      1290: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1291:     } elsif ($stayOnPage eq 'popup') {
                   1292:         $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 1293:     } else {
1.48      bowersj2 1294: 	$link = "/adm/help/${filename}.hlp";
                   1295:     }
                   1296: 
                   1297:     # Add the text
1.755     neumanie 1298:     if ($text ne "") {	
1.763     bisitz   1299: 	$template.='<span class="LC_help_open_topic">'
                   1300:                   .'<a target="_top" href="'.$link.'">'
                   1301:                   .$text.'</a>';
1.48      bowersj2 1302:     }
                   1303: 
1.763     bisitz   1304:     # (Always) Add the graphic
1.179     matthew  1305:     my $title = &mt('Online Help');
1.667     raeburn  1306:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1307:     if ($imgid ne '') {
                   1308:         $imgid = ' id="'.$imgid.'"';
                   1309:     }
1.763     bisitz   1310:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1311:               .'<img src="'.$helpicon.'" border="0"'
                   1312:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1313:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1314:               .' /></a>';
                   1315:     if ($text ne "") {	
                   1316:         $template.='</span>';
                   1317:     }
1.44      bowersj2 1318:     return $template;
                   1319: 
1.106     bowersj2 1320: }
                   1321: 
                   1322: # This is a quicky function for Latex cheatsheet editing, since it 
                   1323: # appears in at least four places
                   1324: sub helpLatexCheatsheet {
1.1037    www      1325:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1326:     my $out;
1.106     bowersj2 1327:     my $addOther = '';
1.732     raeburn  1328:     if ($topic) {
1.1037    www      1329: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1330:     }
                   1331:     $out = '<span>' # Start cheatsheet
                   1332: 	  .$addOther
                   1333:           .'<span>'
1.1037    www      1334: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1335: 	  .'</span> <span>'
1.1037    www      1336: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1337: 	  .'</span>';
1.732     raeburn  1338:     unless ($not_author) {
1.1186    kruse    1339:         $out .= '<span>'
                   1340:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1341:                .'</span> <span>'
                   1342:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1343: 	       .'</span>';
1.732     raeburn  1344:     }
1.763     bisitz   1345:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1346:     return $out;
1.172     www      1347: }
                   1348: 
1.430     albertel 1349: sub general_help {
                   1350:     my $helptopic='Student_Intro';
                   1351:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1352: 	$helptopic='Authoring_Intro';
1.907     raeburn  1353:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1354: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1355:     } elsif ($env{'request.role'}=~/^dc/) {
                   1356:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1357:     }
                   1358:     return $helptopic;
                   1359: }
                   1360: 
                   1361: sub update_help_link {
                   1362:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1363:     my $origurl = $ENV{'REQUEST_URI'};
                   1364:     $origurl=~s|^/~|/priv/|;
                   1365:     my $timestamp = time;
                   1366:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1367:         $$datum = &escape($$datum);
                   1368:     }
                   1369: 
                   1370:     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";
                   1371:     my $output .= <<"ENDOUTPUT";
                   1372: <script type="text/javascript">
1.824     bisitz   1373: // <![CDATA[
1.430     albertel 1374: banner_link = '$banner_link';
1.824     bisitz   1375: // ]]>
1.430     albertel 1376: </script>
                   1377: ENDOUTPUT
                   1378:     return $output;
                   1379: }
                   1380: 
                   1381: # now just updates the help link and generates a blue icon
1.193     raeburn  1382: sub help_open_menu {
1.430     albertel 1383:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1384: 	= @_;    
1.949     droeschl 1385:     $stayOnPage = 1;
1.430     albertel 1386:     my $output;
                   1387:     if ($component_help) {
                   1388: 	if (!$text) {
                   1389: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1390: 				       $width,$height);
                   1391: 	} else {
                   1392: 	    my $help_text;
                   1393: 	    $help_text=&unescape($topic);
                   1394: 	    $output='<table><tr><td>'.
                   1395: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1396: 				 $width,$height).'</td></tr></table>';
                   1397: 	}
                   1398:     }
                   1399:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1400:     return $output.$banner_link;
                   1401: }
                   1402: 
                   1403: sub top_nav_help {
                   1404:     my ($text) = @_;
1.436     albertel 1405:     $text = &mt($text);
1.949     droeschl 1406:     my $stay_on_page = 1;
                   1407: 
1.1168    raeburn  1408:     my ($link,$banner_link);
                   1409:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1410:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1411: 	                         : "javascript:helpMenu('open')";
                   1412:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1413:     }
1.201     raeburn  1414:     my $title = &mt('Get help');
1.1168    raeburn  1415:     if ($link) {
                   1416:         return <<"END";
1.436     albertel 1417: $banner_link
1.1159    raeburn  1418: <a href="$link" title="$title">$text</a>
1.436     albertel 1419: END
1.1168    raeburn  1420:     } else {
                   1421:         return '&nbsp;'.$text.'&nbsp;';
                   1422:     }
1.436     albertel 1423: }
                   1424: 
                   1425: sub help_menu_js {
1.1154    raeburn  1426:     my ($httphost) = @_;
1.949     droeschl 1427:     my $stayOnPage = 1;
1.436     albertel 1428:     my $width = 620;
                   1429:     my $height = 600;
1.430     albertel 1430:     my $helptopic=&general_help();
1.1154    raeburn  1431:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1432:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1433:     my $start_page =
                   1434:         &Apache::loncommon::start_page('Help Menu', undef,
                   1435: 				       {'frameset'    => 1,
                   1436: 					'js_ready'    => 1,
1.1154    raeburn  1437:                                         'use_absolute' => $httphost,
1.331     albertel 1438: 					'add_entries' => {
1.1168    raeburn  1439: 					    'border' => '0', 
1.579     raeburn  1440: 					    'rows'   => "110,*",},});
1.331     albertel 1441:     my $end_page =
                   1442:         &Apache::loncommon::end_page({'frameset' => 1,
                   1443: 				      'js_ready' => 1,});
                   1444: 
1.436     albertel 1445:     my $template .= <<"ENDTEMPLATE";
                   1446: <script type="text/javascript">
1.877     bisitz   1447: // <![CDATA[
1.253     albertel 1448: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1449: var banner_link = '';
1.243     raeburn  1450: function helpMenu(target) {
                   1451:     var caller = this;
                   1452:     if (target == 'open') {
                   1453:         var newWindow = null;
                   1454:         try {
1.262     albertel 1455:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1456:         }
                   1457:         catch(error) {
                   1458:             writeHelp(caller);
                   1459:             return;
                   1460:         }
                   1461:         if (newWindow) {
                   1462:             caller = newWindow;
                   1463:         }
1.193     raeburn  1464:     }
1.243     raeburn  1465:     writeHelp(caller);
                   1466:     return;
                   1467: }
                   1468: function writeHelp(caller) {
1.1168    raeburn  1469:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1470:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1471:     caller.document.close();
                   1472:     caller.focus();
1.193     raeburn  1473: }
1.877     bisitz   1474: // END LON-CAPA Internal -->
1.253     albertel 1475: // ]]>
1.436     albertel 1476: </script>
1.193     raeburn  1477: ENDTEMPLATE
                   1478:     return $template;
                   1479: }
                   1480: 
1.172     www      1481: sub help_open_bug {
                   1482:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1483:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1484:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1485:     $text = "" if (not defined $text);
                   1486: 	$stayOnPage=1;
1.184     albertel 1487:     $width = 600 if (not defined $width);
                   1488:     $height = 600 if (not defined $height);
1.172     www      1489: 
                   1490:     $topic=~s/\W+/\+/g;
                   1491:     my $link='';
                   1492:     my $template='';
1.379     albertel 1493:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1494: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1495:     if (!$stayOnPage)
                   1496:     {
                   1497: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1498:     }
                   1499:     else
                   1500:     {
                   1501: 	$link = $url;
                   1502:     }
                   1503:     # Add the text
                   1504:     if ($text ne "")
                   1505:     {
                   1506: 	$template .= 
                   1507:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1508:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1509:     }
                   1510: 
                   1511:     # Add the graphic
1.179     matthew  1512:     my $title = &mt('Report a Bug');
1.215     albertel 1513:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1514:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1515:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1516: ENDTEMPLATE
                   1517:     if ($text ne '') { $template.='</td></tr></table>' };
                   1518:     return $template;
                   1519: 
                   1520: }
                   1521: 
                   1522: sub help_open_faq {
                   1523:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1524:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1525:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1526:     $text = "" if (not defined $text);
                   1527: 	$stayOnPage=1;
                   1528:     $width = 350 if (not defined $width);
                   1529:     $height = 400 if (not defined $height);
                   1530: 
                   1531:     $topic=~s/\W+/\+/g;
                   1532:     my $link='';
                   1533:     my $template='';
                   1534:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1535:     if (!$stayOnPage)
                   1536:     {
                   1537: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1538:     }
                   1539:     else
                   1540:     {
                   1541: 	$link = $url;
                   1542:     }
                   1543: 
                   1544:     # Add the text
                   1545:     if ($text ne "")
                   1546:     {
                   1547: 	$template .= 
1.173     www      1548:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1549:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1550:     }
                   1551: 
                   1552:     # Add the graphic
1.179     matthew  1553:     my $title = &mt('View the FAQ');
1.215     albertel 1554:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1555:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1556:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1557: ENDTEMPLATE
                   1558:     if ($text ne '') { $template.='</td></tr></table>' };
                   1559:     return $template;
                   1560: 
1.44      bowersj2 1561: }
1.37      matthew  1562: 
1.180     matthew  1563: ###############################################################
                   1564: ###############################################################
                   1565: 
1.45      matthew  1566: =pod
                   1567: 
1.648     raeburn  1568: =item * &change_content_javascript():
1.256     matthew  1569: 
                   1570: This and the next function allow you to create small sections of an
                   1571: otherwise static HTML page that you can update on the fly with
                   1572: Javascript, even in Netscape 4.
                   1573: 
                   1574: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1575: must be written to the HTML page once. It will prove the Javascript
                   1576: function "change(name, content)". Calling the change function with the
                   1577: name of the section 
                   1578: you want to update, matching the name passed to C<changable_area>, and
                   1579: the new content you want to put in there, will put the content into
                   1580: that area.
                   1581: 
                   1582: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1583: to contain room for the original contents. You need to "make space"
                   1584: for whatever changes you wish to make, and be B<sure> to check your
                   1585: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1586: it's adequate for updating a one-line status display, but little more.
                   1587: This script will set the space to 100% width, so you only need to
                   1588: worry about height in Netscape 4.
                   1589: 
                   1590: Modern browsers are much less limiting, and if you can commit to the
                   1591: user not using Netscape 4, this feature may be used freely with
                   1592: pretty much any HTML.
                   1593: 
                   1594: =cut
                   1595: 
                   1596: sub change_content_javascript {
                   1597:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1598:     if ($env{'browser.type'} eq 'netscape' &&
                   1599: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1600: 	return (<<NETSCAPE4);
                   1601: 	function change(name, content) {
                   1602: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1603: 	    doc.open();
                   1604: 	    doc.write(content);
                   1605: 	    doc.close();
                   1606: 	}
                   1607: NETSCAPE4
                   1608:     } else {
                   1609: 	# Otherwise, we need to use semi-standards-compliant code
                   1610: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1611: 	# is really scary, and every useful browser supports it
                   1612: 	return (<<DOMBASED);
                   1613: 	function change(name, content) {
                   1614: 	    element = document.getElementById(name);
                   1615: 	    element.innerHTML = content;
                   1616: 	}
                   1617: DOMBASED
                   1618:     }
                   1619: }
                   1620: 
                   1621: =pod
                   1622: 
1.648     raeburn  1623: =item * &changable_area($name,$origContent):
1.256     matthew  1624: 
                   1625: This provides a "changable area" that can be modified on the fly via
                   1626: the Javascript code provided in C<change_content_javascript>. $name is
                   1627: the name you will use to reference the area later; do not repeat the
                   1628: same name on a given HTML page more then once. $origContent is what
                   1629: the area will originally contain, which can be left blank.
                   1630: 
                   1631: =cut
                   1632: 
                   1633: sub changable_area {
                   1634:     my ($name, $origContent) = @_;
                   1635: 
1.258     albertel 1636:     if ($env{'browser.type'} eq 'netscape' &&
                   1637: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1638: 	# If this is netscape 4, we need to use the Layer tag
                   1639: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1640:     } else {
                   1641: 	return "<span id='$name'>$origContent</span>";
                   1642:     }
                   1643: }
                   1644: 
                   1645: =pod
                   1646: 
1.648     raeburn  1647: =item * &viewport_geometry_js 
1.590     raeburn  1648: 
                   1649: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1650: 
                   1651: =cut
                   1652: 
                   1653: 
                   1654: sub viewport_geometry_js { 
                   1655:     return <<"GEOMETRY";
                   1656: var Geometry = {};
                   1657: function init_geometry() {
                   1658:     if (Geometry.init) { return };
                   1659:     Geometry.init=1;
                   1660:     if (window.innerHeight) {
                   1661:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1662:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1663:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1664:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1665:     }
                   1666:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1667:         Geometry.getViewportHeight =
                   1668:             function() { return document.documentElement.clientHeight; };
                   1669:         Geometry.getViewportWidth =
                   1670:             function() { return document.documentElement.clientWidth; };
                   1671: 
                   1672:         Geometry.getHorizontalScroll =
                   1673:             function() { return document.documentElement.scrollLeft; };
                   1674:         Geometry.getVerticalScroll =
                   1675:             function() { return document.documentElement.scrollTop; };
                   1676:     }
                   1677:     else if (document.body.clientHeight) {
                   1678:         Geometry.getViewportHeight =
                   1679:             function() { return document.body.clientHeight; };
                   1680:         Geometry.getViewportWidth =
                   1681:             function() { return document.body.clientWidth; };
                   1682:         Geometry.getHorizontalScroll =
                   1683:             function() { return document.body.scrollLeft; };
                   1684:         Geometry.getVerticalScroll =
                   1685:             function() { return document.body.scrollTop; };
                   1686:     }
                   1687: }
                   1688: 
                   1689: GEOMETRY
                   1690: }
                   1691: 
                   1692: =pod
                   1693: 
1.648     raeburn  1694: =item * &viewport_size_js()
1.590     raeburn  1695: 
                   1696: 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. 
                   1697: 
                   1698: =cut
                   1699: 
                   1700: sub viewport_size_js {
                   1701:     my $geometry = &viewport_geometry_js();
                   1702:     return <<"DIMS";
                   1703: 
                   1704: $geometry
                   1705: 
                   1706: function getViewportDims(width,height) {
                   1707:     init_geometry();
                   1708:     width.value = Geometry.getViewportWidth();
                   1709:     height.value = Geometry.getViewportHeight();
                   1710:     return;
                   1711: }
                   1712: 
                   1713: DIMS
                   1714: }
                   1715: 
                   1716: =pod
                   1717: 
1.648     raeburn  1718: =item * &resize_textarea_js()
1.565     albertel 1719: 
                   1720: emits the needed javascript to resize a textarea to be as big as possible
                   1721: 
                   1722: creates a function resize_textrea that takes two IDs first should be
                   1723: the id of the element to resize, second should be the id of a div that
                   1724: surrounds everything that comes after the textarea, this routine needs
                   1725: to be attached to the <body> for the onload and onresize events.
                   1726: 
1.648     raeburn  1727: =back
1.565     albertel 1728: 
                   1729: =cut
                   1730: 
                   1731: sub resize_textarea_js {
1.590     raeburn  1732:     my $geometry = &viewport_geometry_js();
1.565     albertel 1733:     return <<"RESIZE";
                   1734:     <script type="text/javascript">
1.824     bisitz   1735: // <![CDATA[
1.590     raeburn  1736: $geometry
1.565     albertel 1737: 
1.588     albertel 1738: function getX(element) {
                   1739:     var x = 0;
                   1740:     while (element) {
                   1741: 	x += element.offsetLeft;
                   1742: 	element = element.offsetParent;
                   1743:     }
                   1744:     return x;
                   1745: }
                   1746: function getY(element) {
                   1747:     var y = 0;
                   1748:     while (element) {
                   1749: 	y += element.offsetTop;
                   1750: 	element = element.offsetParent;
                   1751:     }
                   1752:     return y;
                   1753: }
                   1754: 
                   1755: 
1.565     albertel 1756: function resize_textarea(textarea_id,bottom_id) {
                   1757:     init_geometry();
                   1758:     var textarea        = document.getElementById(textarea_id);
                   1759:     //alert(textarea);
                   1760: 
1.588     albertel 1761:     var textarea_top    = getY(textarea);
1.565     albertel 1762:     var textarea_height = textarea.offsetHeight;
                   1763:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1764:     var bottom_top      = getY(bottom);
1.565     albertel 1765:     var bottom_height   = bottom.offsetHeight;
                   1766:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1767:     var fudge           = 23;
1.565     albertel 1768:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1769:     if (new_height < 300) {
                   1770: 	new_height = 300;
                   1771:     }
                   1772:     textarea.style.height=new_height+'px';
                   1773: }
1.824     bisitz   1774: // ]]>
1.565     albertel 1775: </script>
                   1776: RESIZE
                   1777: 
                   1778: }
                   1779: 
1.1205    golterma 1780: sub colorfuleditor_js {
1.1248    raeburn  1781:     my $browse_or_search;
                   1782:     my $respath;
                   1783:     my ($cnum,$cdom) = &crsauthor_url();
                   1784:     if ($cnum) {
                   1785:         $respath = "/res/$cdom/$cnum/";
                   1786:         my %js_lt = &Apache::lonlocal::texthash(
                   1787:             sunm => 'Sub-directory name',
                   1788:             save => 'Save page to make this permanent',
                   1789:         );
                   1790:         &js_escape(\%js_lt);
                   1791:         $browse_or_search = <<"END";
                   1792: 
                   1793:     function toggleChooser(form,element,titleid,only,search) {
                   1794:         var disp = 'none';
                   1795:         if (document.getElementById('chooser_'+element)) {
                   1796:             var curr = document.getElementById('chooser_'+element).style.display;
                   1797:             if (curr == 'none') {
                   1798:                 disp='inline';
                   1799:                 if (form.elements['chooser_'+element].length) {
                   1800:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1801:                         form.elements['chooser_'+element][i].checked = false;
                   1802:                     }
                   1803:                 }
                   1804:                 toggleResImport(form,element);
                   1805:             }
                   1806:             document.getElementById('chooser_'+element).style.display = disp;
                   1807:         }
                   1808:     }
                   1809: 
                   1810:     function toggleCrsFile(form,element,numdirs) {
                   1811:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1812:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1813:             if (curr == 'none') {
                   1814:                 if (numdirs) {
                   1815:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1816:                     if (numdirs > 1) {
                   1817:                         window['select1'+element+'_changed']();
                   1818:                     }
                   1819:                 }
                   1820:             } 
                   1821:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1822:             
                   1823:         }
                   1824:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1825:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1826:             if (document.getElementById('uploadcrsres_'+element)) {
                   1827:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1828:             }
                   1829:         }
                   1830:         return;
                   1831:     }
                   1832: 
                   1833:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1834:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1835:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1836:         }
                   1837:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1838:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1839:             if (curr == 'none') {
                   1840:                 if (numcrsdirs) {
                   1841:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1842:                    form.elements['newsubdir_'+element][0].checked = true;
                   1843:                    toggleNewsubdir(form,element);
                   1844:                 }
                   1845:             }
                   1846:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1847:         }
                   1848:         return;
                   1849:     }
                   1850: 
                   1851:     function toggleResImport(form,element) {
                   1852:         var choices = new Array('crsres','upload');
                   1853:         for (var i=0; i<choices.length; i++) {
                   1854:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1855:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1856:             }
                   1857:         }
                   1858:     }
                   1859: 
                   1860:     function toggleNewsubdir(form,element) {
                   1861:         var newsub = form.elements['newsubdir_'+element];
                   1862:         if (newsub) {
                   1863:             if (newsub.length) {
                   1864:                 for (var j=0; j<newsub.length; j++) {
                   1865:                     if (newsub[j].checked) {
                   1866:                         if (document.getElementById('newsubdirname_'+element)) {
                   1867:                             if (newsub[j].value == '1') {
                   1868:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1869:                                 if (document.getElementById('newsubdir_'+element)) {
                   1870:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1871:                                 }
                   1872:                             } else {
                   1873:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1874:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1875:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1876:                             }
                   1877:                         }
                   1878:                         break; 
                   1879:                     }
                   1880:                 }
                   1881:             }
                   1882:         }
                   1883:     }
                   1884: 
                   1885:     function updateCrsFile(form,element) {
                   1886:         var directory = form.elements['coursepath_'+element];
                   1887:         var filename = form.elements['coursefile_'+element];
                   1888:         var path = directory.options[directory.selectedIndex].value;
                   1889:         var file = filename.options[filename.selectedIndex].value;
                   1890:         form.elements[element].value = '$respath';
                   1891:         if (path == '/') {
                   1892:             form.elements[element].value += file;
                   1893:         } else {
                   1894:             form.elements[element].value += path+'/'+file;
                   1895:         }
                   1896:         unClean();
                   1897:         if (document.getElementById('previewimg_'+element)) {
                   1898:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1899:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1900:         }
                   1901:         if (document.getElementById('showimg_'+element)) {
                   1902:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1903:         }
                   1904:         toggleChooser(form,element);
                   1905:         return;
                   1906:     }
                   1907: 
                   1908:     function uploadDone(suffix,name) {
                   1909:         if (name) {
                   1910: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1911:             unClean();
                   1912:             toggleChooser(document.forms["lonhomework"],suffix);
                   1913:         }
                   1914:     }
                   1915: 
                   1916: \$(document).ready(function(){
                   1917: 
                   1918:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1919:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1920:             var buttonId = this.id;
                   1921:             var suffix = buttonId.toString();
                   1922:             suffix = suffix.replace(/^crsupload_/,'');
                   1923:             event.preventDefault();
                   1924:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1925:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1926:             \$(this.form).submit();
                   1927:             document.lonhomework.target = '';
                   1928:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1929:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1930:             }
                   1931:             return false;
                   1932:         }
                   1933:     });
                   1934: });
                   1935: END
                   1936:     }
1.1205    golterma 1937:     return <<"COLORFULEDIT"
                   1938: <script type="text/javascript">
                   1939: // <![CDATA[>
                   1940:     function fold_box(curDepth, lastresource){
                   1941: 
                   1942:     // we need a list because there can be several blocks you need to fold in one tag
                   1943:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1944:     // but there is only one folding button per tag
                   1945:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1946: 
                   1947:         if(block.item(0).style.display == 'none'){
                   1948: 
                   1949:             foldbutton.value = '@{[&mt("Hide")]}';
                   1950:             for (i = 0; i < block.length; i++){
                   1951:                 block.item(i).style.display = '';
                   1952:             }
                   1953:         }else{
                   1954: 
                   1955:             foldbutton.value = '@{[&mt("Show")]}';
                   1956:             for (i = 0; i < block.length; i++){
                   1957:                 // block.item(i).style.visibility = 'collapse';
                   1958:                 block.item(i).style.display = 'none';
                   1959:             }
                   1960:         };
                   1961:         saveState(lastresource);
                   1962:     }
                   1963: 
                   1964:     function saveState (lastresource) {
                   1965: 
                   1966:         var tag_list = getTagList();
                   1967:         if(tag_list != null){
                   1968:             var timestamp = new Date().getTime();
                   1969:             var key = lastresource;
                   1970: 
                   1971:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1972:             // starting with timestamp
                   1973:             var value = timestamp+';';
                   1974: 
                   1975:             // building the list of key-value pairs
                   1976:             for(var i = 0; i < tag_list.length; i++){
                   1977:                 value += tag_list[i]+',';
                   1978:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1979:             }
                   1980: 
                   1981:             // only iterate whole storage if nothing to override
                   1982:             if(localStorage.getItem(key) == null){        
                   1983: 
                   1984:                 // prevent storage from growing large
                   1985:                 if(localStorage.length > 50){
                   1986:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1987:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1988:                     var oldest_key;
                   1989:                     
                   1990:                     for(var i = 1; i < localStorage.length; i++){
                   1991:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1992:                             oldest_key = localStorage.key(i);
                   1993:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1994:                         }
                   1995:                     }
                   1996:                     localStorage.removeItem(oldest_key);
                   1997:                 }
                   1998:             }
                   1999:             localStorage.setItem(key,value);
                   2000:         }
                   2001:     }
                   2002: 
                   2003:     // restore folding status of blocks (on page load)
                   2004:     function restoreState (lastresource) {
                   2005:         if(localStorage.getItem(lastresource) != null){
                   2006:             var key = lastresource;
                   2007:             var value = localStorage.getItem(key);
                   2008:             var regex_delTimestamp = /^\d+;/;
                   2009: 
                   2010:             value.replace(regex_delTimestamp, '');
                   2011: 
                   2012:             var valueArr = value.split(';');
                   2013:             var pairs;
                   2014:             var elements;
                   2015:             for (var i = 0; i < valueArr.length; i++){
                   2016:                 pairs = valueArr[i].split(',');
                   2017:                 elements = document.getElementsByName(pairs[0]);
                   2018: 
                   2019:                 for (var j = 0; j < elements.length; j++){  
                   2020:                     elements[j].style.display = pairs[1];
                   2021:                     if (pairs[1] == "none"){
                   2022:                         var regex_id = /([_\\d]+)\$/;
                   2023:                         regex_id.exec(pairs[0]);
                   2024:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2025:                     }
                   2026:                 }
                   2027:             }
                   2028:         }
                   2029:     }
                   2030: 
                   2031:     function getTagList () {
                   2032:         
                   2033:         var stringToSearch = document.lonhomework.innerHTML;
                   2034: 
                   2035:         var ret = new Array();
                   2036:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2037:         var tag_list = stringToSearch.match(regex_findBlock);
                   2038: 
                   2039:         if(tag_list != null){
                   2040:             for(var i = 0; i < tag_list.length; i++){            
                   2041:                 ret.push(tag_list[i].replace(/"/, ''));
                   2042:             }
                   2043:         }
                   2044:         return ret;
                   2045:     }
                   2046: 
                   2047:     function saveScrollPosition (resource) {
                   2048:         var tag_list = getTagList();
                   2049: 
                   2050:         // we dont always want to jump to the first block
                   2051:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2052:         if(\$(window).scrollTop() > 170){
                   2053:             if(tag_list != null){
                   2054:                 var result;
                   2055:                 for(var i = 0; i < tag_list.length; i++){
                   2056:                     if(isElementInViewport(tag_list[i])){
                   2057:                         result += tag_list[i]+';';
                   2058:                     }
                   2059:                 }
                   2060:                 sessionStorage.setItem('anchor_'+resource, result);
                   2061:             }
                   2062:         } else {
                   2063:             // we dont need to save zero, just delete the item to leave everything tidy
                   2064:             sessionStorage.removeItem('anchor_'+resource);
                   2065:         }
                   2066:     }
                   2067: 
                   2068:     function restoreScrollPosition(resource){
                   2069: 
                   2070:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2071:         if(elem != null){
                   2072:             var tag_list = elem.split(';');
                   2073:             var elem_list;
                   2074: 
                   2075:             for(var i = 0; i < tag_list.length; i++){
                   2076:                 elem_list = document.getElementsByName(tag_list[i]);
                   2077:                 
                   2078:                 if(elem_list.length > 0){
                   2079:                     elem = elem_list[0];
                   2080:                     break;
                   2081:                 }
                   2082:             }
                   2083:             elem.scrollIntoView();
                   2084:         }
                   2085:     }
                   2086: 
                   2087:     function isElementInViewport(el) {
                   2088: 
                   2089:         // change to last element instead of first
                   2090:         var elem = document.getElementsByName(el);
                   2091:         var rect = elem[0].getBoundingClientRect();
                   2092: 
                   2093:         return (
                   2094:             rect.top >= 0 &&
                   2095:             rect.left >= 0 &&
                   2096:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2097:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2098:         );
                   2099:     }
                   2100:     
                   2101:     function autosize(depth){
                   2102:         var cmInst = window['cm'+depth];
                   2103:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2104: 
                   2105:         // is fixed size, switching to dynamic
                   2106:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2107:             cmInst.setSize("","auto");
                   2108:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2109:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2110: 
                   2111:         // is dynamic size, switching to fixed
                   2112:         } else {
                   2113:             cmInst.setSize("","300px");
                   2114:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2115:             sessionStorage.removeItem("autosized_"+depth);
                   2116:         }
                   2117:     }
                   2118: 
1.1248    raeburn  2119: $browse_or_search
1.1205    golterma 2120: 
                   2121: // ]]>
                   2122: </script>
                   2123: COLORFULEDIT
                   2124: }
                   2125: 
                   2126: sub xmleditor_js {
                   2127:     return <<XMLEDIT
                   2128: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2129: <script type="text/javascript">
                   2130: // <![CDATA[>
                   2131: 
                   2132:     function saveScrollPosition (resource) {
                   2133: 
                   2134:         var scrollPos = \$(window).scrollTop();
                   2135:         sessionStorage.setItem(resource,scrollPos);
                   2136:     }
                   2137: 
                   2138:     function restoreScrollPosition(resource){
                   2139: 
                   2140:         var scrollPos = sessionStorage.getItem(resource);
                   2141:         \$(window).scrollTop(scrollPos);
                   2142:     }
                   2143: 
                   2144:     // unless internet explorer
                   2145:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2146: 
                   2147:         \$(document).ready(function() {
                   2148:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2149:         });
                   2150:     }
                   2151: 
                   2152:     // inserts text at cursor position into codemirror (xml editor only)
                   2153:     function insertText(text){
                   2154:         cm.focus();
                   2155:         var curPos = cm.getCursor();
                   2156:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2157:     }
                   2158: // ]]>
                   2159: </script>
                   2160: XMLEDIT
                   2161: }
                   2162: 
                   2163: sub insert_folding_button {
                   2164:     my $curDepth = $Apache::lonxml::curdepth;
                   2165:     my $lastresource = $env{'request.ambiguous'};
                   2166: 
                   2167:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2168:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2169: }
                   2170: 
1.1248    raeburn  2171: sub crsauthor_url {
                   2172:     my ($url) = @_;
                   2173:     if ($url eq '') {
                   2174:         $url = $ENV{'REQUEST_URI'};
                   2175:     }
                   2176:     my ($cnum,$cdom);
                   2177:     if ($env{'request.course.id'}) {
                   2178:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2179:         if ($audom ne '' && $auname ne '') {
                   2180:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2181:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2182:                 $cnum = $auname;
                   2183:                 $cdom = $audom;
                   2184:             }
                   2185:         }
                   2186:     }
                   2187:     return ($cnum,$cdom);
                   2188: }
                   2189: 
                   2190: sub import_crsauthor_form {
1.1265    raeburn  2191:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2192:     return (0) unless ($env{'request.course.id'});
                   2193:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2194:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2195:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2196:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2197:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2198:     my @ids=&Apache::lonnet::current_machine_ids();
                   2199:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2200:     
                   2201:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2202:         $is_home = 1;
                   2203:     }
                   2204:     $relpath = "/priv/$cdom/$cnum";
                   2205:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2206:     my %lt = &Apache::lonlocal::texthash (
                   2207:         fnam => 'Filename',
                   2208:         dire => 'Directory',
                   2209:     );
                   2210:     my $numdirs = scalar(keys(%files));
                   2211:     my (%possexts,$singledir,@singledirfiles);
                   2212:     if ($only) {
                   2213:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2214:     }
                   2215:     my (%nonemptydirs,$possdirs);
                   2216:     if ($numdirs > 1) {
                   2217:         my @order;
                   2218:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2219:             if (ref($files{$key}) eq 'HASH') {
                   2220:                 my $shown = $key;
                   2221:                 if ($key eq '') {
                   2222:                     $shown = '/';
                   2223:                 }
                   2224:                 my @ordered = ();
                   2225:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
                   2226:                     if ($only) {
                   2227:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2228:                         unless ($possexts{lc($ext)}) {
                   2229:                             next;
                   2230:                         }
                   2231:                     }
                   2232:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2233:                     push(@ordered,$file);
                   2234:                 }
                   2235:                 if (@ordered) {
                   2236:                     push(@order,$key);
                   2237:                     $nonemptydirs{$key} = 1;
                   2238:                     $selimport_menus{$key}->{'text'} = $shown;
                   2239:                     $selimport_menus{$key}->{'default'} = '';
                   2240:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2241:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2242:                 }
                   2243:             }
                   2244:         }
                   2245:         $possdirs = scalar(keys(%nonemptydirs));
                   2246:         if ($possdirs > 1) {
                   2247:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2248:             $output = $lt{'dire'}.
                   2249:                       &linked_select_forms($form,'<br />'.
                   2250:                                            $lt{'fnam'},'',
                   2251:                                            $firstselectname,$secondselectname,
                   2252:                                            \%selimport_menus,\@order,
                   2253:                                            $onchangefirst,'',$suffix).'<br />';
                   2254:         } elsif ($possdirs == 1) {
                   2255:             $singledir = (keys(%nonemptydirs))[0];
                   2256:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2257:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2258:             }
                   2259:             delete($selimport_menus{$singledir});
                   2260:         }
                   2261:     } elsif ($numdirs == 1) {
                   2262:         $singledir = (keys(%files))[0];
                   2263:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2264:             if ($only) {
                   2265:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2266:                 unless ($possexts{lc($ext)}) {
                   2267:                     next;
                   2268:                 }
                   2269:             }
                   2270:             push(@singledirfiles,$file);
                   2271:         }
                   2272:         if (@singledirfiles) {
                   2273:             $possdirs == 1;
                   2274:         }
                   2275:     }
                   2276:     if (($possdirs == 1) && (@singledirfiles)) {
                   2277:         my $showdir = $singledir;
                   2278:         if ($singledir eq '') {
                   2279:             $showdir = '/';
                   2280:         }
                   2281:         $output = $lt{'dire'}.
                   2282:                   '<select name="'.$firstselectname.'">'.
                   2283:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2284:                   '</select><br />'.
                   2285:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2286:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2287:         foreach my $file (@singledirfiles) {
                   2288:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2289:         }
                   2290:         $output .= '</select><br />'."\n";
                   2291:     }
                   2292:     return ($possdirs,$output);
                   2293: }
                   2294: 
1.565     albertel 2295: =pod
                   2296: 
1.256     matthew  2297: =head1 Excel and CSV file utility routines
                   2298: 
                   2299: =cut
                   2300: 
                   2301: ###############################################################
                   2302: ###############################################################
                   2303: 
                   2304: =pod
                   2305: 
1.1162    raeburn  2306: =over 4
                   2307: 
1.648     raeburn  2308: =item * &csv_translate($text) 
1.37      matthew  2309: 
1.185     www      2310: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2311: format.
                   2312: 
                   2313: =cut
                   2314: 
1.180     matthew  2315: ###############################################################
                   2316: ###############################################################
1.37      matthew  2317: sub csv_translate {
                   2318:     my $text = shift;
                   2319:     $text =~ s/\"/\"\"/g;
1.209     albertel 2320:     $text =~ s/\n/ /g;
1.37      matthew  2321:     return $text;
                   2322: }
1.180     matthew  2323: 
                   2324: ###############################################################
                   2325: ###############################################################
                   2326: 
                   2327: =pod
                   2328: 
1.648     raeburn  2329: =item * &define_excel_formats()
1.180     matthew  2330: 
                   2331: Define some commonly used Excel cell formats.
                   2332: 
                   2333: Currently supported formats:
                   2334: 
                   2335: =over 4
                   2336: 
                   2337: =item header
                   2338: 
                   2339: =item bold
                   2340: 
                   2341: =item h1
                   2342: 
                   2343: =item h2
                   2344: 
                   2345: =item h3
                   2346: 
1.256     matthew  2347: =item h4
                   2348: 
                   2349: =item i
                   2350: 
1.180     matthew  2351: =item date
                   2352: 
                   2353: =back
                   2354: 
                   2355: Inputs: $workbook
                   2356: 
                   2357: Returns: $format, a hash reference.
                   2358: 
1.1057    foxr     2359: 
1.180     matthew  2360: =cut
                   2361: 
                   2362: ###############################################################
                   2363: ###############################################################
                   2364: sub define_excel_formats {
                   2365:     my ($workbook) = @_;
                   2366:     my $format;
                   2367:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2368:                                                 bottom    => 1,
                   2369:                                                 align     => 'center');
                   2370:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2371:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2372:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2373:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2374:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2375:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2376:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2377:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2378:     return $format;
                   2379: }
                   2380: 
                   2381: ###############################################################
                   2382: ###############################################################
1.113     bowersj2 2383: 
                   2384: =pod
                   2385: 
1.648     raeburn  2386: =item * &create_workbook()
1.255     matthew  2387: 
                   2388: Create an Excel worksheet.  If it fails, output message on the
                   2389: request object and return undefs.
                   2390: 
                   2391: Inputs: Apache request object
                   2392: 
                   2393: Returns (undef) on failure, 
                   2394:     Excel worksheet object, scalar with filename, and formats 
                   2395:     from &Apache::loncommon::define_excel_formats on success
                   2396: 
                   2397: =cut
                   2398: 
                   2399: ###############################################################
                   2400: ###############################################################
                   2401: sub create_workbook {
                   2402:     my ($r) = @_;
                   2403:         #
                   2404:     # Create the excel spreadsheet
                   2405:     my $filename = '/prtspool/'.
1.258     albertel 2406:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2407:         time.'_'.rand(1000000000).'.xls';
                   2408:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2409:     if (! defined($workbook)) {
                   2410:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2411:         $r->print(
                   2412:             '<p class="LC_error">'
                   2413:            .&mt('Problems occurred in creating the new Excel file.')
                   2414:            .' '.&mt('This error has been logged.')
                   2415:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2416:            .'</p>'
                   2417:         );
1.255     matthew  2418:         return (undef);
                   2419:     }
                   2420:     #
1.1014    foxr     2421:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2422:     #
                   2423:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2424:     return ($workbook,$filename,$format);
                   2425: }
                   2426: 
                   2427: ###############################################################
                   2428: ###############################################################
                   2429: 
                   2430: =pod
                   2431: 
1.648     raeburn  2432: =item * &create_text_file()
1.113     bowersj2 2433: 
1.542     raeburn  2434: Create a file to write to and eventually make available to the user.
1.256     matthew  2435: If file creation fails, outputs an error message on the request object and 
                   2436: return undefs.
1.113     bowersj2 2437: 
1.256     matthew  2438: Inputs: Apache request object, and file suffix
1.113     bowersj2 2439: 
1.256     matthew  2440: Returns (undef) on failure, 
                   2441:     Filehandle and filename on success.
1.113     bowersj2 2442: 
                   2443: =cut
                   2444: 
1.256     matthew  2445: ###############################################################
                   2446: ###############################################################
                   2447: sub create_text_file {
                   2448:     my ($r,$suffix) = @_;
                   2449:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2450:     my $fh;
                   2451:     my $filename = '/prtspool/'.
1.258     albertel 2452:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2453:         time.'_'.rand(1000000000).'.'.$suffix;
                   2454:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2455:     if (! defined($fh)) {
                   2456:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2457:         $r->print(
                   2458:             '<p class="LC_error">'
                   2459:            .&mt('Problems occurred in creating the output file.')
                   2460:            .' '.&mt('This error has been logged.')
                   2461:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2462:            .'</p>'
                   2463:         );
1.113     bowersj2 2464:     }
1.256     matthew  2465:     return ($fh,$filename)
1.113     bowersj2 2466: }
                   2467: 
                   2468: 
1.256     matthew  2469: =pod 
1.113     bowersj2 2470: 
                   2471: =back
                   2472: 
                   2473: =cut
1.37      matthew  2474: 
                   2475: ###############################################################
1.33      matthew  2476: ##        Home server <option> list generating code          ##
                   2477: ###############################################################
1.35      matthew  2478: 
1.169     www      2479: # ------------------------------------------
                   2480: 
                   2481: sub domain_select {
1.1289    raeburn  2482:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2483:     my @possdoms;
                   2484:     if (ref($incdoms) eq 'ARRAY') {
                   2485:         @possdoms = @{$incdoms};
                   2486:     } else {
                   2487:         @possdoms = &Apache::lonnet::all_domains();
                   2488:     }
                   2489: 
1.169     www      2490:     my %domains=map { 
1.514     albertel 2491: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2492:     } @possdoms;
                   2493: 
                   2494:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2495:         foreach my $dom (@{$excdoms}) {
                   2496:             delete($domains{$dom});
                   2497:         }
                   2498:     }
                   2499: 
1.169     www      2500:     if ($multiple) {
                   2501: 	$domains{''}=&mt('Any domain');
1.550     albertel 2502: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2503: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2504:     } else {
1.550     albertel 2505: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2506: 	return &select_form($name,$value,\%domains);
1.169     www      2507:     }
                   2508: }
                   2509: 
1.282     albertel 2510: #-------------------------------------------
                   2511: 
                   2512: =pod
                   2513: 
1.519     raeburn  2514: =head1 Routines for form select boxes
                   2515: 
                   2516: =over 4
                   2517: 
1.648     raeburn  2518: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2519: 
                   2520: Returns a string containing a <select> element int multiple mode
                   2521: 
                   2522: 
                   2523: Args:
                   2524:   $name - name of the <select> element
1.506     raeburn  2525:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2526:   $size - number of rows long the select element is
1.283     albertel 2527:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2528:           (shown text should already have been &mt())
1.506     raeburn  2529:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2530: 
1.282     albertel 2531: =cut
                   2532: 
                   2533: #-------------------------------------------
1.169     www      2534: sub multiple_select_form {
1.284     albertel 2535:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2536:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2537:     my $output='';
1.191     matthew  2538:     if (! defined($size)) {
                   2539:         $size = 4;
1.283     albertel 2540:         if (scalar(keys(%$hash))<4) {
                   2541:             $size = scalar(keys(%$hash));
1.191     matthew  2542:         }
                   2543:     }
1.734     bisitz   2544:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2545:     my @order;
1.506     raeburn  2546:     if (ref($order) eq 'ARRAY')  {
                   2547:         @order = @{$order};
                   2548:     } else {
                   2549:         @order = sort(keys(%$hash));
1.501     banghart 2550:     }
                   2551:     if (exists($$hash{'select_form_order'})) {
                   2552:         @order = @{$$hash{'select_form_order'}};
                   2553:     }
                   2554:         
1.284     albertel 2555:     foreach my $key (@order) {
1.356     albertel 2556:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2557:         $output.='selected="selected" ' if ($selected{$key});
                   2558:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2559:     }
                   2560:     $output.="</select>\n";
                   2561:     return $output;
                   2562: }
                   2563: 
1.88      www      2564: #-------------------------------------------
                   2565: 
                   2566: =pod
                   2567: 
1.1254    raeburn  2568: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2569: 
                   2570: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2571: allow a user to select options from a ref to a hash containing:
                   2572: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2573: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2574: An optional arg -- $readonly -- if true will cause the select form
                   2575: to be disabled, e.g., for the case where an instructor has a section-
                   2576: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2577: 
1.88      www      2578: See lonrights.pm for an example invocation and use.
                   2579: 
                   2580: =cut
                   2581: 
                   2582: #-------------------------------------------
                   2583: sub select_form {
1.1228    raeburn  2584:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2585:     return unless (ref($hashref) eq 'HASH');
                   2586:     if ($onchange) {
                   2587:         $onchange = ' onchange="'.$onchange.'"';
                   2588:     }
1.1228    raeburn  2589:     my $disabled;
                   2590:     if ($readonly) {
                   2591:         $disabled = ' disabled="disabled"';
                   2592:     }
                   2593:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2594:     my @keys;
1.970     raeburn  2595:     if (exists($hashref->{'select_form_order'})) {
                   2596: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2597:     } else {
1.970     raeburn  2598: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2599:     }
1.356     albertel 2600:     foreach my $key (@keys) {
                   2601:         $selectform.=
                   2602: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2603:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2604:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2605:     }
                   2606:     $selectform.="</select>";
                   2607:     return $selectform;
                   2608: }
                   2609: 
1.475     www      2610: # For display filters
                   2611: 
                   2612: sub display_filter {
1.1074    raeburn  2613:     my ($context) = @_;
1.475     www      2614:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2615:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2616:     my $phraseinput = 'hidden';
                   2617:     my $includeinput = 'hidden';
                   2618:     my ($checked,$includetypestext);
                   2619:     if ($env{'form.displayfilter'} eq 'containing') {
                   2620:         $phraseinput = 'text'; 
                   2621:         if ($context eq 'parmslog') {
                   2622:             $includeinput = 'checkbox';
                   2623:             if ($env{'form.includetypes'}) {
                   2624:                 $checked = ' checked="checked"';
                   2625:             }
                   2626:             $includetypestext = &mt('Include parameter types');
                   2627:         }
                   2628:     } else {
                   2629:         $includetypestext = '&nbsp;';
                   2630:     }
                   2631:     my ($additional,$secondid,$thirdid);
                   2632:     if ($context eq 'parmslog') {
                   2633:         $additional = 
                   2634:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2635:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2636:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2637:             '</label>';
                   2638:         $secondid = 'includetypes';
                   2639:         $thirdid = 'includetypestext';
                   2640:     }
                   2641:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2642:                                                     '$secondid','$thirdid')";
                   2643:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2644: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2645: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2646: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2647:            &mt('Filter: [_1]',
1.477     www      2648: 	   &select_form($env{'form.displayfilter'},
                   2649: 			'displayfilter',
1.970     raeburn  2650: 			{'currentfolder' => 'Current folder/page',
1.477     www      2651: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2652: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2653: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2654:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2655:                          '" />'.$additional;
                   2656: }
                   2657: 
                   2658: sub display_filter_js {
                   2659:     my $includetext = &mt('Include parameter types');
                   2660:     return <<"ENDJS";
                   2661:   
                   2662: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2663:     var firstType = 'hidden';
                   2664:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2665:         firstType = 'text';
                   2666:     }
                   2667:     firstObject = document.getElementById(firstid);
                   2668:     if (typeof(firstObject) == 'object') {
                   2669:         if (firstObject.type != firstType) {
                   2670:             changeInputType(firstObject,firstType);
                   2671:         }
                   2672:     }
                   2673:     if (context == 'parmslog') {
                   2674:         var secondType = 'hidden';
                   2675:         if (firstType == 'text') {
                   2676:             secondType = 'checkbox';
                   2677:         }
                   2678:         secondObject = document.getElementById(secondid);  
                   2679:         if (typeof(secondObject) == 'object') {
                   2680:             if (secondObject.type != secondType) {
                   2681:                 changeInputType(secondObject,secondType);
                   2682:             }
                   2683:         }
                   2684:         var textItem = document.getElementById(thirdid);
                   2685:         var currtext = textItem.innerHTML;
                   2686:         var newtext;
                   2687:         if (firstType == 'text') {
                   2688:             newtext = '$includetext';
                   2689:         } else {
                   2690:             newtext = '&nbsp;';
                   2691:         }
                   2692:         if (currtext != newtext) {
                   2693:             textItem.innerHTML = newtext;
                   2694:         }
                   2695:     }
                   2696:     return;
                   2697: }
                   2698: 
                   2699: function changeInputType(oldObject,newType) {
                   2700:     var newObject = document.createElement('input');
                   2701:     newObject.type = newType;
                   2702:     if (oldObject.size) {
                   2703:         newObject.size = oldObject.size;
                   2704:     }
                   2705:     if (oldObject.value) {
                   2706:         newObject.value = oldObject.value;
                   2707:     }
                   2708:     if (oldObject.name) {
                   2709:         newObject.name = oldObject.name;
                   2710:     }
                   2711:     if (oldObject.id) {
                   2712:         newObject.id = oldObject.id;
                   2713:     }
                   2714:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2715:     return;
                   2716: }
                   2717: 
                   2718: ENDJS
1.475     www      2719: }
                   2720: 
1.167     www      2721: sub gradeleveldescription {
                   2722:     my $gradelevel=shift;
                   2723:     my %gradelevels=(0 => 'Not specified',
                   2724: 		     1 => 'Grade 1',
                   2725: 		     2 => 'Grade 2',
                   2726: 		     3 => 'Grade 3',
                   2727: 		     4 => 'Grade 4',
                   2728: 		     5 => 'Grade 5',
                   2729: 		     6 => 'Grade 6',
                   2730: 		     7 => 'Grade 7',
                   2731: 		     8 => 'Grade 8',
                   2732: 		     9 => 'Grade 9',
                   2733: 		     10 => 'Grade 10',
                   2734: 		     11 => 'Grade 11',
                   2735: 		     12 => 'Grade 12',
                   2736: 		     13 => 'Grade 13',
                   2737: 		     14 => '100 Level',
                   2738: 		     15 => '200 Level',
                   2739: 		     16 => '300 Level',
                   2740: 		     17 => '400 Level',
                   2741: 		     18 => 'Graduate Level');
                   2742:     return &mt($gradelevels{$gradelevel});
                   2743: }
                   2744: 
1.163     www      2745: sub select_level_form {
                   2746:     my ($deflevel,$name)=@_;
                   2747:     unless ($deflevel) { $deflevel=0; }
1.167     www      2748:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2749:     for (my $i=0; $i<=18; $i++) {
                   2750:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2751:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2752:                 ">".&gradeleveldescription($i)."</option>\n";
                   2753:     }
                   2754:     $selectform.="</select>";
                   2755:     return $selectform;
1.163     www      2756: }
1.167     www      2757: 
1.35      matthew  2758: #-------------------------------------------
                   2759: 
1.45      matthew  2760: =pod
                   2761: 
1.1256    raeburn  2762: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2763: 
                   2764: Returns a string containing a <select name='$name' size='1'> form to 
                   2765: allow a user to select the domain to preform an operation in.  
                   2766: See loncreateuser.pm for an example invocation and use.
                   2767: 
1.90      www      2768: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2769: selected");
                   2770: 
1.743     raeburn  2771: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2772: 
1.910     raeburn  2773: 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.
                   2774: 
1.1121    raeburn  2775: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2776: 
                   2777: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2778: 
1.1256    raeburn  2779: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2780: 
1.35      matthew  2781: =cut
                   2782: 
                   2783: #-------------------------------------------
1.34      matthew  2784: sub select_dom_form {
1.1256    raeburn  2785:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2786:     if ($onchange) {
1.874     raeburn  2787:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2788:     }
1.1256    raeburn  2789:     if ($disabled) {
                   2790:         $disabled = ' disabled="disabled"';
                   2791:     }
1.1121    raeburn  2792:     my (@domains,%exclude);
1.910     raeburn  2793:     if (ref($incdoms) eq 'ARRAY') {
                   2794:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2795:     } else {
                   2796:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2797:     }
1.90      www      2798:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2799:     if (ref($excdoms) eq 'ARRAY') {
                   2800:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2801:     }
1.1256    raeburn  2802:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2803:     foreach my $dom (@domains) {
1.1121    raeburn  2804:         next if ($exclude{$dom});
1.356     albertel 2805:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2806:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2807:         if ($showdomdesc) {
                   2808:             if ($dom ne '') {
                   2809:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2810:                 if ($domdesc ne '') {
                   2811:                     $selectdomain .= ' ('.$domdesc.')';
                   2812:                 }
                   2813:             } 
                   2814:         }
                   2815:         $selectdomain .= "</option>\n";
1.34      matthew  2816:     }
                   2817:     $selectdomain.="</select>";
                   2818:     return $selectdomain;
                   2819: }
                   2820: 
1.35      matthew  2821: #-------------------------------------------
                   2822: 
1.45      matthew  2823: =pod
                   2824: 
1.648     raeburn  2825: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2826: 
1.586     raeburn  2827: input: 4 arguments (two required, two optional) - 
                   2828:     $domain - domain of new user
                   2829:     $name - name of form element
                   2830:     $default - Value of 'default' causes a default item to be first 
                   2831:                             option, and selected by default. 
                   2832:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2833:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2834: output: returns 2 items: 
1.586     raeburn  2835: (a) form element which contains either:
                   2836:    (i) <select name="$name">
                   2837:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2838:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2839:        </select>
                   2840:        form item if there are multiple library servers in $domain, or
                   2841:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2842:        if there is only one library server in $domain.
                   2843: 
                   2844: (b) number of library servers found.
                   2845: 
                   2846: See loncreateuser.pm for example of use.
1.35      matthew  2847: 
                   2848: =cut
                   2849: 
                   2850: #-------------------------------------------
1.586     raeburn  2851: sub home_server_form_item {
                   2852:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2853:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2854:     my $result;
                   2855:     my $numlib = keys(%servers);
                   2856:     if ($numlib > 1) {
                   2857:         $result .= '<select name="'.$name.'" />'."\n";
                   2858:         if ($default) {
1.804     bisitz   2859:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2860:                        '</option>'."\n";
                   2861:         }
                   2862:         foreach my $hostid (sort(keys(%servers))) {
                   2863:             $result.= '<option value="'.$hostid.'">'.
                   2864: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2865:         }
                   2866:         $result .= '</select>'."\n";
                   2867:     } elsif ($numlib == 1) {
                   2868:         my $hostid;
                   2869:         foreach my $item (keys(%servers)) {
                   2870:             $hostid = $item;
                   2871:         }
                   2872:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2873:                    $hostid.'" />';
                   2874:                    if (!$hide) {
                   2875:                        $result .= $hostid.' '.$servers{$hostid};
                   2876:                    }
                   2877:                    $result .= "\n";
                   2878:     } elsif ($default) {
                   2879:         $result .= '<input type="hidden" name="'.$name.
                   2880:                    '" value="default" />';
                   2881:                    if (!$hide) {
                   2882:                        $result .= &mt('default');
                   2883:                    }
                   2884:                    $result .= "\n";
1.33      matthew  2885:     }
1.586     raeburn  2886:     return ($result,$numlib);
1.33      matthew  2887: }
1.112     bowersj2 2888: 
                   2889: =pod
                   2890: 
1.534     albertel 2891: =back 
                   2892: 
1.112     bowersj2 2893: =cut
1.87      matthew  2894: 
                   2895: ###############################################################
1.112     bowersj2 2896: ##                  Decoding User Agent                      ##
1.87      matthew  2897: ###############################################################
                   2898: 
                   2899: =pod
                   2900: 
1.112     bowersj2 2901: =head1 Decoding the User Agent
                   2902: 
                   2903: =over 4
                   2904: 
                   2905: =item * &decode_user_agent()
1.87      matthew  2906: 
                   2907: Inputs: $r
                   2908: 
                   2909: Outputs:
                   2910: 
                   2911: =over 4
                   2912: 
1.112     bowersj2 2913: =item * $httpbrowser
1.87      matthew  2914: 
1.112     bowersj2 2915: =item * $clientbrowser
1.87      matthew  2916: 
1.112     bowersj2 2917: =item * $clientversion
1.87      matthew  2918: 
1.112     bowersj2 2919: =item * $clientmathml
1.87      matthew  2920: 
1.112     bowersj2 2921: =item * $clientunicode
1.87      matthew  2922: 
1.112     bowersj2 2923: =item * $clientos
1.87      matthew  2924: 
1.1137    raeburn  2925: =item * $clientmobile
                   2926: 
1.1141    raeburn  2927: =item * $clientinfo
                   2928: 
1.1194    raeburn  2929: =item * $clientosversion
                   2930: 
1.87      matthew  2931: =back
                   2932: 
1.157     matthew  2933: =back 
                   2934: 
1.87      matthew  2935: =cut
                   2936: 
                   2937: ###############################################################
                   2938: ###############################################################
                   2939: sub decode_user_agent {
1.247     albertel 2940:     my ($r)=@_;
1.87      matthew  2941:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2942:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2943:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2944:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2945:     my $clientbrowser='unknown';
                   2946:     my $clientversion='0';
                   2947:     my $clientmathml='';
                   2948:     my $clientunicode='0';
1.1137    raeburn  2949:     my $clientmobile=0;
1.1194    raeburn  2950:     my $clientosversion='';
1.87      matthew  2951:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2952:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2953: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2954: 	    $clientbrowser=$bname;
                   2955:             $httpbrowser=~/$vreg/i;
                   2956: 	    $clientversion=$1;
                   2957:             $clientmathml=($clientversion>=$minv);
                   2958:             $clientunicode=($clientversion>=$univ);
                   2959: 	}
                   2960:     }
                   2961:     my $clientos='unknown';
1.1141    raeburn  2962:     my $clientinfo;
1.87      matthew  2963:     if (($httpbrowser=~/linux/i) ||
                   2964:         ($httpbrowser=~/unix/i) ||
                   2965:         ($httpbrowser=~/ux/i) ||
                   2966:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2967:     if (($httpbrowser=~/vax/i) ||
                   2968:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2969:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2970:     if (($httpbrowser=~/mac/i) ||
                   2971:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2972:     if ($httpbrowser=~/win/i) {
                   2973:         $clientos='win';
                   2974:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2975:             $clientosversion = $1;
                   2976:         }
                   2977:     }
1.87      matthew  2978:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2979:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2980:         $clientmobile=lc($1);
                   2981:     }
1.1141    raeburn  2982:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2983:         $clientinfo = 'firefox-'.$1;
                   2984:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2985:         $clientinfo = 'chromeframe-'.$1;
                   2986:     }
1.87      matthew  2987:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  2988:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2989:             $clientosversion);
1.87      matthew  2990: }
                   2991: 
1.32      matthew  2992: ###############################################################
                   2993: ##    Authentication changing form generation subroutines    ##
                   2994: ###############################################################
                   2995: ##
                   2996: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2997: ## hash, and have reasonable default values.
                   2998: ##
                   2999: ##    formname = the name given in the <form> tag.
1.35      matthew  3000: #-------------------------------------------
                   3001: 
1.45      matthew  3002: =pod
                   3003: 
1.112     bowersj2 3004: =head1 Authentication Routines
                   3005: 
                   3006: =over 4
                   3007: 
1.648     raeburn  3008: =item * &authform_xxxxxx()
1.35      matthew  3009: 
                   3010: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3011: handle some of the conveniences required for authentication forms.  
                   3012: This is not an optimal method, but it works.  
                   3013: 
                   3014: =over 4
                   3015: 
1.112     bowersj2 3016: =item * authform_header
1.35      matthew  3017: 
1.112     bowersj2 3018: =item * authform_authorwarning
1.35      matthew  3019: 
1.112     bowersj2 3020: =item * authform_nochange
1.35      matthew  3021: 
1.112     bowersj2 3022: =item * authform_kerberos
1.35      matthew  3023: 
1.112     bowersj2 3024: =item * authform_internal
1.35      matthew  3025: 
1.112     bowersj2 3026: =item * authform_filesystem
1.35      matthew  3027: 
                   3028: =back
                   3029: 
1.648     raeburn  3030: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3031: 
1.35      matthew  3032: =cut
                   3033: 
                   3034: #-------------------------------------------
1.32      matthew  3035: sub authform_header{  
                   3036:     my %in = (
                   3037:         formname => 'cu',
1.80      albertel 3038:         kerb_def_dom => '',
1.32      matthew  3039:         @_,
                   3040:     );
                   3041:     $in{'formname'} = 'document.' . $in{'formname'};
                   3042:     my $result='';
1.80      albertel 3043: 
                   3044: #---------------------------------------------- Code for upper case translation
                   3045:     my $Javascript_toUpperCase;
                   3046:     unless ($in{kerb_def_dom}) {
                   3047:         $Javascript_toUpperCase =<<"END";
                   3048:         switch (choice) {
                   3049:            case 'krb': currentform.elements[choicearg].value =
                   3050:                currentform.elements[choicearg].value.toUpperCase();
                   3051:                break;
                   3052:            default:
                   3053:         }
                   3054: END
                   3055:     } else {
                   3056:         $Javascript_toUpperCase = "";
                   3057:     }
                   3058: 
1.165     raeburn  3059:     my $radioval = "'nochange'";
1.591     raeburn  3060:     if (defined($in{'curr_authtype'})) {
                   3061:         if ($in{'curr_authtype'} ne '') {
                   3062:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3063:         }
1.174     matthew  3064:     }
1.165     raeburn  3065:     my $argfield = 'null';
1.591     raeburn  3066:     if (defined($in{'mode'})) {
1.165     raeburn  3067:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3068:             if (defined($in{'curr_autharg'})) {
                   3069:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3070:                     $argfield = "'$in{'curr_autharg'}'";
                   3071:                 }
                   3072:             }
                   3073:         }
                   3074:     }
                   3075: 
1.32      matthew  3076:     $result.=<<"END";
                   3077: var current = new Object();
1.165     raeburn  3078: current.radiovalue = $radioval;
                   3079: current.argfield = $argfield;
1.32      matthew  3080: 
                   3081: function changed_radio(choice,currentform) {
                   3082:     var choicearg = choice + 'arg';
                   3083:     // If a radio button in changed, we need to change the argfield
                   3084:     if (current.radiovalue != choice) {
                   3085:         current.radiovalue = choice;
                   3086:         if (current.argfield != null) {
                   3087:             currentform.elements[current.argfield].value = '';
                   3088:         }
                   3089:         if (choice == 'nochange') {
                   3090:             current.argfield = null;
                   3091:         } else {
                   3092:             current.argfield = choicearg;
                   3093:             switch(choice) {
                   3094:                 case 'krb': 
                   3095:                     currentform.elements[current.argfield].value = 
                   3096:                         "$in{'kerb_def_dom'}";
                   3097:                 break;
                   3098:               default:
                   3099:                 break;
                   3100:             }
                   3101:         }
                   3102:     }
                   3103:     return;
                   3104: }
1.22      www      3105: 
1.32      matthew  3106: function changed_text(choice,currentform) {
                   3107:     var choicearg = choice + 'arg';
                   3108:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3109:         $Javascript_toUpperCase
1.32      matthew  3110:         // clear old field
                   3111:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3112:             currentform.elements[current.argfield].value = '';
                   3113:         }
                   3114:         current.argfield = choicearg;
                   3115:     }
                   3116:     set_auth_radio_buttons(choice,currentform);
                   3117:     return;
1.20      www      3118: }
1.32      matthew  3119: 
                   3120: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3121:     var numauthchoices = currentform.login.length;
                   3122:     if (typeof numauthchoices  == "undefined") {
                   3123:         return;
                   3124:     } 
1.32      matthew  3125:     var i=0;
1.986     raeburn  3126:     while (i < numauthchoices) {
1.32      matthew  3127:         if (currentform.login[i].value == newvalue) { break; }
                   3128:         i++;
                   3129:     }
1.986     raeburn  3130:     if (i == numauthchoices) {
1.32      matthew  3131:         return;
                   3132:     }
                   3133:     current.radiovalue = newvalue;
                   3134:     currentform.login[i].checked = true;
                   3135:     return;
                   3136: }
                   3137: END
                   3138:     return $result;
                   3139: }
                   3140: 
1.1106    raeburn  3141: sub authform_authorwarning {
1.32      matthew  3142:     my $result='';
1.144     matthew  3143:     $result='<i>'.
                   3144:         &mt('As a general rule, only authors or co-authors should be '.
                   3145:             'filesystem authenticated '.
                   3146:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3147:     return $result;
                   3148: }
                   3149: 
1.1106    raeburn  3150: sub authform_nochange {
1.32      matthew  3151:     my %in = (
                   3152:               formname => 'document.cu',
                   3153:               kerb_def_dom => 'MSU.EDU',
                   3154:               @_,
                   3155:           );
1.1106    raeburn  3156:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3157:     my $result;
1.1104    raeburn  3158:     if (!$authnum) {
1.1105    raeburn  3159:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3160:     } else {
                   3161:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3162:                   '<input type="radio" name="login" value="nochange" '.
                   3163:                   'checked="checked" onclick="'.
1.281     albertel 3164:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3165: 	    '</label>';
1.586     raeburn  3166:     }
1.32      matthew  3167:     return $result;
                   3168: }
                   3169: 
1.591     raeburn  3170: sub authform_kerberos {
1.32      matthew  3171:     my %in = (
                   3172:               formname => 'document.cu',
                   3173:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3174:               kerb_def_auth => 'krb4',
1.32      matthew  3175:               @_,
                   3176:               );
1.586     raeburn  3177:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3178:         $autharg,$jscall,$disabled);
1.1106    raeburn  3179:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3180:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3181:        $check5 = ' checked="checked"';
1.80      albertel 3182:     } else {
1.772     bisitz   3183:        $check4 = ' checked="checked"';
1.80      albertel 3184:     }
1.1259    raeburn  3185:     if ($in{'readonly'}) {
                   3186:         $disabled = ' disabled="disabled"';
                   3187:     }
1.165     raeburn  3188:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3189:     if (defined($in{'curr_authtype'})) {
                   3190:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3191:             $krbcheck = ' checked="checked"';
1.623     raeburn  3192:             if (defined($in{'mode'})) {
                   3193:                 if ($in{'mode'} eq 'modifyuser') {
                   3194:                     $krbcheck = '';
                   3195:                 }
                   3196:             }
1.591     raeburn  3197:             if (defined($in{'curr_kerb_ver'})) {
                   3198:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3199:                     $check5 = ' checked="checked"';
1.591     raeburn  3200:                     $check4 = '';
                   3201:                 } else {
1.772     bisitz   3202:                     $check4 = ' checked="checked"';
1.591     raeburn  3203:                     $check5 = '';
                   3204:                 }
1.586     raeburn  3205:             }
1.591     raeburn  3206:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3207:                 $krbarg = $in{'curr_autharg'};
                   3208:             }
1.586     raeburn  3209:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3210:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3211:                     $result = 
                   3212:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3213:         $in{'curr_autharg'},$krbver);
                   3214:                 } else {
                   3215:                     $result =
                   3216:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3217:                 }
                   3218:                 return $result; 
                   3219:             }
                   3220:         }
                   3221:     } else {
                   3222:         if ($authnum == 1) {
1.784     bisitz   3223:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3224:         }
                   3225:     }
1.586     raeburn  3226:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3227:         return;
1.587     raeburn  3228:     } elsif ($authtype eq '') {
1.591     raeburn  3229:         if (defined($in{'mode'})) {
1.587     raeburn  3230:             if ($in{'mode'} eq 'modifycourse') {
                   3231:                 if ($authnum == 1) {
1.1259    raeburn  3232:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3233:                 }
                   3234:             }
                   3235:         }
1.586     raeburn  3236:     }
                   3237:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3238:     if ($authtype eq '') {
                   3239:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3240:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3241:                     $krbcheck.$disabled.' />';
1.586     raeburn  3242:     }
                   3243:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3244:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3245:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3246:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3247:          $in{'curr_authtype'} eq 'krb4')) {
                   3248:         $result .= &mt
1.144     matthew  3249:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3250:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3251:          '<label>'.$authtype,
1.281     albertel 3252:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3253:              'value="'.$krbarg.'" '.
1.1259    raeburn  3254:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3255:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3256:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3257: 	 '</label>');
1.586     raeburn  3258:     } elsif ($can_assign{'krb4'}) {
                   3259:         $result .= &mt
                   3260:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3261:          '[_3] Version 4 [_4]',
                   3262:          '<label>'.$authtype,
                   3263:          '</label><input type="text" size="10" name="krbarg" '.
                   3264:              'value="'.$krbarg.'" '.
1.1259    raeburn  3265:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3266:          '<label><input type="hidden" name="krbver" value="4" />',
                   3267:          '</label>');
                   3268:     } elsif ($can_assign{'krb5'}) {
                   3269:         $result .= &mt
                   3270:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3271:          '[_3] Version 5 [_4]',
                   3272:          '<label>'.$authtype,
                   3273:          '</label><input type="text" size="10" name="krbarg" '.
                   3274:              'value="'.$krbarg.'" '.
1.1259    raeburn  3275:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3276:          '<label><input type="hidden" name="krbver" value="5" />',
                   3277:          '</label>');
                   3278:     }
1.32      matthew  3279:     return $result;
                   3280: }
                   3281: 
1.1106    raeburn  3282: sub authform_internal {
1.586     raeburn  3283:     my %in = (
1.32      matthew  3284:                 formname => 'document.cu',
                   3285:                 kerb_def_dom => 'MSU.EDU',
                   3286:                 @_,
                   3287:                 );
1.1259    raeburn  3288:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3289:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3290:     if ($in{'readonly'}) {
                   3291:         $disabled = ' disabled="disabled"';
                   3292:     }
1.591     raeburn  3293:     if (defined($in{'curr_authtype'})) {
                   3294:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3295:             if ($can_assign{'int'}) {
1.772     bisitz   3296:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3297:                 if (defined($in{'mode'})) {
                   3298:                     if ($in{'mode'} eq 'modifyuser') {
                   3299:                         $intcheck = '';
                   3300:                     }
                   3301:                 }
1.591     raeburn  3302:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3303:                     $intarg = $in{'curr_autharg'};
                   3304:                 }
                   3305:             } else {
                   3306:                 $result = &mt('Currently internally authenticated.');
                   3307:                 return $result;
1.165     raeburn  3308:             }
                   3309:         }
1.586     raeburn  3310:     } else {
                   3311:         if ($authnum == 1) {
1.784     bisitz   3312:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3313:         }
                   3314:     }
                   3315:     if (!$can_assign{'int'}) {
                   3316:         return;
1.587     raeburn  3317:     } elsif ($authtype eq '') {
1.591     raeburn  3318:         if (defined($in{'mode'})) {
1.587     raeburn  3319:             if ($in{'mode'} eq 'modifycourse') {
                   3320:                 if ($authnum == 1) {
1.1259    raeburn  3321:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3322:                 }
                   3323:             }
                   3324:         }
1.165     raeburn  3325:     }
1.586     raeburn  3326:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3327:     if ($authtype eq '') {
                   3328:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3329:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3330:     }
1.605     bisitz   3331:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3332:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3333:     $result = &mt
1.144     matthew  3334:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3335:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3336:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3337:     return $result;
                   3338: }
                   3339: 
1.1104    raeburn  3340: sub authform_local {
1.32      matthew  3341:     my %in = (
                   3342:               formname => 'document.cu',
                   3343:               kerb_def_dom => 'MSU.EDU',
                   3344:               @_,
                   3345:               );
1.1259    raeburn  3346:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3347:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3348:     if ($in{'readonly'}) {
                   3349:         $disabled = ' disabled="disabled"';
                   3350:     } 
1.591     raeburn  3351:     if (defined($in{'curr_authtype'})) {
                   3352:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3353:             if ($can_assign{'loc'}) {
1.772     bisitz   3354:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3355:                 if (defined($in{'mode'})) {
                   3356:                     if ($in{'mode'} eq 'modifyuser') {
                   3357:                         $loccheck = '';
                   3358:                     }
                   3359:                 }
1.591     raeburn  3360:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3361:                     $locarg = $in{'curr_autharg'};
                   3362:                 }
                   3363:             } else {
                   3364:                 $result = &mt('Currently using local (institutional) authentication.');
                   3365:                 return $result;
1.165     raeburn  3366:             }
                   3367:         }
1.586     raeburn  3368:     } else {
                   3369:         if ($authnum == 1) {
1.784     bisitz   3370:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3371:         }
                   3372:     }
                   3373:     if (!$can_assign{'loc'}) {
                   3374:         return;
1.587     raeburn  3375:     } elsif ($authtype eq '') {
1.591     raeburn  3376:         if (defined($in{'mode'})) {
1.587     raeburn  3377:             if ($in{'mode'} eq 'modifycourse') {
                   3378:                 if ($authnum == 1) {
1.1259    raeburn  3379:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3380:                 }
                   3381:             }
                   3382:         }
1.165     raeburn  3383:     }
1.586     raeburn  3384:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3385:     if ($authtype eq '') {
                   3386:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3387:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3388:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3389:     }
                   3390:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3391:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3392:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3393:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3394:     return $result;
                   3395: }
                   3396: 
1.1106    raeburn  3397: sub authform_filesystem {
1.32      matthew  3398:     my %in = (
                   3399:               formname => 'document.cu',
                   3400:               kerb_def_dom => 'MSU.EDU',
                   3401:               @_,
                   3402:               );
1.1259    raeburn  3403:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3404:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3405:     if ($in{'readonly'}) {
                   3406:         $disabled = ' disabled="disabled"';
                   3407:     }
1.591     raeburn  3408:     if (defined($in{'curr_authtype'})) {
                   3409:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3410:             if ($can_assign{'fsys'}) {
1.772     bisitz   3411:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3412:                 if (defined($in{'mode'})) {
                   3413:                     if ($in{'mode'} eq 'modifyuser') {
                   3414:                         $fsyscheck = '';
                   3415:                     }
                   3416:                 }
1.586     raeburn  3417:             } else {
                   3418:                 $result = &mt('Currently Filesystem Authenticated.');
                   3419:                 return $result;
1.1259    raeburn  3420:             }
1.586     raeburn  3421:         }
                   3422:     } else {
                   3423:         if ($authnum == 1) {
1.784     bisitz   3424:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3425:         }
                   3426:     }
                   3427:     if (!$can_assign{'fsys'}) {
                   3428:         return;
1.587     raeburn  3429:     } elsif ($authtype eq '') {
1.591     raeburn  3430:         if (defined($in{'mode'})) {
1.587     raeburn  3431:             if ($in{'mode'} eq 'modifycourse') {
                   3432:                 if ($authnum == 1) {
1.1259    raeburn  3433:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3434:                 }
                   3435:             }
                   3436:         }
1.586     raeburn  3437:     }
                   3438:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3439:     if ($authtype eq '') {
                   3440:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3441:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3442:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3443:     }
                   3444:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3445:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3446:     $result = &mt
1.144     matthew  3447:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3448:          '<label><input type="radio" name="login" value="fsys" '.
1.1259    raeburn  3449:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3450:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1259    raeburn  3451:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3452:     return $result;
                   3453: }
                   3454: 
1.586     raeburn  3455: sub get_assignable_auth {
                   3456:     my ($dom) = @_;
                   3457:     if ($dom eq '') {
                   3458:         $dom = $env{'request.role.domain'};
                   3459:     }
                   3460:     my %can_assign = (
                   3461:                           krb4 => 1,
                   3462:                           krb5 => 1,
                   3463:                           int  => 1,
                   3464:                           loc  => 1,
                   3465:                      );
                   3466:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3467:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3468:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3469:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3470:             my $context;
                   3471:             if ($env{'request.role'} =~ /^au/) {
                   3472:                 $context = 'author';
1.1259    raeburn  3473:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3474:                 $context = 'domain';
                   3475:             } elsif ($env{'request.course.id'}) {
                   3476:                 $context = 'course';
                   3477:             }
                   3478:             if ($context) {
                   3479:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3480:                    %can_assign = %{$authhash->{$context}}; 
                   3481:                 }
                   3482:             }
                   3483:         }
                   3484:     }
                   3485:     my $authnum = 0;
                   3486:     foreach my $key (keys(%can_assign)) {
                   3487:         if ($can_assign{$key}) {
                   3488:             $authnum ++;
                   3489:         }
                   3490:     }
                   3491:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3492:         $authnum --;
                   3493:     }
                   3494:     return ($authnum,%can_assign);
                   3495: }
                   3496: 
1.80      albertel 3497: ###############################################################
                   3498: ##    Get Kerberos Defaults for Domain                 ##
                   3499: ###############################################################
                   3500: ##
                   3501: ## Returns default kerberos version and an associated argument
                   3502: ## as listed in file domain.tab. If not listed, provides
                   3503: ## appropriate default domain and kerberos version.
                   3504: ##
                   3505: #-------------------------------------------
                   3506: 
                   3507: =pod
                   3508: 
1.648     raeburn  3509: =item * &get_kerberos_defaults()
1.80      albertel 3510: 
                   3511: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3512: version and domain. If not found, it defaults to version 4 and the 
                   3513: domain of the server.
1.80      albertel 3514: 
1.648     raeburn  3515: =over 4
                   3516: 
1.80      albertel 3517: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3518: 
1.648     raeburn  3519: =back
                   3520: 
                   3521: =back
                   3522: 
1.80      albertel 3523: =cut
                   3524: 
                   3525: #-------------------------------------------
                   3526: sub get_kerberos_defaults {
                   3527:     my $domain=shift;
1.641     raeburn  3528:     my ($krbdef,$krbdefdom);
                   3529:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3530:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3531:         $krbdef = $domdefaults{'auth_def'};
                   3532:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3533:     } else {
1.80      albertel 3534:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3535:         my $krbdefdom=$1;
                   3536:         $krbdefdom=~tr/a-z/A-Z/;
                   3537:         $krbdef = "krb4";
                   3538:     }
                   3539:     return ($krbdef,$krbdefdom);
                   3540: }
1.112     bowersj2 3541: 
1.32      matthew  3542: 
1.46      matthew  3543: ###############################################################
                   3544: ##                Thesaurus Functions                        ##
                   3545: ###############################################################
1.20      www      3546: 
1.46      matthew  3547: =pod
1.20      www      3548: 
1.112     bowersj2 3549: =head1 Thesaurus Functions
                   3550: 
                   3551: =over 4
                   3552: 
1.648     raeburn  3553: =item * &initialize_keywords()
1.46      matthew  3554: 
                   3555: Initializes the package variable %Keywords if it is empty.  Uses the
                   3556: package variable $thesaurus_db_file.
                   3557: 
                   3558: =cut
                   3559: 
                   3560: ###################################################
                   3561: 
                   3562: sub initialize_keywords {
                   3563:     return 1 if (scalar keys(%Keywords));
                   3564:     # If we are here, %Keywords is empty, so fill it up
                   3565:     #   Make sure the file we need exists...
                   3566:     if (! -e $thesaurus_db_file) {
                   3567:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3568:                                  " failed because it does not exist");
                   3569:         return 0;
                   3570:     }
                   3571:     #   Set up the hash as a database
                   3572:     my %thesaurus_db;
                   3573:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3574:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3575:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3576:                                  $thesaurus_db_file);
                   3577:         return 0;
                   3578:     } 
                   3579:     #  Get the average number of appearances of a word.
                   3580:     my $avecount = $thesaurus_db{'average.count'};
                   3581:     #  Put keywords (those that appear > average) into %Keywords
                   3582:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3583:         my ($count,undef) = split /:/,$data;
                   3584:         $Keywords{$word}++ if ($count > $avecount);
                   3585:     }
                   3586:     untie %thesaurus_db;
                   3587:     # Remove special values from %Keywords.
1.356     albertel 3588:     foreach my $value ('total.count','average.count') {
                   3589:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3590:   }
1.46      matthew  3591:     return 1;
                   3592: }
                   3593: 
                   3594: ###################################################
                   3595: 
                   3596: =pod
                   3597: 
1.648     raeburn  3598: =item * &keyword($word)
1.46      matthew  3599: 
                   3600: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3601: than the average number of times in the thesaurus database.  Calls 
                   3602: &initialize_keywords
                   3603: 
                   3604: =cut
                   3605: 
                   3606: ###################################################
1.20      www      3607: 
                   3608: sub keyword {
1.46      matthew  3609:     return if (!&initialize_keywords());
                   3610:     my $word=lc(shift());
                   3611:     $word=~s/\W//g;
                   3612:     return exists($Keywords{$word});
1.20      www      3613: }
1.46      matthew  3614: 
                   3615: ###############################################################
                   3616: 
                   3617: =pod 
1.20      www      3618: 
1.648     raeburn  3619: =item * &get_related_words()
1.46      matthew  3620: 
1.160     matthew  3621: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3622: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3623: will be returned.  The order of the words returned is determined by the
                   3624: database which holds them.
                   3625: 
                   3626: Uses global $thesaurus_db_file.
                   3627: 
1.1057    foxr     3628: 
1.46      matthew  3629: =cut
                   3630: 
                   3631: ###############################################################
                   3632: sub get_related_words {
                   3633:     my $keyword = shift;
                   3634:     my %thesaurus_db;
                   3635:     if (! -e $thesaurus_db_file) {
                   3636:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3637:                                  "failed because the file does not exist");
                   3638:         return ();
                   3639:     }
                   3640:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3641:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3642:         return ();
                   3643:     } 
                   3644:     my @Words=();
1.429     www      3645:     my $count=0;
1.46      matthew  3646:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3647: 	# The first element is the number of times
                   3648: 	# the word appears.  We do not need it now.
1.429     www      3649: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3650: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3651: 	my $threshold=$mostfrequentcount/10;
                   3652:         foreach my $possibleword (@RelatedWords) {
                   3653:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3654:             if ($wordcount>$threshold) {
                   3655: 		push(@Words,$word);
                   3656:                 $count++;
                   3657:                 if ($count>10) { last; }
                   3658: 	    }
1.20      www      3659:         }
                   3660:     }
1.46      matthew  3661:     untie %thesaurus_db;
                   3662:     return @Words;
1.14      harris41 3663: }
1.1090    foxr     3664: ###############################################################
                   3665: #
                   3666: #  Spell checking
                   3667: #
                   3668: 
                   3669: =pod
                   3670: 
1.1142    raeburn  3671: =back
                   3672: 
1.1090    foxr     3673: =head1 Spell checking
                   3674: 
                   3675: =over 4
                   3676: 
                   3677: =item * &check_spelling($wordlist $language)
                   3678: 
                   3679: Takes a string containing words and feeds it to an external
                   3680: spellcheck program via a pipeline. Returns a string containing
                   3681: them mis-spelled words.
                   3682: 
                   3683: Parameters:
                   3684: 
                   3685: =over 4
                   3686: 
                   3687: =item - $wordlist
                   3688: 
                   3689: String that will be fed into the spellcheck program.
                   3690: 
                   3691: =item - $language
                   3692: 
                   3693: Language string that specifies the language for which the spell
                   3694: check will be performed.
                   3695: 
                   3696: =back
                   3697: 
                   3698: =back
                   3699: 
                   3700: Note: This sub assumes that aspell is installed.
                   3701: 
                   3702: 
                   3703: =cut
                   3704: 
1.46      matthew  3705: 
1.1090    foxr     3706: sub check_spelling {
                   3707:     my ($wordlist, $language) = @_;
1.1091    foxr     3708:     my @misspellings;
                   3709:     
                   3710:     # Generate the speller and set the langauge.
                   3711:     # if explicitly selected:
1.1090    foxr     3712: 
1.1091    foxr     3713:     my $speller = Text::Aspell->new;
1.1090    foxr     3714:     if ($language) {
1.1091    foxr     3715: 	$speller->set_option('lang', $language);
1.1090    foxr     3716:     }
                   3717: 
1.1091    foxr     3718:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3719: 
1.1091    foxr     3720:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3721: 
1.1091    foxr     3722:     foreach my $word (@words) {
                   3723: 	if(! $speller->check($word)) {
                   3724: 	    push(@misspellings, $word);
1.1090    foxr     3725: 	}
                   3726:     }
1.1091    foxr     3727:     return join(' ', @misspellings);
                   3728:     
1.1090    foxr     3729: }
                   3730: 
1.61      www      3731: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3732: =pod
                   3733: 
1.112     bowersj2 3734: =head1 User Name Functions
                   3735: 
                   3736: =over 4
                   3737: 
1.648     raeburn  3738: =item * &plainname($uname,$udom,$first)
1.81      albertel 3739: 
1.112     bowersj2 3740: Takes a users logon name and returns it as a string in
1.226     albertel 3741: "first middle last generation" form 
                   3742: if $first is set to 'lastname' then it returns it as
                   3743: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3744: 
                   3745: =cut
1.61      www      3746: 
1.295     www      3747: 
1.81      albertel 3748: ###############################################################
1.61      www      3749: sub plainname {
1.226     albertel 3750:     my ($uname,$udom,$first)=@_;
1.537     albertel 3751:     return if (!defined($uname) || !defined($udom));
1.295     www      3752:     my %names=&getnames($uname,$udom);
1.226     albertel 3753:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3754: 					  $names{'middlename'},
                   3755: 					  $names{'lastname'},
                   3756: 					  $names{'generation'},$first);
                   3757:     $name=~s/^\s+//;
1.62      www      3758:     $name=~s/\s+$//;
                   3759:     $name=~s/\s+/ /g;
1.353     albertel 3760:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3761:     return $name;
1.61      www      3762: }
1.66      www      3763: 
                   3764: # -------------------------------------------------------------------- Nickname
1.81      albertel 3765: =pod
                   3766: 
1.648     raeburn  3767: =item * &nickname($uname,$udom)
1.81      albertel 3768: 
                   3769: Gets a users name and returns it as a string as
                   3770: 
                   3771: "&quot;nickname&quot;"
1.66      www      3772: 
1.81      albertel 3773: if the user has a nickname or
                   3774: 
                   3775: "first middle last generation"
                   3776: 
                   3777: if the user does not
                   3778: 
                   3779: =cut
1.66      www      3780: 
                   3781: sub nickname {
                   3782:     my ($uname,$udom)=@_;
1.537     albertel 3783:     return if (!defined($uname) || !defined($udom));
1.295     www      3784:     my %names=&getnames($uname,$udom);
1.68      albertel 3785:     my $name=$names{'nickname'};
1.66      www      3786:     if ($name) {
                   3787:        $name='&quot;'.$name.'&quot;'; 
                   3788:     } else {
                   3789:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3790: 	     $names{'lastname'}.' '.$names{'generation'};
                   3791:        $name=~s/\s+$//;
                   3792:        $name=~s/\s+/ /g;
                   3793:     }
                   3794:     return $name;
                   3795: }
                   3796: 
1.295     www      3797: sub getnames {
                   3798:     my ($uname,$udom)=@_;
1.537     albertel 3799:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3800:     if ($udom eq 'public' && $uname eq 'public') {
                   3801: 	return ('lastname' => &mt('Public'));
                   3802:     }
1.295     www      3803:     my $id=$uname.':'.$udom;
                   3804:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3805:     if ($cached) {
                   3806: 	return %{$names};
                   3807:     } else {
                   3808: 	my %loadnames=&Apache::lonnet::get('environment',
                   3809:                     ['firstname','middlename','lastname','generation','nickname'],
                   3810: 					 $udom,$uname);
                   3811: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3812: 	return %loadnames;
                   3813:     }
                   3814: }
1.61      www      3815: 
1.542     raeburn  3816: # -------------------------------------------------------------------- getemails
1.648     raeburn  3817: 
1.542     raeburn  3818: =pod
                   3819: 
1.648     raeburn  3820: =item * &getemails($uname,$udom)
1.542     raeburn  3821: 
                   3822: Gets a user's email information and returns it as a hash with keys:
                   3823: notification, critnotification, permanentemail
                   3824: 
                   3825: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3826: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3827:  
1.648     raeburn  3828: 
1.542     raeburn  3829: =cut
                   3830: 
1.648     raeburn  3831: 
1.466     albertel 3832: sub getemails {
                   3833:     my ($uname,$udom)=@_;
                   3834:     if ($udom eq 'public' && $uname eq 'public') {
                   3835: 	return;
                   3836:     }
1.467     www      3837:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3838:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3839:     my $id=$uname.':'.$udom;
                   3840:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3841:     if ($cached) {
                   3842: 	return %{$names};
                   3843:     } else {
                   3844: 	my %loadnames=&Apache::lonnet::get('environment',
                   3845:                     			   ['notification','critnotification',
                   3846: 					    'permanentemail'],
                   3847: 					   $udom,$uname);
                   3848: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3849: 	return %loadnames;
                   3850:     }
                   3851: }
                   3852: 
1.551     albertel 3853: sub flush_email_cache {
                   3854:     my ($uname,$udom)=@_;
                   3855:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3856:     if (!$uname) { $uname=$env{'user.name'};   }
                   3857:     return if ($udom eq 'public' && $uname eq 'public');
                   3858:     my $id=$uname.':'.$udom;
                   3859:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3860: }
                   3861: 
1.728     raeburn  3862: # -------------------------------------------------------------------- getlangs
                   3863: 
                   3864: =pod
                   3865: 
                   3866: =item * &getlangs($uname,$udom)
                   3867: 
                   3868: Gets a user's language preference and returns it as a hash with key:
                   3869: language.
                   3870: 
                   3871: =cut
                   3872: 
                   3873: 
                   3874: sub getlangs {
                   3875:     my ($uname,$udom) = @_;
                   3876:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3877:     if (!$uname) { $uname=$env{'user.name'};   }
                   3878:     my $id=$uname.':'.$udom;
                   3879:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3880:     if ($cached) {
                   3881:         return %{$langs};
                   3882:     } else {
                   3883:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3884:                                            $udom,$uname);
                   3885:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3886:         return %loadlangs;
                   3887:     }
                   3888: }
                   3889: 
                   3890: sub flush_langs_cache {
                   3891:     my ($uname,$udom)=@_;
                   3892:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3893:     if (!$uname) { $uname=$env{'user.name'};   }
                   3894:     return if ($udom eq 'public' && $uname eq 'public');
                   3895:     my $id=$uname.':'.$udom;
                   3896:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3897: }
                   3898: 
1.61      www      3899: # ------------------------------------------------------------------ Screenname
1.81      albertel 3900: 
                   3901: =pod
                   3902: 
1.648     raeburn  3903: =item * &screenname($uname,$udom)
1.81      albertel 3904: 
                   3905: Gets a users screenname and returns it as a string
                   3906: 
                   3907: =cut
1.61      www      3908: 
                   3909: sub screenname {
                   3910:     my ($uname,$udom)=@_;
1.258     albertel 3911:     if ($uname eq $env{'user.name'} &&
                   3912: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3913:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3914:     return $names{'screenname'};
1.62      www      3915: }
                   3916: 
1.212     albertel 3917: 
1.802     bisitz   3918: # ------------------------------------------------------------- Confirm Wrapper
                   3919: =pod
                   3920: 
1.1142    raeburn  3921: =item * &confirmwrapper($message)
1.802     bisitz   3922: 
                   3923: Wrap messages about completion of operation in box
                   3924: 
                   3925: =cut
                   3926: 
                   3927: sub confirmwrapper {
                   3928:     my ($message)=@_;
                   3929:     if ($message) {
                   3930:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3931:                .$message."\n"
                   3932:                .'</div>'."\n";
                   3933:     } else {
                   3934:         return $message;
                   3935:     }
                   3936: }
                   3937: 
1.62      www      3938: # ------------------------------------------------------------- Message Wrapper
                   3939: 
                   3940: sub messagewrapper {
1.369     www      3941:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3942:     return 
1.441     albertel 3943:         '<a href="/adm/email?compose=individual&amp;'.
                   3944:         'recname='.$username.'&amp;recdom='.$domain.
                   3945: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3946:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3947: }
1.802     bisitz   3948: 
1.74      www      3949: # --------------------------------------------------------------- Notes Wrapper
                   3950: 
                   3951: sub noteswrapper {
                   3952:     my ($link,$un,$do)=@_;
                   3953:     return 
1.896     amueller 3954: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3955: }
1.802     bisitz   3956: 
1.62      www      3957: # ------------------------------------------------------------- Aboutme Wrapper
                   3958: 
                   3959: sub aboutmewrapper {
1.1070    raeburn  3960:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3961:     if (!defined($username)  && !defined($domain)) {
                   3962:         return;
                   3963:     }
1.1096    raeburn  3964:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3965: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3966: }
                   3967: 
                   3968: # ------------------------------------------------------------ Syllabus Wrapper
                   3969: 
                   3970: sub syllabuswrapper {
1.707     bisitz   3971:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3972:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3973: }
1.14      harris41 3974: 
1.802     bisitz   3975: # -----------------------------------------------------------------------------
                   3976: 
1.208     matthew  3977: sub track_student_link {
1.887     raeburn  3978:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3979:     my $link ="/adm/trackstudent?";
1.208     matthew  3980:     my $title = 'View recent activity';
                   3981:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3982:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3983:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3984:         $title .= ' of this student';
1.268     albertel 3985:     } 
1.208     matthew  3986:     if (defined($target) && $target !~ /^\s*$/) {
                   3987:         $target = qq{target="$target"};
                   3988:     } else {
                   3989:         $target = '';
                   3990:     }
1.268     albertel 3991:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3992:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3993:     $title = &mt($title);
                   3994:     $linktext = &mt($linktext);
1.448     albertel 3995:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3996: 	&help_open_topic('View_recent_activity');
1.208     matthew  3997: }
                   3998: 
1.781     raeburn  3999: sub slot_reservations_link {
                   4000:     my ($linktext,$sname,$sdom,$target) = @_;
                   4001:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4002:     my $title = 'View slot reservation history';
                   4003:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4004:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4005:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4006:         $title .= ' of this student';
                   4007:     }
                   4008:     if (defined($target) && $target !~ /^\s*$/) {
                   4009:         $target = qq{target="$target"};
                   4010:     } else {
                   4011:         $target = '';
                   4012:     }
                   4013:     $title = &mt($title);
                   4014:     $linktext = &mt($linktext);
                   4015:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4016: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4017: 
                   4018: }
                   4019: 
1.508     www      4020: # ===================================================== Display a student photo
                   4021: 
                   4022: 
1.509     albertel 4023: sub student_image_tag {
1.508     www      4024:     my ($domain,$user)=@_;
                   4025:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4026:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4027: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4028:     } else {
                   4029: 	return '';
                   4030:     }
                   4031: }
                   4032: 
1.112     bowersj2 4033: =pod
                   4034: 
                   4035: =back
                   4036: 
                   4037: =head1 Access .tab File Data
                   4038: 
                   4039: =over 4
                   4040: 
1.648     raeburn  4041: =item * &languageids() 
1.112     bowersj2 4042: 
                   4043: returns list of all language ids
                   4044: 
                   4045: =cut
                   4046: 
1.14      harris41 4047: sub languageids {
1.16      harris41 4048:     return sort(keys(%language));
1.14      harris41 4049: }
                   4050: 
1.112     bowersj2 4051: =pod
                   4052: 
1.648     raeburn  4053: =item * &languagedescription() 
1.112     bowersj2 4054: 
                   4055: returns description of a specified language id
                   4056: 
                   4057: =cut
                   4058: 
1.14      harris41 4059: sub languagedescription {
1.125     www      4060:     my $code=shift;
                   4061:     return  ($supported_language{$code}?'* ':'').
                   4062:             $language{$code}.
1.126     www      4063: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4064: }
                   4065: 
1.1048    foxr     4066: =pod
                   4067: 
                   4068: =item * &plainlanguagedescription
                   4069: 
                   4070: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4071: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4072: 
                   4073: =cut
                   4074: 
1.145     www      4075: sub plainlanguagedescription {
                   4076:     my $code=shift;
                   4077:     return $language{$code};
                   4078: }
                   4079: 
1.1048    foxr     4080: =pod
                   4081: 
                   4082: =item * &supportedlanguagecode
                   4083: 
                   4084: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4085: code.
                   4086: 
                   4087: =cut
                   4088: 
1.145     www      4089: sub supportedlanguagecode {
                   4090:     my $code=shift;
                   4091:     return $supported_language{$code};
1.97      www      4092: }
                   4093: 
1.112     bowersj2 4094: =pod
                   4095: 
1.1048    foxr     4096: =item * &latexlanguage()
                   4097: 
                   4098: Given a language key code returns the correspondnig language to use
                   4099: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4100: is no supported hyphenation for the language code.
                   4101: 
                   4102: =cut
                   4103: 
                   4104: sub latexlanguage {
                   4105:     my $code = shift;
                   4106:     return $latex_language{$code};
                   4107: }
                   4108: 
                   4109: =pod
                   4110: 
                   4111: =item * &latexhyphenation()
                   4112: 
                   4113: Same as above but what's supplied is the language as it might be stored
                   4114: in the metadata.
                   4115: 
                   4116: =cut
                   4117: 
                   4118: sub latexhyphenation {
                   4119:     my $key = shift;
                   4120:     return $latex_language_bykey{$key};
                   4121: }
                   4122: 
                   4123: =pod
                   4124: 
1.648     raeburn  4125: =item * &copyrightids() 
1.112     bowersj2 4126: 
                   4127: returns list of all copyrights
                   4128: 
                   4129: =cut
                   4130: 
                   4131: sub copyrightids {
                   4132:     return sort(keys(%cprtag));
                   4133: }
                   4134: 
                   4135: =pod
                   4136: 
1.648     raeburn  4137: =item * &copyrightdescription() 
1.112     bowersj2 4138: 
                   4139: returns description of a specified copyright id
                   4140: 
                   4141: =cut
                   4142: 
                   4143: sub copyrightdescription {
1.166     www      4144:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4145: }
1.197     matthew  4146: 
                   4147: =pod
                   4148: 
1.648     raeburn  4149: =item * &source_copyrightids() 
1.192     taceyjo1 4150: 
                   4151: returns list of all source copyrights
                   4152: 
                   4153: =cut
                   4154: 
                   4155: sub source_copyrightids {
                   4156:     return sort(keys(%scprtag));
                   4157: }
                   4158: 
                   4159: =pod
                   4160: 
1.648     raeburn  4161: =item * &source_copyrightdescription() 
1.192     taceyjo1 4162: 
                   4163: returns description of a specified source copyright id
                   4164: 
                   4165: =cut
                   4166: 
                   4167: sub source_copyrightdescription {
                   4168:     return &mt($scprtag{shift(@_)});
                   4169: }
1.112     bowersj2 4170: 
                   4171: =pod
                   4172: 
1.648     raeburn  4173: =item * &filecategories() 
1.112     bowersj2 4174: 
                   4175: returns list of all file categories
                   4176: 
                   4177: =cut
                   4178: 
                   4179: sub filecategories {
                   4180:     return sort(keys(%category_extensions));
                   4181: }
                   4182: 
                   4183: =pod
                   4184: 
1.648     raeburn  4185: =item * &filecategorytypes() 
1.112     bowersj2 4186: 
                   4187: returns list of file types belonging to a given file
                   4188: category
                   4189: 
                   4190: =cut
                   4191: 
                   4192: sub filecategorytypes {
1.356     albertel 4193:     my ($cat) = @_;
1.1248    raeburn  4194:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4195:         return @{$category_extensions{lc($cat)}};
                   4196:     } else {
                   4197:         return ();
                   4198:     }
1.112     bowersj2 4199: }
                   4200: 
                   4201: =pod
                   4202: 
1.648     raeburn  4203: =item * &fileembstyle() 
1.112     bowersj2 4204: 
                   4205: returns embedding style for a specified file type
                   4206: 
                   4207: =cut
                   4208: 
                   4209: sub fileembstyle {
                   4210:     return $fe{lc(shift(@_))};
1.169     www      4211: }
                   4212: 
1.351     www      4213: sub filemimetype {
                   4214:     return $fm{lc(shift(@_))};
                   4215: }
                   4216: 
1.169     www      4217: 
                   4218: sub filecategoryselect {
                   4219:     my ($name,$value)=@_;
1.189     matthew  4220:     return &select_form($value,$name,
1.970     raeburn  4221:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4222: }
                   4223: 
                   4224: =pod
                   4225: 
1.648     raeburn  4226: =item * &filedescription() 
1.112     bowersj2 4227: 
                   4228: returns description for a specified file type
                   4229: 
                   4230: =cut
                   4231: 
                   4232: sub filedescription {
1.188     matthew  4233:     my $file_description = $fd{lc(shift())};
                   4234:     $file_description =~ s:([\[\]]):~$1:g;
                   4235:     return &mt($file_description);
1.112     bowersj2 4236: }
                   4237: 
                   4238: =pod
                   4239: 
1.648     raeburn  4240: =item * &filedescriptionex() 
1.112     bowersj2 4241: 
                   4242: returns description for a specified file type with
                   4243: extra formatting
                   4244: 
                   4245: =cut
                   4246: 
                   4247: sub filedescriptionex {
                   4248:     my $ex=shift;
1.188     matthew  4249:     my $file_description = $fd{lc($ex)};
                   4250:     $file_description =~ s:([\[\]]):~$1:g;
                   4251:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4252: }
                   4253: 
                   4254: # End of .tab access
                   4255: =pod
                   4256: 
                   4257: =back
                   4258: 
                   4259: =cut
                   4260: 
                   4261: # ------------------------------------------------------------------ File Types
                   4262: sub fileextensions {
                   4263:     return sort(keys(%fe));
                   4264: }
                   4265: 
1.97      www      4266: # ----------------------------------------------------------- Display Languages
                   4267: # returns a hash with all desired display languages
                   4268: #
                   4269: 
                   4270: sub display_languages {
                   4271:     my %languages=();
1.695     raeburn  4272:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4273: 	$languages{$lang}=1;
1.97      www      4274:     }
                   4275:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4276:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4277: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4278: 	    $languages{$lang}=1;
1.97      www      4279:         }
                   4280:     }
                   4281:     return %languages;
1.14      harris41 4282: }
                   4283: 
1.582     albertel 4284: sub languages {
                   4285:     my ($possible_langs) = @_;
1.695     raeburn  4286:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4287:     if (!ref($possible_langs)) {
                   4288: 	if( wantarray ) {
                   4289: 	    return @preferred_langs;
                   4290: 	} else {
                   4291: 	    return $preferred_langs[0];
                   4292: 	}
                   4293:     }
                   4294:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4295:     my @preferred_possibilities;
                   4296:     foreach my $preferred_lang (@preferred_langs) {
                   4297: 	if (exists($possibilities{$preferred_lang})) {
                   4298: 	    push(@preferred_possibilities, $preferred_lang);
                   4299: 	}
                   4300:     }
                   4301:     if( wantarray ) {
                   4302: 	return @preferred_possibilities;
                   4303:     }
                   4304:     return $preferred_possibilities[0];
                   4305: }
                   4306: 
1.742     raeburn  4307: sub user_lang {
                   4308:     my ($touname,$toudom,$fromcid) = @_;
                   4309:     my @userlangs;
                   4310:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4311:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4312:                     $env{'course.'.$fromcid.'.languages'}));
                   4313:     } else {
                   4314:         my %langhash = &getlangs($touname,$toudom);
                   4315:         if ($langhash{'languages'} ne '') {
                   4316:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4317:         } else {
                   4318:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4319:             if ($domdefs{'lang_def'} ne '') {
                   4320:                 @userlangs = ($domdefs{'lang_def'});
                   4321:             }
                   4322:         }
                   4323:     }
                   4324:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4325:     my $user_lh = Apache::localize->get_handle(@languages);
                   4326:     return $user_lh;
                   4327: }
                   4328: 
                   4329: 
1.112     bowersj2 4330: ###############################################################
                   4331: ##               Student Answer Attempts                     ##
                   4332: ###############################################################
                   4333: 
                   4334: =pod
                   4335: 
                   4336: =head1 Alternate Problem Views
                   4337: 
                   4338: =over 4
                   4339: 
1.648     raeburn  4340: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4341:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4342: 
                   4343: Return string with previous attempt on problem. Arguments:
                   4344: 
                   4345: =over 4
                   4346: 
                   4347: =item * $symb: Problem, including path
                   4348: 
                   4349: =item * $username: username of the desired student
                   4350: 
                   4351: =item * $domain: domain of the desired student
1.14      harris41 4352: 
1.112     bowersj2 4353: =item * $course: Course ID
1.14      harris41 4354: 
1.112     bowersj2 4355: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4356:     something
1.14      harris41 4357: 
1.112     bowersj2 4358: =item * $regexp: if string matches this regexp, the string will be
                   4359:     sent to $gradesub
1.14      harris41 4360: 
1.112     bowersj2 4361: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4362: 
1.1199    raeburn  4363: =item * $usec: section of the desired student
                   4364: 
                   4365: =item * $identifier: counter for student (multiple students one problem) or 
                   4366:     problem (one student; whole sequence).
                   4367: 
1.112     bowersj2 4368: =back
1.14      harris41 4369: 
1.112     bowersj2 4370: The output string is a table containing all desired attempts, if any.
1.16      harris41 4371: 
1.112     bowersj2 4372: =cut
1.1       albertel 4373: 
                   4374: sub get_previous_attempt {
1.1199    raeburn  4375:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4376:   my $prevattempts='';
1.43      ng       4377:   no strict 'refs';
1.1       albertel 4378:   if ($symb) {
1.3       albertel 4379:     my (%returnhash)=
                   4380:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4381:     if ($returnhash{'version'}) {
                   4382:       my %lasthash=();
                   4383:       my $version;
                   4384:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4385:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4386:             if ($key =~ /\.rawrndseed$/) {
                   4387:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4388:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4389:             } else {
                   4390:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4391:             }
1.19      harris41 4392:         }
1.1       albertel 4393:       }
1.596     albertel 4394:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4395:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4396:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4397:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4398:       foreach my $key (sort(keys(%lasthash))) {
                   4399: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4400: 	if ($#parts > 0) {
1.31      albertel 4401: 	  my $data=$parts[-1];
1.989     raeburn  4402:           next if ($data eq 'foilorder');
1.31      albertel 4403: 	  pop(@parts);
1.1010    www      4404:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4405:           if ($data eq 'type') {
                   4406:               unless ($showsurv) {
                   4407:                   my $id = join(',',@parts);
                   4408:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4409:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4410:                       $lasthidden{$ign.'.'.$id} = 1;
                   4411:                   }
1.945     raeburn  4412:               }
1.1199    raeburn  4413:               if ($identifier ne '') {
                   4414:                   my $id = join(',',@parts);
                   4415:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4416:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4417:                       $hidestatus{$ign.'.'.$id} = 1;
                   4418:                   }
                   4419:               }
                   4420:           } elsif ($data eq 'regrader') {
                   4421:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4422:                   my $id = join(',',@parts);
                   4423:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4424:               }
1.1010    www      4425:           } 
1.31      albertel 4426: 	} else {
1.41      ng       4427: 	  if ($#parts == 0) {
                   4428: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4429: 	  } else {
                   4430: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4431: 	  }
1.31      albertel 4432: 	}
1.16      harris41 4433:       }
1.596     albertel 4434:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4435:       if ($getattempt eq '') {
1.1199    raeburn  4436:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4437:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4438:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4439:                 foreach my $id (keys(%regraded)) {
                   4440:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4441:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4442:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4443:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4444:                     }
                   4445:                 }
                   4446:             }
1.1200    raeburn  4447:         }
                   4448: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4449:             my (@hidden,@unsolved);
1.945     raeburn  4450:             if (%typeparts) {
                   4451:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4452:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4453:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4454:                         push(@hidden,$id);
1.1199    raeburn  4455:                     } elsif ($identifier ne '') {
                   4456:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4457:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4458:                                 ($hidestatus{$id})) {
1.1200    raeburn  4459:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4460:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4461:                                 push(@{$solved{$id}},$version);
                   4462:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4463:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4464:                                 my $skip;
                   4465:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4466:                                     foreach my $reset (@{$resets{$id}}) {
                   4467:                                         if ($reset > $solved{$id}[-1]) {
                   4468:                                             $skip=1;
                   4469:                                             last;
                   4470:                                         }
                   4471:                                     }
                   4472:                                 }
                   4473:                                 unless ($skip) {
                   4474:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4475:                                     push(@unsolved,$partslist);
                   4476:                                 }
                   4477:                             }
                   4478:                         }
1.945     raeburn  4479:                     }
                   4480:                 }
                   4481:             }
                   4482:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4483:                            '<td>'.&mt('Transaction [_1]',$version);
                   4484:             if (@unsolved) {
                   4485:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4486:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4487:                                  &mt('Hide').'</label></span>';
                   4488:             }
                   4489:             $prevattempts .= '</td>';
1.945     raeburn  4490:             if (@hidden) {
                   4491:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4492:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4493:                     my $hide;
                   4494:                     foreach my $id (@hidden) {
                   4495:                         if ($key =~ /^\Q$id\E/) {
                   4496:                             $hide = 1;
                   4497:                             last;
                   4498:                         }
                   4499:                     }
                   4500:                     if ($hide) {
                   4501:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4502:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4503:                             my $value = &format_previous_attempt_value($key,
                   4504:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4505:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4506:                         } else {
                   4507:                             $prevattempts.='<td>&nbsp;</td>';
                   4508:                         }
                   4509:                     } else {
                   4510:                         if ($key =~ /\./) {
1.1212    raeburn  4511:                             my $value = $returnhash{$version.':'.$key};
                   4512:                             if ($key =~ /\.rndseed$/) {
                   4513:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4514:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4515:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4516:                                 }
                   4517:                             }
                   4518:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4519:                                            '&nbsp;</td>';
1.945     raeburn  4520:                         } else {
                   4521:                             $prevattempts.='<td>&nbsp;</td>';
                   4522:                         }
                   4523:                     }
                   4524:                 }
                   4525:             } else {
                   4526: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4527:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4528:                     my $value = $returnhash{$version.':'.$key};
                   4529:                     if ($key =~ /\.rndseed$/) {
                   4530:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4531:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4532:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4533:                         }
                   4534:                     }
                   4535:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4536:                                    '&nbsp;</td>';
1.945     raeburn  4537: 	        }
                   4538:             }
                   4539: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4540: 	 }
1.1       albertel 4541:       }
1.945     raeburn  4542:       my @currhidden = keys(%lasthidden);
1.596     albertel 4543:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4544:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4545:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4546:           if (%typeparts) {
                   4547:               my $hidden;
                   4548:               foreach my $id (@currhidden) {
                   4549:                   if ($key =~ /^\Q$id\E/) {
                   4550:                       $hidden = 1;
                   4551:                       last;
                   4552:                   }
                   4553:               }
                   4554:               if ($hidden) {
                   4555:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4556:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4557:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4558:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4559:                           $value = &$gradesub($value);
                   4560:                       }
1.1173    kruse    4561:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4562:                   } else {
                   4563:                       $prevattempts.='<td>&nbsp;</td>';
                   4564:                   }
                   4565:               } else {
                   4566:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4567:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4568:                       $value = &$gradesub($value);
                   4569:                   }
1.1173    kruse    4570:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4571:               }
                   4572:           } else {
                   4573: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4574: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4575:                   $value = &$gradesub($value);
                   4576:               }
1.1173    kruse    4577: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4578:           }
1.16      harris41 4579:       }
1.596     albertel 4580:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4581:     } else {
1.1305    raeburn  4582:       my $msg;
                   4583:       if ($symb =~ /ext\.tool$/) {
                   4584:           $msg = &mt('No grade passed back.');
                   4585:       } else {
                   4586:           $msg = &mt('Nothing submitted - no attempts.');
                   4587:       }
1.596     albertel 4588:       $prevattempts=
                   4589: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  4590: 	  '<td>'.$msg.'</td>'.
1.596     albertel 4591: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4592:     }
                   4593:   } else {
1.596     albertel 4594:     $prevattempts=
                   4595: 	  &start_data_table().&start_data_table_row().
                   4596: 	  '<td>'.&mt('No data.').'</td>'.
                   4597: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4598:   }
1.10      albertel 4599: }
                   4600: 
1.581     albertel 4601: sub format_previous_attempt_value {
                   4602:     my ($key,$value) = @_;
1.1011    www      4603:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4604:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4605:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4606:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4607:     } elsif ($key =~ /answerstring$/) {
                   4608:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4609:         my @answer = %answers;
                   4610:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4611:         my @anskeys = sort(keys(%answers));
                   4612:         if (@anskeys == 1) {
                   4613:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4614:             if ($answer =~ m{\0}) {
                   4615:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4616:             }
                   4617:             my $tag_internal_answer_name = 'INTERNAL';
                   4618:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4619:                 $value = $answer; 
                   4620:             } else {
                   4621:                 $value = $anskeys[0].'='.$answer;
                   4622:             }
                   4623:         } else {
                   4624:             foreach my $ans (@anskeys) {
                   4625:                 my $answer = $answers{$ans};
1.1001    raeburn  4626:                 if ($answer =~ m{\0}) {
                   4627:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4628:                 }
                   4629:                 $value .=  $ans.'='.$answer.'<br />';;
                   4630:             } 
                   4631:         }
1.581     albertel 4632:     } else {
1.1173    kruse    4633:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4634:     }
                   4635:     return $value;
                   4636: }
                   4637: 
                   4638: 
1.107     albertel 4639: sub relative_to_absolute {
                   4640:     my ($url,$output)=@_;
                   4641:     my $parser=HTML::TokeParser->new(\$output);
                   4642:     my $token;
                   4643:     my $thisdir=$url;
                   4644:     my @rlinks=();
                   4645:     while ($token=$parser->get_token) {
                   4646: 	if ($token->[0] eq 'S') {
                   4647: 	    if ($token->[1] eq 'a') {
                   4648: 		if ($token->[2]->{'href'}) {
                   4649: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4650: 		}
                   4651: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4652: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4653: 	    } elsif ($token->[1] eq 'base') {
                   4654: 		$thisdir=$token->[2]->{'href'};
                   4655: 	    }
                   4656: 	}
                   4657:     }
                   4658:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4659:     foreach my $link (@rlinks) {
1.726     raeburn  4660: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4661: 		($link=~/^\//) ||
                   4662: 		($link=~/^javascript:/i) ||
                   4663: 		($link=~/^mailto:/i) ||
                   4664: 		($link=~/^\#/)) {
                   4665: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4666: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4667: 	}
                   4668:     }
                   4669: # -------------------------------------------------- Deal with Applet codebases
                   4670:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4671:     return $output;
                   4672: }
                   4673: 
1.112     bowersj2 4674: =pod
                   4675: 
1.648     raeburn  4676: =item * &get_student_view()
1.112     bowersj2 4677: 
                   4678: show a snapshot of what student was looking at
                   4679: 
                   4680: =cut
                   4681: 
1.10      albertel 4682: sub get_student_view {
1.186     albertel 4683:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4684:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4685:   my (%form);
1.10      albertel 4686:   my @elements=('symb','courseid','domain','username');
                   4687:   foreach my $element (@elements) {
1.186     albertel 4688:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4689:   }
1.186     albertel 4690:   if (defined($moreenv)) {
                   4691:       %form=(%form,%{$moreenv});
                   4692:   }
1.236     albertel 4693:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4694:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306  ! raeburn  4695:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
        !          4696:       $feedurl =~ s{^/adm/wrapper}{};
        !          4697:   }
1.650     www      4698:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4699:   $userview=~s/\<body[^\>]*\>//gi;
                   4700:   $userview=~s/\<\/body\>//gi;
                   4701:   $userview=~s/\<html\>//gi;
                   4702:   $userview=~s/\<\/html\>//gi;
                   4703:   $userview=~s/\<head\>//gi;
                   4704:   $userview=~s/\<\/head\>//gi;
                   4705:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4706:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4707:   if (wantarray) {
                   4708:      return ($userview,$response);
                   4709:   } else {
                   4710:      return $userview;
                   4711:   }
                   4712: }
                   4713: 
                   4714: sub get_student_view_with_retries {
                   4715:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4716: 
                   4717:     my $ok = 0;                 # True if we got a good response.
                   4718:     my $content;
                   4719:     my $response;
                   4720: 
                   4721:     # Try to get the student_view done. within the retries count:
                   4722:     
                   4723:     do {
                   4724:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4725:          $ok      = $response->is_success;
                   4726:          if (!$ok) {
                   4727:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4728:          }
                   4729:          $retries--;
                   4730:     } while (!$ok && ($retries > 0));
                   4731:     
                   4732:     if (!$ok) {
                   4733:        $content = '';          # On error return an empty content.
                   4734:     }
1.651     www      4735:     if (wantarray) {
                   4736:        return ($content, $response);
                   4737:     } else {
                   4738:        return $content;
                   4739:     }
1.11      albertel 4740: }
                   4741: 
1.112     bowersj2 4742: =pod
                   4743: 
1.648     raeburn  4744: =item * &get_student_answers() 
1.112     bowersj2 4745: 
                   4746: show a snapshot of how student was answering problem
                   4747: 
                   4748: =cut
                   4749: 
1.11      albertel 4750: sub get_student_answers {
1.100     sakharuk 4751:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4752:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4753:   my (%moreenv);
1.11      albertel 4754:   my @elements=('symb','courseid','domain','username');
                   4755:   foreach my $element (@elements) {
1.186     albertel 4756:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4757:   }
1.186     albertel 4758:   $moreenv{'grade_target'}='answer';
                   4759:   %moreenv=(%form,%moreenv);
1.497     raeburn  4760:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4761:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4762:   return $userview;
1.1       albertel 4763: }
1.116     albertel 4764: 
                   4765: =pod
                   4766: 
                   4767: =item * &submlink()
                   4768: 
1.242     albertel 4769: Inputs: $text $uname $udom $symb $target
1.116     albertel 4770: 
                   4771: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4772: 
                   4773: =cut
                   4774: 
                   4775: ###############################################
                   4776: sub submlink {
1.242     albertel 4777:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4778:     if (!($uname && $udom)) {
                   4779: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4780: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4781: 	if (!$symb) { $symb=$cursymb; }
                   4782:     }
1.254     matthew  4783:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4784:     $symb=&escape($symb);
1.960     bisitz   4785:     if ($target) { $target=" target=\"$target\""; }
                   4786:     return
                   4787:         '<a href="/adm/grades?command=submission'.
                   4788:         '&amp;symb='.$symb.
                   4789:         '&amp;student='.$uname.
                   4790:         '&amp;userdom='.$udom.'"'.
                   4791:         $target.'>'.$text.'</a>';
1.242     albertel 4792: }
                   4793: ##############################################
                   4794: 
                   4795: =pod
                   4796: 
                   4797: =item * &pgrdlink()
                   4798: 
                   4799: Inputs: $text $uname $udom $symb $target
                   4800: 
                   4801: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4802: 
                   4803: =cut
                   4804: 
                   4805: ###############################################
                   4806: sub pgrdlink {
                   4807:     my $link=&submlink(@_);
                   4808:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4809:     return $link;
                   4810: }
                   4811: ##############################################
                   4812: 
                   4813: =pod
                   4814: 
                   4815: =item * &pprmlink()
                   4816: 
                   4817: Inputs: $text $uname $udom $symb $target
                   4818: 
                   4819: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4820: student and a specific resource
1.242     albertel 4821: 
                   4822: =cut
                   4823: 
                   4824: ###############################################
                   4825: sub pprmlink {
                   4826:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4827:     if (!($uname && $udom)) {
                   4828: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4829: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4830: 	if (!$symb) { $symb=$cursymb; }
                   4831:     }
1.254     matthew  4832:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4833:     $symb=&escape($symb);
1.242     albertel 4834:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4835:     return '<a href="/adm/parmset?command=set&amp;'.
                   4836: 	'symb='.$symb.'&amp;uname='.$uname.
                   4837: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4838: }
                   4839: ##############################################
1.37      matthew  4840: 
1.112     bowersj2 4841: =pod
                   4842: 
                   4843: =back
                   4844: 
                   4845: =cut
                   4846: 
1.37      matthew  4847: ###############################################
1.51      www      4848: 
                   4849: 
                   4850: sub timehash {
1.687     raeburn  4851:     my ($thistime) = @_;
                   4852:     my $timezone = &Apache::lonlocal::gettimezone();
                   4853:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4854:                      ->set_time_zone($timezone);
                   4855:     my $wday = $dt->day_of_week();
                   4856:     if ($wday == 7) { $wday = 0; }
                   4857:     return ( 'second' => $dt->second(),
                   4858:              'minute' => $dt->minute(),
                   4859:              'hour'   => $dt->hour(),
                   4860:              'day'     => $dt->day_of_month(),
                   4861:              'month'   => $dt->month(),
                   4862:              'year'    => $dt->year(),
                   4863:              'weekday' => $wday,
                   4864:              'dayyear' => $dt->day_of_year(),
                   4865:              'dlsav'   => $dt->is_dst() );
1.51      www      4866: }
                   4867: 
1.370     www      4868: sub utc_string {
                   4869:     my ($date)=@_;
1.371     www      4870:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4871: }
                   4872: 
1.51      www      4873: sub maketime {
                   4874:     my %th=@_;
1.687     raeburn  4875:     my ($epoch_time,$timezone,$dt);
                   4876:     $timezone = &Apache::lonlocal::gettimezone();
                   4877:     eval {
                   4878:         $dt = DateTime->new( year   => $th{'year'},
                   4879:                              month  => $th{'month'},
                   4880:                              day    => $th{'day'},
                   4881:                              hour   => $th{'hour'},
                   4882:                              minute => $th{'minute'},
                   4883:                              second => $th{'second'},
                   4884:                              time_zone => $timezone,
                   4885:                          );
                   4886:     };
                   4887:     if (!$@) {
                   4888:         $epoch_time = $dt->epoch;
                   4889:         if ($epoch_time) {
                   4890:             return $epoch_time;
                   4891:         }
                   4892:     }
1.51      www      4893:     return POSIX::mktime(
                   4894:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4895:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4896: }
                   4897: 
                   4898: #########################################
1.51      www      4899: 
                   4900: sub findallcourses {
1.482     raeburn  4901:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4902:     my %roles;
                   4903:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4904:     my %courses;
1.51      www      4905:     my $now=time;
1.482     raeburn  4906:     if (!defined($uname)) {
                   4907:         $uname = $env{'user.name'};
                   4908:     }
                   4909:     if (!defined($udom)) {
                   4910:         $udom = $env{'user.domain'};
                   4911:     }
                   4912:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4913:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4914:         if (!%roles) {
                   4915:             %roles = (
                   4916:                        cc => 1,
1.907     raeburn  4917:                        co => 1,
1.482     raeburn  4918:                        in => 1,
                   4919:                        ep => 1,
                   4920:                        ta => 1,
                   4921:                        cr => 1,
                   4922:                        st => 1,
                   4923:              );
                   4924:         }
                   4925:         foreach my $entry (keys(%roleshash)) {
                   4926:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4927:             if ($trole =~ /^cr/) { 
                   4928:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4929:             } else {
                   4930:                 next if (!exists($roles{$trole}));
                   4931:             }
                   4932:             if ($tend) {
                   4933:                 next if ($tend < $now);
                   4934:             }
                   4935:             if ($tstart) {
                   4936:                 next if ($tstart > $now);
                   4937:             }
1.1058    raeburn  4938:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4939:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4940:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4941:             if ($secpart eq '') {
                   4942:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4943:                 $sec = 'none';
1.1058    raeburn  4944:                 $value .= $cnum.'/';
1.482     raeburn  4945:             } else {
                   4946:                 $cnum = $cnumpart;
                   4947:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4948:                 $value .= $cnum.'/'.$sec;
                   4949:             }
                   4950:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4951:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4952:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4953:                 }
                   4954:             } else {
                   4955:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4956:             }
1.482     raeburn  4957:         }
                   4958:     } else {
                   4959:         foreach my $key (keys(%env)) {
1.483     albertel 4960: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4961:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4962: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4963: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4964: 	        next if (%roles && !exists($roles{$role}));
                   4965: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4966:                 my $active=1;
                   4967:                 if ($starttime) {
                   4968: 		    if ($now<$starttime) { $active=0; }
                   4969:                 }
                   4970:                 if ($endtime) {
                   4971:                     if ($now>$endtime) { $active=0; }
                   4972:                 }
                   4973:                 if ($active) {
1.1058    raeburn  4974:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4975:                     if ($sec eq '') {
                   4976:                         $sec = 'none';
1.1058    raeburn  4977:                     } else {
                   4978:                         $value .= $sec;
                   4979:                     }
                   4980:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4981:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4982:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4983:                         }
                   4984:                     } else {
                   4985:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4986:                     }
1.474     raeburn  4987:                 }
                   4988:             }
1.51      www      4989:         }
                   4990:     }
1.474     raeburn  4991:     return %courses;
1.51      www      4992: }
1.37      matthew  4993: 
1.54      www      4994: ###############################################
1.474     raeburn  4995: 
                   4996: sub blockcheck {
1.1189    raeburn  4997:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4998: 
1.1189    raeburn  4999:     if (defined($udom) && defined($uname)) {
                   5000:         # If uname and udom are for a course, check for blocks in the course.
                   5001:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5002:             my ($startblock,$endblock,$triggerblock) =
                   5003:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   5004:             return ($startblock,$endblock,$triggerblock);
                   5005:         }
                   5006:     } else {
1.490     raeburn  5007:         $udom = $env{'user.domain'};
                   5008:         $uname = $env{'user.name'};
                   5009:     }
                   5010: 
1.502     raeburn  5011:     my $startblock = 0;
                   5012:     my $endblock = 0;
1.1062    raeburn  5013:     my $triggerblock = '';
1.482     raeburn  5014:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  5015: 
1.490     raeburn  5016:     # If uname is for a user, and activity is course-specific, i.e.,
                   5017:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5018: 
1.490     raeburn  5019:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5020:          $activity eq 'groups' || $activity eq 'printout' ||
                   5021:          $activity eq 'reinit' || $activity eq 'alert') &&
1.1189    raeburn  5022:         ($env{'request.course.id'})) {
1.490     raeburn  5023:         foreach my $key (keys(%live_courses)) {
                   5024:             if ($key ne $env{'request.course.id'}) {
                   5025:                 delete($live_courses{$key});
                   5026:             }
                   5027:         }
                   5028:     }
                   5029: 
                   5030:     my $otheruser = 0;
                   5031:     my %own_courses;
                   5032:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5033:         # Resource belongs to user other than current user.
                   5034:         $otheruser = 1;
                   5035:         # Gather courses for current user
                   5036:         %own_courses = 
                   5037:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5038:     }
                   5039: 
                   5040:     # Gather active course roles - course coordinator, instructor, 
                   5041:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5042: 
                   5043:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5044:         my ($cdom,$cnum);
                   5045:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5046:             $cdom = $env{'course.'.$course.'.domain'};
                   5047:             $cnum = $env{'course.'.$course.'.num'};
                   5048:         } else {
1.490     raeburn  5049:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5050:         }
                   5051:         my $no_ownblock = 0;
                   5052:         my $no_userblock = 0;
1.533     raeburn  5053:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5054:             # Check if current user has 'evb' priv for this
                   5055:             if (defined($own_courses{$course})) {
                   5056:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5057:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5058:                     if ($sec ne 'none') {
                   5059:                         $checkrole .= '/'.$sec;
                   5060:                     }
                   5061:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5062:                         $no_ownblock = 1;
                   5063:                         last;
                   5064:                     }
                   5065:                 }
                   5066:             }
                   5067:             # if they have 'evb' priv and are currently not playing student
                   5068:             next if (($no_ownblock) &&
                   5069:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5070:         }
1.474     raeburn  5071:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5072:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5073:             if ($sec ne 'none') {
1.482     raeburn  5074:                 $checkrole .= '/'.$sec;
1.474     raeburn  5075:             }
1.490     raeburn  5076:             if ($otheruser) {
                   5077:                 # Resource belongs to user other than current user.
                   5078:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5079:                 my (%allroles,%userroles);
                   5080:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5081:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5082:                         my ($trole,$tdom,$tnum,$tsec);
                   5083:                         if ($entry =~ /^cr/) {
                   5084:                             ($trole,$tdom,$tnum,$tsec) = 
                   5085:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5086:                         } else {
                   5087:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5088:                         }
                   5089:                         my ($spec,$area,$trest);
                   5090:                         $area = '/'.$tdom.'/'.$tnum;
                   5091:                         $trest = $tnum;
                   5092:                         if ($tsec ne '') {
                   5093:                             $area .= '/'.$tsec;
                   5094:                             $trest .= '/'.$tsec;
                   5095:                         }
                   5096:                         $spec = $trole.'.'.$area;
                   5097:                         if ($trole =~ /^cr/) {
                   5098:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5099:                                                               $tdom,$spec,$trest,$area);
                   5100:                         } else {
                   5101:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5102:                                                                 $tdom,$spec,$trest,$area);
                   5103:                         }
                   5104:                     }
1.1276    raeburn  5105:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5106:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5107:                         if ($1) {
                   5108:                             $no_userblock = 1;
                   5109:                             last;
                   5110:                         }
1.486     raeburn  5111:                     }
                   5112:                 }
1.490     raeburn  5113:             } else {
                   5114:                 # Resource belongs to current user
                   5115:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5116:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5117:                     $no_ownblock = 1;
                   5118:                     last;
                   5119:                 }
1.474     raeburn  5120:             }
                   5121:         }
                   5122:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5123:         next if (($no_ownblock) &&
1.491     albertel 5124:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5125:         next if ($no_userblock);
1.474     raeburn  5126: 
1.1303    raeburn  5127:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5128:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5129: 
1.1062    raeburn  5130:         my ($start,$end,$trigger) = 
                   5131:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  5132:         if (($start != 0) && 
                   5133:             (($startblock == 0) || ($startblock > $start))) {
                   5134:             $startblock = $start;
1.1062    raeburn  5135:             if ($trigger ne '') {
                   5136:                 $triggerblock = $trigger;
                   5137:             }
1.502     raeburn  5138:         }
                   5139:         if (($end != 0)  &&
                   5140:             (($endblock == 0) || ($endblock < $end))) {
                   5141:             $endblock = $end;
1.1062    raeburn  5142:             if ($trigger ne '') {
                   5143:                 $triggerblock = $trigger;
                   5144:             }
1.502     raeburn  5145:         }
1.490     raeburn  5146:     }
1.1062    raeburn  5147:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5148: }
                   5149: 
                   5150: sub get_blocks {
1.1062    raeburn  5151:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  5152:     my $startblock = 0;
                   5153:     my $endblock = 0;
1.1062    raeburn  5154:     my $triggerblock = '';
1.490     raeburn  5155:     my $course = $cdom.'_'.$cnum;
                   5156:     $setters->{$course} = {};
                   5157:     $setters->{$course}{'staff'} = [];
                   5158:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5159:     $setters->{$course}{'triggers'} = [];
                   5160:     my (@blockers,%triggered);
                   5161:     my $now = time;
                   5162:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5163:     if ($activity eq 'docs') {
                   5164:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   5165:         foreach my $block (@blockers) {
                   5166:             if ($block =~ /^firstaccess____(.+)$/) {
                   5167:                 my $item = $1;
                   5168:                 my $type = 'map';
                   5169:                 my $timersymb = $item;
                   5170:                 if ($item eq 'course') {
                   5171:                     $type = 'course';
                   5172:                 } elsif ($item =~ /___\d+___/) {
                   5173:                     $type = 'resource';
                   5174:                 } else {
                   5175:                     $timersymb = &Apache::lonnet::symbread($item);
                   5176:                 }
                   5177:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5178:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5179:                 $triggered{$block} = {
                   5180:                                        start => $start,
                   5181:                                        end   => $end,
                   5182:                                        type  => $type,
                   5183:                                      };
                   5184:             }
                   5185:         }
                   5186:     } else {
                   5187:         foreach my $block (keys(%commblocks)) {
                   5188:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5189:                 my ($start,$end) = ($1,$2);
                   5190:                 if ($start <= time && $end >= time) {
                   5191:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5192:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5193:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5194:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5195:                                     push(@blockers,$block);
                   5196:                                 }
                   5197:                             }
                   5198:                         }
                   5199:                     }
                   5200:                 }
                   5201:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5202:                 my $item = $1;
                   5203:                 my $timersymb = $item; 
                   5204:                 my $type = 'map';
                   5205:                 if ($item eq 'course') {
                   5206:                     $type = 'course';
                   5207:                 } elsif ($item =~ /___\d+___/) {
                   5208:                     $type = 'resource';
                   5209:                 } else {
                   5210:                     $timersymb = &Apache::lonnet::symbread($item);
                   5211:                 }
                   5212:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5213:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5214:                 if ($start && $end) {
                   5215:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5216:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5217:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5218:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5219:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5220:                                         push(@blockers,$block);
                   5221:                                         $triggered{$block} = {
                   5222:                                                                start => $start,
                   5223:                                                                end   => $end,
                   5224:                                                                type  => $type,
                   5225:                                                              };
                   5226:                                     }
                   5227:                                 }
                   5228:                             }
1.1062    raeburn  5229:                         }
                   5230:                     }
1.490     raeburn  5231:                 }
1.1062    raeburn  5232:             }
                   5233:         }
                   5234:     }
                   5235:     foreach my $blocker (@blockers) {
                   5236:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5237:             &parse_block_record($commblocks{$blocker});
                   5238:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5239:         my ($start,$end,$triggertype);
                   5240:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5241:             ($start,$end) = ($1,$2);
                   5242:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5243:             $start = $triggered{$blocker}{'start'};
                   5244:             $end = $triggered{$blocker}{'end'};
                   5245:             $triggertype = $triggered{$blocker}{'type'};
                   5246:         }
                   5247:         if ($start) {
                   5248:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5249:             if ($triggertype) {
                   5250:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5251:             } else {
                   5252:                 push(@{$$setters{$course}{'triggers'}},0);
                   5253:             }
                   5254:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5255:                 $startblock = $start;
                   5256:                 if ($triggertype) {
                   5257:                     $triggerblock = $blocker;
1.474     raeburn  5258:                 }
                   5259:             }
1.1062    raeburn  5260:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5261:                $endblock = $end;
                   5262:                if ($triggertype) {
                   5263:                    $triggerblock = $blocker;
                   5264:                }
                   5265:             }
1.474     raeburn  5266:         }
                   5267:     }
1.1062    raeburn  5268:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5269: }
                   5270: 
                   5271: sub parse_block_record {
                   5272:     my ($record) = @_;
                   5273:     my ($setuname,$setudom,$title,$blocks);
                   5274:     if (ref($record) eq 'HASH') {
                   5275:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5276:         $title = &unescape($record->{'event'});
                   5277:         $blocks = $record->{'blocks'};
                   5278:     } else {
                   5279:         my @data = split(/:/,$record,3);
                   5280:         if (scalar(@data) eq 2) {
                   5281:             $title = $data[1];
                   5282:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5283:         } else {
                   5284:             ($setuname,$setudom,$title) = @data;
                   5285:         }
                   5286:         $blocks = { 'com' => 'on' };
                   5287:     }
                   5288:     return ($setuname,$setudom,$title,$blocks);
                   5289: }
                   5290: 
1.854     kalberla 5291: sub blocking_status {
1.1189    raeburn  5292:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  5293:     my %setters;
1.890     droeschl 5294: 
1.1061    raeburn  5295: # check for active blocking
1.1062    raeburn  5296:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  5297:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  5298:     my $blocked = 0;
                   5299:     if ($startblock && $endblock) {
                   5300:         $blocked = 1;
                   5301:     }
1.890     droeschl 5302: 
1.1061    raeburn  5303: # caller just wants to know whether a block is active
                   5304:     if (!wantarray) { return $blocked; }
                   5305: 
                   5306: # build a link to a popup window containing the details
                   5307:     my $querystring  = "?activity=$activity";
                   5308: # $uname and $udom decide whose portfolio the user is trying to look at
1.1232    raeburn  5309:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5310:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5311:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5312:     } elsif ($activity eq 'docs') {
                   5313:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   5314:     }
1.1061    raeburn  5315: 
                   5316:     my $output .= <<'END_MYBLOCK';
                   5317: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5318:     var options = "width=" + w + ",height=" + h + ",";
                   5319:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5320:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5321:     var newWin = window.open(url, wdwName, options);
                   5322:     newWin.focus();
                   5323: }
1.890     droeschl 5324: END_MYBLOCK
1.854     kalberla 5325: 
1.1061    raeburn  5326:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5327:   
1.1061    raeburn  5328:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5329:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5330:     my $class = 'LC_comblock';
1.1062    raeburn  5331:     if ($activity eq 'docs') {
                   5332:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5333:         $class = '';
1.1063    raeburn  5334:     } elsif ($activity eq 'printout') {
                   5335:         $text = &mt('Printing Blocked');
1.1232    raeburn  5336:     } elsif ($activity eq 'passwd') {
                   5337:         $text = &mt('Password Changing Blocked');
1.1282    raeburn  5338:     } elsif ($activity eq 'alert') {
                   5339:         $text = &mt('Checking Critical Messages Blocked');
                   5340:     } elsif ($activity eq 'reinit') {
                   5341:         $text = &mt('Checking Course Update Blocked');
1.1062    raeburn  5342:     }
1.1061    raeburn  5343:     $output .= <<"END_BLOCK";
1.1217    raeburn  5344: <div class='$class'>
1.869     kalberla 5345:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5346:   title='$text'>
                   5347:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5348:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5349:   title='$text'>$text</a>
1.867     kalberla 5350: </div>
                   5351: 
                   5352: END_BLOCK
1.474     raeburn  5353: 
1.1061    raeburn  5354:     return ($blocked, $output);
1.854     kalberla 5355: }
1.490     raeburn  5356: 
1.60      matthew  5357: ###############################################
                   5358: 
1.682     raeburn  5359: sub check_ip_acc {
1.1201    raeburn  5360:     my ($acc,$clientip)=@_;
1.682     raeburn  5361:     &Apache::lonxml::debug("acc is $acc");
                   5362:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5363:         return 1;
                   5364:     }
1.1219    raeburn  5365:     my $allowed;
1.1252    raeburn  5366:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  5367: 
                   5368:     my $name;
1.1219    raeburn  5369:     my %access = (
                   5370:                      allowfrom => 1,
                   5371:                      denyfrom  => 0,
                   5372:                  );
                   5373:     my @allows;
                   5374:     my @denies;
                   5375:     foreach my $item (split(',',$acc)) {
                   5376:         $item =~ s/^\s*//;
                   5377:         $item =~ s/\s*$//;
                   5378:         my $pattern;
                   5379:         if ($item =~ /^\!(.+)$/) {
                   5380:             push(@denies,$1);
                   5381:         } else {
                   5382:             push(@allows,$item);
                   5383:         }
                   5384:    }
                   5385:    my $numdenies = scalar(@denies);
                   5386:    my $numallows = scalar(@allows);
                   5387:    my $count = 0;
                   5388:    foreach my $pattern (@denies,@allows) {
                   5389:         $count ++; 
                   5390:         my $acctype = 'allowfrom';
                   5391:         if ($count <= $numdenies) {
                   5392:             $acctype = 'denyfrom';
                   5393:         }
1.682     raeburn  5394:         if ($pattern =~ /\*$/) {
                   5395:             #35.8.*
                   5396:             $pattern=~s/\*//;
1.1219    raeburn  5397:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5398:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5399:             #35.8.3.[34-56]
                   5400:             my $low=$2;
                   5401:             my $high=$3;
                   5402:             $pattern=$1;
                   5403:             if ($ip =~ /^\Q$pattern\E/) {
                   5404:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5405:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5406:             }
                   5407:         } elsif ($pattern =~ /^\*/) {
                   5408:             #*.msu.edu
                   5409:             $pattern=~s/\*//;
                   5410:             if (!defined($name)) {
                   5411:                 use Socket;
                   5412:                 my $netaddr=inet_aton($ip);
                   5413:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5414:             }
1.1219    raeburn  5415:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5416:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5417:             #127.0.0.1
1.1219    raeburn  5418:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5419:         } else {
                   5420:             #some.name.com
                   5421:             if (!defined($name)) {
                   5422:                 use Socket;
                   5423:                 my $netaddr=inet_aton($ip);
                   5424:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5425:             }
1.1219    raeburn  5426:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5427:         }
                   5428:         if ($allowed =~ /^(0|1)$/) { last; }
                   5429:     }
                   5430:     if ($allowed eq '') {
                   5431:         if ($numdenies && !$numallows) {
                   5432:             $allowed = 1;
                   5433:         } else {
                   5434:             $allowed = 0;
1.682     raeburn  5435:         }
                   5436:     }
                   5437:     return $allowed;
                   5438: }
                   5439: 
                   5440: ###############################################
                   5441: 
1.60      matthew  5442: =pod
                   5443: 
1.112     bowersj2 5444: =head1 Domain Template Functions
                   5445: 
                   5446: =over 4
                   5447: 
                   5448: =item * &determinedomain()
1.60      matthew  5449: 
                   5450: Inputs: $domain (usually will be undef)
                   5451: 
1.63      www      5452: Returns: Determines which domain should be used for designs
1.60      matthew  5453: 
                   5454: =cut
1.54      www      5455: 
1.60      matthew  5456: ###############################################
1.63      www      5457: sub determinedomain {
                   5458:     my $domain=shift;
1.531     albertel 5459:     if (! $domain) {
1.60      matthew  5460:         # Determine domain if we have not been given one
1.893     raeburn  5461:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5462:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5463:         if ($env{'request.role.domain'}) { 
                   5464:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5465:         }
                   5466:     }
1.63      www      5467:     return $domain;
                   5468: }
                   5469: ###############################################
1.517     raeburn  5470: 
1.518     albertel 5471: sub devalidate_domconfig_cache {
                   5472:     my ($udom)=@_;
                   5473:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5474: }
                   5475: 
                   5476: # ---------------------- Get domain configuration for a domain
                   5477: sub get_domainconf {
                   5478:     my ($udom) = @_;
                   5479:     my $cachetime=1800;
                   5480:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5481:     if (defined($cached)) { return %{$result}; }
                   5482: 
                   5483:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5484: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5485:     my (%designhash,%legacy);
1.518     albertel 5486:     if (keys(%domconfig) > 0) {
                   5487:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5488:             if (keys(%{$domconfig{'login'}})) {
                   5489:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5490:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5491:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5492:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5493:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5494:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5495:                                         if ($key eq 'loginvia') {
                   5496:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5497:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5498:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5499:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5500: 
                   5501:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5502:                                                 } else {
                   5503:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5504:                                                 }
1.948     raeburn  5505:                                             }
1.1208    raeburn  5506:                                         } elsif ($key eq 'headtag') {
                   5507:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5508:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5509:                                             }
1.946     raeburn  5510:                                         }
1.1208    raeburn  5511:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5512:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5513:                                         }
1.946     raeburn  5514:                                     }
                   5515:                                 }
                   5516:                             }
                   5517:                         } else {
                   5518:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5519:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5520:                                     $domconfig{'login'}{$key}{$img};
                   5521:                             }
1.699     raeburn  5522:                         }
                   5523:                     } else {
                   5524:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5525:                     }
1.632     raeburn  5526:                 }
                   5527:             } else {
                   5528:                 $legacy{'login'} = 1;
1.518     albertel 5529:             }
1.632     raeburn  5530:         } else {
                   5531:             $legacy{'login'} = 1;
1.518     albertel 5532:         }
                   5533:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5534:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5535:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5536:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5537:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5538:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5539:                         }
1.518     albertel 5540:                     }
                   5541:                 }
1.632     raeburn  5542:             } else {
                   5543:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5544:             }
1.632     raeburn  5545:         } else {
                   5546:             $legacy{'rolecolors'} = 1;
1.518     albertel 5547:         }
1.948     raeburn  5548:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5549:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5550:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5551:             }
                   5552:         }
1.632     raeburn  5553:         if (keys(%legacy) > 0) {
                   5554:             my %legacyhash = &get_legacy_domconf($udom);
                   5555:             foreach my $item (keys(%legacyhash)) {
                   5556:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5557:                     if ($legacy{'login'}) { 
                   5558:                         $designhash{$item} = $legacyhash{$item};
                   5559:                     }
                   5560:                 } else {
                   5561:                     if ($legacy{'rolecolors'}) {
                   5562:                         $designhash{$item} = $legacyhash{$item};
                   5563:                     }
1.518     albertel 5564:                 }
                   5565:             }
                   5566:         }
1.632     raeburn  5567:     } else {
                   5568:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5569:     }
                   5570:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5571: 				  $cachetime);
                   5572:     return %designhash;
                   5573: }
                   5574: 
1.632     raeburn  5575: sub get_legacy_domconf {
                   5576:     my ($udom) = @_;
                   5577:     my %legacyhash;
                   5578:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5579:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5580:     if (-e $designfile) {
                   5581:         if ( open (my $fh,"<$designfile") ) {
                   5582:             while (my $line = <$fh>) {
                   5583:                 next if ($line =~ /^\#/);
                   5584:                 chomp($line);
                   5585:                 my ($key,$val)=(split(/\=/,$line));
                   5586:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5587:             }
                   5588:             close($fh);
                   5589:         }
                   5590:     }
1.1026    raeburn  5591:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5592:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5593:     }
                   5594:     return %legacyhash;
                   5595: }
                   5596: 
1.63      www      5597: =pod
                   5598: 
1.112     bowersj2 5599: =item * &domainlogo()
1.63      www      5600: 
                   5601: Inputs: $domain (usually will be undef)
                   5602: 
                   5603: Returns: A link to a domain logo, if the domain logo exists.
                   5604: If the domain logo does not exist, a description of the domain.
                   5605: 
                   5606: =cut
1.112     bowersj2 5607: 
1.63      www      5608: ###############################################
                   5609: sub domainlogo {
1.517     raeburn  5610:     my $domain = &determinedomain(shift);
1.518     albertel 5611:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5612:     # See if there is a logo
                   5613:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5614:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5615:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5616: 	    if ($imgsrc =~ m{^/res/}) {
                   5617: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5618: 		&Apache::lonnet::repcopy($local_name);
                   5619: 	    }
                   5620: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5621:         } 
                   5622:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5623:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5624:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5625:     } else {
1.60      matthew  5626:         return '';
1.59      www      5627:     }
                   5628: }
1.63      www      5629: ##############################################
                   5630: 
                   5631: =pod
                   5632: 
1.112     bowersj2 5633: =item * &designparm()
1.63      www      5634: 
                   5635: Inputs: $which parameter; $domain (usually will be undef)
                   5636: 
                   5637: Returns: value of designparamter $which
                   5638: 
                   5639: =cut
1.112     bowersj2 5640: 
1.397     albertel 5641: 
1.400     albertel 5642: ##############################################
1.397     albertel 5643: sub designparm {
                   5644:     my ($which,$domain)=@_;
                   5645:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5646:         return $env{'environment.color.'.$which};
1.96      www      5647:     }
1.63      www      5648:     $domain=&determinedomain($domain);
1.1016    raeburn  5649:     my %domdesign;
                   5650:     unless ($domain eq 'public') {
                   5651:         %domdesign = &get_domainconf($domain);
                   5652:     }
1.520     raeburn  5653:     my $output;
1.517     raeburn  5654:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5655:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5656:     } else {
1.520     raeburn  5657:         $output = $defaultdesign{$which};
                   5658:     }
                   5659:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5660:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5661:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5662:             if ($output =~ m{^/res/}) {
                   5663:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5664:                 &Apache::lonnet::repcopy($local_name);
                   5665:             }
1.520     raeburn  5666:             $output = &lonhttpdurl($output);
                   5667:         }
1.63      www      5668:     }
1.520     raeburn  5669:     return $output;
1.63      www      5670: }
1.59      www      5671: 
1.822     bisitz   5672: ##############################################
                   5673: =pod
                   5674: 
1.832     bisitz   5675: =item * &authorspace()
                   5676: 
1.1028    raeburn  5677: Inputs: $url (usually will be undef).
1.832     bisitz   5678: 
1.1132    raeburn  5679: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5680:          directory being viewed (or for which action is being taken). 
                   5681:          If $url is provided, and begins /priv/<domain>/<uname>
                   5682:          the path will be that portion of the $context argument.
                   5683:          Otherwise the path will be for the author space of the current
                   5684:          user when the current role is author, or for that of the 
                   5685:          co-author/assistant co-author space when the current role 
                   5686:          is co-author or assistant co-author.
1.832     bisitz   5687: 
                   5688: =cut
                   5689: 
                   5690: sub authorspace {
1.1028    raeburn  5691:     my ($url) = @_;
                   5692:     if ($url ne '') {
                   5693:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5694:            return $1;
                   5695:         }
                   5696:     }
1.832     bisitz   5697:     my $caname = '';
1.1024    www      5698:     my $cadom = '';
1.1028    raeburn  5699:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5700:         ($cadom,$caname) =
1.832     bisitz   5701:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5702:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5703:         $caname = $env{'user.name'};
1.1024    www      5704:         $cadom = $env{'user.domain'};
1.832     bisitz   5705:     }
1.1028    raeburn  5706:     if (($caname ne '') && ($cadom ne '')) {
                   5707:         return "/priv/$cadom/$caname/";
                   5708:     }
                   5709:     return;
1.832     bisitz   5710: }
                   5711: 
                   5712: ##############################################
                   5713: =pod
                   5714: 
1.822     bisitz   5715: =item * &head_subbox()
                   5716: 
                   5717: Inputs: $content (contains HTML code with page functions, etc.)
                   5718: 
                   5719: Returns: HTML div with $content
                   5720:          To be included in page header
                   5721: 
                   5722: =cut
                   5723: 
                   5724: sub head_subbox {
                   5725:     my ($content)=@_;
                   5726:     my $output =
1.993     raeburn  5727:         '<div class="LC_head_subbox">'
1.822     bisitz   5728:        .$content
                   5729:        .'</div>'
                   5730: }
                   5731: 
                   5732: ##############################################
                   5733: =pod
                   5734: 
                   5735: =item * &CSTR_pageheader()
                   5736: 
1.1026    raeburn  5737: Input: (optional) filename from which breadcrumb trail is built.
                   5738:        In most cases no input as needed, as $env{'request.filename'}
                   5739:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5740: 
                   5741: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5742:          To be included on Authoring Space pages
1.822     bisitz   5743: 
                   5744: =cut
                   5745: 
                   5746: sub CSTR_pageheader {
1.1026    raeburn  5747:     my ($trailfile) = @_;
                   5748:     if ($trailfile eq '') {
                   5749:         $trailfile = $env{'request.filename'};
                   5750:     }
                   5751: 
                   5752: # this is for resources; directories have customtitle, and crumbs
                   5753: # and select recent are created in lonpubdir.pm
                   5754: 
                   5755:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5756:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5757:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5758:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5759:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5760: 
                   5761:     my $parentpath = '';
                   5762:     my $lastitem = '';
                   5763:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5764:         $parentpath = $1;
                   5765:         $lastitem = $2;
                   5766:     } else {
                   5767:         $lastitem = $thisdisfn;
                   5768:     }
1.921     bisitz   5769: 
1.1246    raeburn  5770:     my ($crsauthor,$title);
                   5771:     if (($env{'request.course.id'}) &&
                   5772:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  5773:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  5774:         $crsauthor = 1;
                   5775:         $title = &mt('Course Authoring Space');
                   5776:     } else {
                   5777:         $title = &mt('Authoring Space');
                   5778:     }
                   5779: 
1.921     bisitz   5780:     my $output =
1.822     bisitz   5781:          '<div>'
                   5782:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  5783:         .'<b>'.$title.'</b> '
1.822     bisitz   5784:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5785:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5786:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5787: 
                   5788:     if ($lastitem) {
                   5789:         $output .=
                   5790:              '<span class="LC_filename">'
                   5791:             .$lastitem
                   5792:             .'</span>';
                   5793:     }
1.1245    raeburn  5794: 
1.1246    raeburn  5795:     if ($crsauthor) {
                   5796:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   5797:     } else {
                   5798:         $output .=
                   5799:              '<br />'
                   5800:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5801:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5802:             .'</form>'
                   5803:             .&Apache::lonmenu::constspaceform();
                   5804:     }
                   5805:     $output .= '</div>';
1.921     bisitz   5806: 
                   5807:     return $output;
1.822     bisitz   5808: }
                   5809: 
1.60      matthew  5810: ###############################################
                   5811: ###############################################
                   5812: 
                   5813: =pod
                   5814: 
1.112     bowersj2 5815: =back
                   5816: 
1.549     albertel 5817: =head1 HTML Helpers
1.112     bowersj2 5818: 
                   5819: =over 4
                   5820: 
                   5821: =item * &bodytag()
1.60      matthew  5822: 
                   5823: Returns a uniform header for LON-CAPA web pages.
                   5824: 
                   5825: Inputs: 
                   5826: 
1.112     bowersj2 5827: =over 4
                   5828: 
                   5829: =item * $title, A title to be displayed on the page.
                   5830: 
                   5831: =item * $function, the current role (can be undef).
                   5832: 
                   5833: =item * $addentries, extra parameters for the <body> tag.
                   5834: 
                   5835: =item * $bodyonly, if defined, only return the <body> tag.
                   5836: 
                   5837: =item * $domain, if defined, force a given domain.
                   5838: 
                   5839: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5840:             text interface only)
1.60      matthew  5841: 
1.814     bisitz   5842: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5843:                      navigational links
1.317     albertel 5844: 
1.338     albertel 5845: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5846: 
1.460     albertel 5847: =item * $args, optional argument valid values are
                   5848:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  5849:             use_absolute     -> for external resource or syllabus, this will
                   5850:                                 contain https://<hostname> if server uses
                   5851:                                 https (as per hosts.tab), but request is for http
                   5852:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5853: 
1.1096    raeburn  5854: =item * $advtoolsref, optional argument, ref to an array containing
                   5855:             inlineremote items to be added in "Functions" menu below
                   5856:             breadcrumbs.
                   5857: 
1.112     bowersj2 5858: =back
                   5859: 
1.60      matthew  5860: Returns: A uniform header for LON-CAPA web pages.  
                   5861: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5862: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5863: other decorations will be returned.
                   5864: 
                   5865: =cut
                   5866: 
1.54      www      5867: sub bodytag {
1.831     bisitz   5868:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5869:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5870: 
1.954     raeburn  5871:     my $public;
                   5872:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5873:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5874:         $public = 1;
                   5875:     }
1.460     albertel 5876:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5877:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  5878:     my $hostname = $args->{'hostname'};
1.339     albertel 5879: 
1.183     matthew  5880:     $function = &get_users_function() if (!$function);
1.339     albertel 5881:     my $img =    &designparm($function.'.img',$domain);
                   5882:     my $font =   &designparm($function.'.font',$domain);
                   5883:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5884: 
1.803     bisitz   5885:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5886: 		   'bgcolor' => $pgbg,
1.339     albertel 5887: 		   'text'    => $font,
                   5888:                    'alink'   => &designparm($function.'.alink',$domain),
                   5889: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5890: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5891:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5892: 
1.63      www      5893:  # role and realm
1.1178    raeburn  5894:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5895:     if ($realm) {
                   5896:         $realm = '/'.$realm;
                   5897:     }
1.378     raeburn  5898:     if ($role  eq 'ca') {
1.479     albertel 5899:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5900:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5901:     } 
1.55      www      5902: # realm
1.258     albertel 5903:     if ($env{'request.course.id'}) {
1.378     raeburn  5904:         if ($env{'request.role'} !~ /^cr/) {
                   5905:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  5906:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  5907:             if ($env{'request.role.desc'}) {
                   5908:                 $role = $env{'request.role.desc'};
                   5909:             } else {
                   5910:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5911:             }
1.1257    raeburn  5912:         } else {
                   5913:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  5914:         }
1.898     raeburn  5915:         if ($env{'request.course.sec'}) {
                   5916:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5917:         }   
1.359     albertel 5918: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5919:     } else {
                   5920:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5921:     }
1.433     albertel 5922: 
1.359     albertel 5923:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5924: 
1.438     albertel 5925:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5926: 
1.101     www      5927: # construct main body tag
1.359     albertel 5928:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  5929: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5930: 
1.1131    raeburn  5931:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5932: 
1.1130    raeburn  5933:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5934:         return $bodytag;
1.1130    raeburn  5935:     }
1.359     albertel 5936: 
1.954     raeburn  5937:     if ($public) {
1.433     albertel 5938: 	undef($role);
                   5939:     }
1.359     albertel 5940:     
1.762     bisitz   5941:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5942:     #
                   5943:     # Extra info if you are the DC
                   5944:     my $dc_info = '';
                   5945:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5946:                         $env{'course.'.$env{'request.course.id'}.
                   5947:                                  '.domain'}.'/'})) {
                   5948:         my $cid = $env{'request.course.id'};
1.917     raeburn  5949:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5950:         $dc_info =~ s/\s+$//;
1.359     albertel 5951:     }
                   5952: 
1.1237    raeburn  5953:     my $crstype;
                   5954:     if ($env{'request.course.id'}) {
                   5955:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   5956:     } elsif ($args->{'crstype'}) {
                   5957:         $crstype = $args->{'crstype'};
                   5958:     }
                   5959:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   5960:         undef($role);
                   5961:     } else {
1.1242    raeburn  5962:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  5963:     }
1.853     droeschl 5964: 
1.903     droeschl 5965:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5966: 
                   5967:         #    if ($env{'request.state'} eq 'construct') {
                   5968:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5969:         #    }
                   5970: 
1.1130    raeburn  5971:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5972:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5973: 
1.1237    raeburn  5974:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
1.359     albertel 5975: 
1.916     droeschl 5976:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5977:              if ($dc_info) {
                   5978:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5979:              }
1.1130    raeburn  5980:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5981:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5982:             return $bodytag;
                   5983:         }
1.894     droeschl 5984: 
1.927     raeburn  5985:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5986:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5987:         }
1.916     droeschl 5988: 
1.1130    raeburn  5989:         $bodytag .= $right;
1.852     droeschl 5990: 
1.917     raeburn  5991:         if ($dc_info) {
                   5992:             $dc_info = &dc_courseid_toggle($dc_info);
                   5993:         }
                   5994:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5995: 
1.1169    raeburn  5996:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5997:         if ($args->{'no_secondary_menu'}) {
                   5998:             return $bodytag;
                   5999:         }
1.1169    raeburn  6000:         #don't show menus for public users
1.954     raeburn  6001:         if (!$public){
1.1154    raeburn  6002:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 6003:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6004:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6005:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6006:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1274    raeburn  6007:                                 $args->{'bread_crumbs'},'','',$hostname);
1.1096    raeburn  6008:             } elsif ($forcereg) {
                   6009:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6010:                                                             $args->{'group'},
1.1274    raeburn  6011:                                                             $args->{'hide_buttons'},
                   6012:                                                             $hostname);
1.1096    raeburn  6013:             } else {
                   6014:                 $bodytag .= 
                   6015:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6016:                                                         $forcereg,$args->{'group'},
                   6017:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6018:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6019:             }
1.903     droeschl 6020:         }else{
                   6021:             # this is to seperate menu from content when there's no secondary
                   6022:             # menu. Especially needed for public accessible ressources.
                   6023:             $bodytag .= '<hr style="clear:both" />';
                   6024:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6025:         }
1.903     droeschl 6026: 
1.235     raeburn  6027:         return $bodytag;
1.182     matthew  6028: }
                   6029: 
1.917     raeburn  6030: sub dc_courseid_toggle {
                   6031:     my ($dc_info) = @_;
1.980     raeburn  6032:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6033:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6034:            &mt('(More ...)').'</a></span>'.
                   6035:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6036: }
                   6037: 
1.330     albertel 6038: sub make_attr_string {
                   6039:     my ($register,$attr_ref) = @_;
                   6040: 
                   6041:     if ($attr_ref && !ref($attr_ref)) {
                   6042: 	die("addentries Must be a hash ref ".
                   6043: 	    join(':',caller(1))." ".
                   6044: 	    join(':',caller(0))." ");
                   6045:     }
                   6046: 
                   6047:     if ($register) {
1.339     albertel 6048: 	my ($on_load,$on_unload);
                   6049: 	foreach my $key (keys(%{$attr_ref})) {
                   6050: 	    if      (lc($key) eq 'onload') {
                   6051: 		$on_load.=$attr_ref->{$key}.';';
                   6052: 		delete($attr_ref->{$key});
                   6053: 
                   6054: 	    } elsif (lc($key) eq 'onunload') {
                   6055: 		$on_unload.=$attr_ref->{$key}.';';
                   6056: 		delete($attr_ref->{$key});
                   6057: 	    }
                   6058: 	}
1.953     droeschl 6059: 	$attr_ref->{'onload'}  = $on_load;
                   6060: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6061:     }
1.339     albertel 6062: 
1.330     albertel 6063:     my $attr_string;
1.1159    raeburn  6064:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6065: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6066:     }
                   6067:     return $attr_string;
                   6068: }
                   6069: 
                   6070: 
1.182     matthew  6071: ###############################################
1.251     albertel 6072: ###############################################
                   6073: 
                   6074: =pod
                   6075: 
                   6076: =item * &endbodytag()
                   6077: 
                   6078: Returns a uniform footer for LON-CAPA web pages.
                   6079: 
1.635     raeburn  6080: Inputs: 1 - optional reference to an args hash
                   6081: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6082: a 'Continue' link is not displayed if the page contains an
                   6083: internal redirect in the <head></head> section,
                   6084: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6085: 
                   6086: =cut
                   6087: 
                   6088: sub endbodytag {
1.635     raeburn  6089:     my ($args) = @_;
1.1080    raeburn  6090:     my $endbodytag;
                   6091:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6092:         $endbodytag='</body>';
                   6093:     }
1.315     albertel 6094:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6095:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6096: 	    $endbodytag=
                   6097: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6098: 	        &mt('Continue').'</a>'.
                   6099: 	        $endbodytag;
                   6100:         }
1.315     albertel 6101:     }
1.251     albertel 6102:     return $endbodytag;
                   6103: }
                   6104: 
1.352     albertel 6105: =pod
                   6106: 
                   6107: =item * &standard_css()
                   6108: 
                   6109: Returns a style sheet
                   6110: 
                   6111: Inputs: (all optional)
                   6112:             domain         -> force to color decorate a page for a specific
                   6113:                                domain
                   6114:             function       -> force usage of a specific rolish color scheme
                   6115:             bgcolor        -> override the default page bgcolor
                   6116: 
                   6117: =cut
                   6118: 
1.343     albertel 6119: sub standard_css {
1.345     albertel 6120:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6121:     $function  = &get_users_function() if (!$function);
                   6122:     my $img    = &designparm($function.'.img',   $domain);
                   6123:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6124:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6125:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6126: #second colour for later usage
1.345     albertel 6127:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6128:     my $pgbg_or_bgcolor =
                   6129: 	         $bgcolor ||
1.352     albertel 6130: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6131:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6132:     my $alink  = &designparm($function.'.alink', $domain);
                   6133:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6134:     my $link   = &designparm($function.'.link',  $domain);
                   6135: 
1.602     albertel 6136:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6137:     my $mono                 = 'monospace';
1.850     bisitz   6138:     my $data_table_head      = $sidebg;
                   6139:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6140:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6141:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6142:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6143:     my $mail_new             = '#FFBB77';
                   6144:     my $mail_new_hover       = '#DD9955';
                   6145:     my $mail_read            = '#BBBB77';
                   6146:     my $mail_read_hover      = '#999944';
                   6147:     my $mail_replied         = '#AAAA88';
                   6148:     my $mail_replied_hover   = '#888855';
                   6149:     my $mail_other           = '#99BBBB';
                   6150:     my $mail_other_hover     = '#669999';
1.391     albertel 6151:     my $table_header         = '#DDDDDD';
1.489     raeburn  6152:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6153:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6154:     my $button_hover         = '#BF2317';
1.392     albertel 6155: 
1.608     albertel 6156:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6157:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6158:                                              : '0 3px 0 4px';
1.448     albertel 6159: 
1.523     albertel 6160: 
1.343     albertel 6161:     return <<END;
1.947     droeschl 6162: 
                   6163: /* needed for iframe to allow 100% height in FF */
                   6164: body, html { 
                   6165:     margin: 0;
                   6166:     padding: 0 0.5%;
                   6167:     height: 99%; /* to avoid scrollbars */
                   6168: }
                   6169: 
1.795     www      6170: body {
1.911     bisitz   6171:   font-family: $sans;
                   6172:   line-height:130%;
                   6173:   font-size:0.83em;
                   6174:   color:$font;
1.795     www      6175: }
                   6176: 
1.959     onken    6177: a:focus,
                   6178: a:focus img {
1.795     www      6179:   color: red;
                   6180: }
1.698     harmsja  6181: 
1.911     bisitz   6182: form, .inline {
                   6183:   display: inline;
1.795     www      6184: }
1.721     harmsja  6185: 
1.795     www      6186: .LC_right {
1.911     bisitz   6187:   text-align:right;
1.795     www      6188: }
                   6189: 
                   6190: .LC_middle {
1.911     bisitz   6191:   vertical-align:middle;
1.795     www      6192: }
1.721     harmsja  6193: 
1.1130    raeburn  6194: .LC_floatleft {
                   6195:   float: left;
                   6196: }
                   6197: 
                   6198: .LC_floatright {
                   6199:   float: right;
                   6200: }
                   6201: 
1.911     bisitz   6202: .LC_400Box {
                   6203:   width:400px;
                   6204: }
1.721     harmsja  6205: 
1.947     droeschl 6206: .LC_iframecontainer {
                   6207:     width: 98%;
                   6208:     margin: 0;
                   6209:     position: fixed;
                   6210:     top: 8.5em;
                   6211:     bottom: 0;
                   6212: }
                   6213: 
                   6214: .LC_iframecontainer iframe{
                   6215:     border: none;
                   6216:     width: 100%;
                   6217:     height: 100%;
                   6218: }
                   6219: 
1.778     bisitz   6220: .LC_filename {
                   6221:   font-family: $mono;
                   6222:   white-space:pre;
1.921     bisitz   6223:   font-size: 120%;
1.778     bisitz   6224: }
                   6225: 
                   6226: .LC_fileicon {
                   6227:   border: none;
                   6228:   height: 1.3em;
                   6229:   vertical-align: text-bottom;
                   6230:   margin-right: 0.3em;
                   6231:   text-decoration:none;
                   6232: }
                   6233: 
1.1008    www      6234: .LC_setting {
                   6235:   text-decoration:underline;
                   6236: }
                   6237: 
1.350     albertel 6238: .LC_error {
                   6239:   color: red;
                   6240: }
1.795     www      6241: 
1.1097    bisitz   6242: .LC_warning {
                   6243:   color: darkorange;
                   6244: }
                   6245: 
1.457     albertel 6246: .LC_diff_removed {
1.733     bisitz   6247:   color: red;
1.394     albertel 6248: }
1.532     albertel 6249: 
                   6250: .LC_info,
1.457     albertel 6251: .LC_success,
                   6252: .LC_diff_added {
1.350     albertel 6253:   color: green;
                   6254: }
1.795     www      6255: 
1.802     bisitz   6256: div.LC_confirm_box {
                   6257:   background-color: #FAFAFA;
                   6258:   border: 1px solid $lg_border_color;
                   6259:   margin-right: 0;
                   6260:   padding: 5px;
                   6261: }
                   6262: 
                   6263: div.LC_confirm_box .LC_error img,
                   6264: div.LC_confirm_box .LC_success img {
                   6265:   vertical-align: middle;
                   6266: }
                   6267: 
1.1242    raeburn  6268: .LC_maxwidth {
                   6269:   max-width: 100%;
                   6270:   height: auto;
                   6271: }
                   6272: 
1.1243    raeburn  6273: .LC_textsize_mobile {
                   6274:   \@media only screen and (max-device-width: 480px) {
                   6275:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6276:   }
                   6277: }
                   6278: 
1.440     albertel 6279: .LC_icon {
1.771     droeschl 6280:   border: none;
1.790     droeschl 6281:   vertical-align: middle;
1.771     droeschl 6282: }
                   6283: 
1.543     albertel 6284: .LC_docs_spacer {
                   6285:   width: 25px;
                   6286:   height: 1px;
1.771     droeschl 6287:   border: none;
1.543     albertel 6288: }
1.346     albertel 6289: 
1.532     albertel 6290: .LC_internal_info {
1.735     bisitz   6291:   color: #999999;
1.532     albertel 6292: }
                   6293: 
1.794     www      6294: .LC_discussion {
1.1050    www      6295:   background: $data_table_dark;
1.911     bisitz   6296:   border: 1px solid black;
                   6297:   margin: 2px;
1.794     www      6298: }
                   6299: 
                   6300: .LC_disc_action_left {
1.1050    www      6301:   background: $sidebg;
1.911     bisitz   6302:   text-align: left;
1.1050    www      6303:   padding: 4px;
                   6304:   margin: 2px;
1.794     www      6305: }
                   6306: 
                   6307: .LC_disc_action_right {
1.1050    www      6308:   background: $sidebg;
1.911     bisitz   6309:   text-align: right;
1.1050    www      6310:   padding: 4px;
                   6311:   margin: 2px;
1.794     www      6312: }
                   6313: 
                   6314: .LC_disc_new_item {
1.911     bisitz   6315:   background: white;
                   6316:   border: 2px solid red;
1.1050    www      6317:   margin: 4px;
                   6318:   padding: 4px;
1.794     www      6319: }
                   6320: 
                   6321: .LC_disc_old_item {
1.911     bisitz   6322:   background: white;
1.1050    www      6323:   margin: 4px;
                   6324:   padding: 4px;
1.794     www      6325: }
                   6326: 
1.458     albertel 6327: table.LC_pastsubmission {
                   6328:   border: 1px solid black;
                   6329:   margin: 2px;
                   6330: }
                   6331: 
1.924     bisitz   6332: table#LC_menubuttons {
1.345     albertel 6333:   width: 100%;
                   6334:   background: $pgbg;
1.392     albertel 6335:   border: 2px;
1.402     albertel 6336:   border-collapse: separate;
1.803     bisitz   6337:   padding: 0;
1.345     albertel 6338: }
1.392     albertel 6339: 
1.801     tempelho 6340: table#LC_title_bar a {
                   6341:   color: $fontmenu;
                   6342: }
1.836     bisitz   6343: 
1.807     droeschl 6344: table#LC_title_bar {
1.819     tempelho 6345:   clear: both;
1.836     bisitz   6346:   display: none;
1.807     droeschl 6347: }
                   6348: 
1.795     www      6349: table#LC_title_bar,
1.933     droeschl 6350: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6351: table#LC_title_bar.LC_with_remote {
1.359     albertel 6352:   width: 100%;
1.392     albertel 6353:   border-color: $pgbg;
                   6354:   border-style: solid;
                   6355:   border-width: $border;
1.379     albertel 6356:   background: $pgbg;
1.801     tempelho 6357:   color: $fontmenu;
1.392     albertel 6358:   border-collapse: collapse;
1.803     bisitz   6359:   padding: 0;
1.819     tempelho 6360:   margin: 0;
1.359     albertel 6361: }
1.795     www      6362: 
1.933     droeschl 6363: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6364:     margin: 0;
                   6365:     padding: 0;
1.933     droeschl 6366:     position: relative;
                   6367:     list-style: none;
1.913     droeschl 6368: }
1.933     droeschl 6369: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6370:     display: inline;
                   6371: }
1.933     droeschl 6372: 
                   6373: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6374:     padding: 0;
1.933     droeschl 6375:     margin: 0;
                   6376:     float: left;
1.913     droeschl 6377: }
1.933     droeschl 6378: .LC_breadcrumb_tools_tools {
                   6379:     padding: 0;
                   6380:     margin: 0;
1.913     droeschl 6381:     float: right;
                   6382: }
                   6383: 
1.1240    raeburn  6384: .LC_placement_prog {
                   6385:     padding-right: 20px;
                   6386:     font-weight: bold;
                   6387:     font-size: 90%;
                   6388: }
                   6389: 
1.359     albertel 6390: table#LC_title_bar td {
                   6391:   background: $tabbg;
                   6392: }
1.795     www      6393: 
1.911     bisitz   6394: table#LC_menubuttons img {
1.803     bisitz   6395:   border: none;
1.346     albertel 6396: }
1.795     www      6397: 
1.842     droeschl 6398: .LC_breadcrumbs_component {
1.911     bisitz   6399:   float: right;
                   6400:   margin: 0 1em;
1.357     albertel 6401: }
1.842     droeschl 6402: .LC_breadcrumbs_component img {
1.911     bisitz   6403:   vertical-align: middle;
1.777     tempelho 6404: }
1.795     www      6405: 
1.1243    raeburn  6406: .LC_breadcrumbs_hoverable {
                   6407:   background: $sidebg;
                   6408: }
                   6409: 
1.383     albertel 6410: td.LC_table_cell_checkbox {
                   6411:   text-align: center;
                   6412: }
1.795     www      6413: 
                   6414: .LC_fontsize_small {
1.911     bisitz   6415:   font-size: 70%;
1.705     tempelho 6416: }
                   6417: 
1.844     bisitz   6418: #LC_breadcrumbs {
1.911     bisitz   6419:   clear:both;
                   6420:   background: $sidebg;
                   6421:   border-bottom: 1px solid $lg_border_color;
                   6422:   line-height: 2.5em;
1.933     droeschl 6423:   overflow: hidden;
1.911     bisitz   6424:   margin: 0;
                   6425:   padding: 0;
1.995     raeburn  6426:   text-align: left;
1.819     tempelho 6427: }
1.862     bisitz   6428: 
1.1098    bisitz   6429: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6430:   clear:both;
                   6431:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6432:   border: 1px solid $sidebg;
1.1098    bisitz   6433:   margin: 0 0 10px 0;
1.966     bisitz   6434:   padding: 3px;
1.995     raeburn  6435:   text-align: left;
1.822     bisitz   6436: }
                   6437: 
1.795     www      6438: .LC_fontsize_medium {
1.911     bisitz   6439:   font-size: 85%;
1.705     tempelho 6440: }
                   6441: 
1.795     www      6442: .LC_fontsize_large {
1.911     bisitz   6443:   font-size: 120%;
1.705     tempelho 6444: }
                   6445: 
1.346     albertel 6446: .LC_menubuttons_inline_text {
                   6447:   color: $font;
1.698     harmsja  6448:   font-size: 90%;
1.701     harmsja  6449:   padding-left:3px;
1.346     albertel 6450: }
                   6451: 
1.934     droeschl 6452: .LC_menubuttons_inline_text img{
                   6453:   vertical-align: middle;
                   6454: }
                   6455: 
1.1051    www      6456: li.LC_menubuttons_inline_text img {
1.951     onken    6457:   cursor:pointer;
1.1002    droeschl 6458:   text-decoration: none;
1.951     onken    6459: }
                   6460: 
1.526     www      6461: .LC_menubuttons_link {
                   6462:   text-decoration: none;
                   6463: }
1.795     www      6464: 
1.522     albertel 6465: .LC_menubuttons_category {
1.521     www      6466:   color: $font;
1.526     www      6467:   background: $pgbg;
1.521     www      6468:   font-size: larger;
                   6469:   font-weight: bold;
                   6470: }
                   6471: 
1.346     albertel 6472: td.LC_menubuttons_text {
1.911     bisitz   6473:   color: $font;
1.346     albertel 6474: }
1.706     harmsja  6475: 
1.346     albertel 6476: .LC_current_location {
                   6477:   background: $tabbg;
                   6478: }
1.795     www      6479: 
1.1286    raeburn  6480: td.LC_zero_height {
                   6481:   line-height: 0; 
                   6482:   cellpadding: 0;
                   6483: }
                   6484: 
1.938     bisitz   6485: table.LC_data_table {
1.347     albertel 6486:   border: 1px solid #000000;
1.402     albertel 6487:   border-collapse: separate;
1.426     albertel 6488:   border-spacing: 1px;
1.610     albertel 6489:   background: $pgbg;
1.347     albertel 6490: }
1.795     www      6491: 
1.422     albertel 6492: .LC_data_table_dense {
                   6493:   font-size: small;
                   6494: }
1.795     www      6495: 
1.507     raeburn  6496: table.LC_nested_outer {
                   6497:   border: 1px solid #000000;
1.589     raeburn  6498:   border-collapse: collapse;
1.803     bisitz   6499:   border-spacing: 0;
1.507     raeburn  6500:   width: 100%;
                   6501: }
1.795     www      6502: 
1.879     raeburn  6503: table.LC_innerpickbox,
1.507     raeburn  6504: table.LC_nested {
1.803     bisitz   6505:   border: none;
1.589     raeburn  6506:   border-collapse: collapse;
1.803     bisitz   6507:   border-spacing: 0;
1.507     raeburn  6508:   width: 100%;
                   6509: }
1.795     www      6510: 
1.911     bisitz   6511: table.LC_data_table tr th,
                   6512: table.LC_calendar tr th,
1.879     raeburn  6513: table.LC_prior_tries tr th,
                   6514: table.LC_innerpickbox tr th {
1.349     albertel 6515:   font-weight: bold;
                   6516:   background-color: $data_table_head;
1.801     tempelho 6517:   color:$fontmenu;
1.701     harmsja  6518:   font-size:90%;
1.347     albertel 6519: }
1.795     www      6520: 
1.879     raeburn  6521: table.LC_innerpickbox tr th,
                   6522: table.LC_innerpickbox tr td {
                   6523:   vertical-align: top;
                   6524: }
                   6525: 
1.711     raeburn  6526: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6527:   background-color: #CCCCCC;
1.711     raeburn  6528:   font-weight: bold;
                   6529:   text-align: left;
                   6530: }
1.795     www      6531: 
1.912     bisitz   6532: table.LC_data_table tr.LC_odd_row > td {
                   6533:   background-color: $data_table_light;
                   6534:   padding: 2px;
                   6535:   vertical-align: top;
                   6536: }
                   6537: 
1.809     bisitz   6538: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6539:   background-color: $data_table_light;
1.912     bisitz   6540:   vertical-align: top;
                   6541: }
                   6542: 
                   6543: table.LC_data_table tr.LC_even_row > td {
                   6544:   background-color: $data_table_dark;
1.425     albertel 6545:   padding: 2px;
1.900     bisitz   6546:   vertical-align: top;
1.347     albertel 6547: }
1.795     www      6548: 
1.809     bisitz   6549: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6550:   background-color: $data_table_dark;
1.900     bisitz   6551:   vertical-align: top;
1.347     albertel 6552: }
1.795     www      6553: 
1.425     albertel 6554: table.LC_data_table tr.LC_data_table_highlight td {
                   6555:   background-color: $data_table_darker;
                   6556: }
1.795     www      6557: 
1.639     raeburn  6558: table.LC_data_table tr td.LC_leftcol_header {
                   6559:   background-color: $data_table_head;
                   6560:   font-weight: bold;
                   6561: }
1.795     www      6562: 
1.451     albertel 6563: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6564: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6565:   font-weight: bold;
                   6566:   font-style: italic;
                   6567:   text-align: center;
                   6568:   padding: 8px;
1.347     albertel 6569: }
1.795     www      6570: 
1.1114    raeburn  6571: table.LC_data_table tr.LC_empty_row td,
                   6572: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6573:   background-color: $sidebg;
                   6574: }
                   6575: 
                   6576: table.LC_nested tr.LC_empty_row td {
                   6577:   background-color: #FFFFFF;
                   6578: }
                   6579: 
1.890     droeschl 6580: table.LC_caption {
                   6581: }
                   6582: 
1.507     raeburn  6583: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6584:   padding: 4ex
                   6585: }
1.795     www      6586: 
1.507     raeburn  6587: table.LC_nested_outer tr th {
                   6588:   font-weight: bold;
1.801     tempelho 6589:   color:$fontmenu;
1.507     raeburn  6590:   background-color: $data_table_head;
1.701     harmsja  6591:   font-size: small;
1.507     raeburn  6592:   border-bottom: 1px solid #000000;
                   6593: }
1.795     www      6594: 
1.507     raeburn  6595: table.LC_nested_outer tr td.LC_subheader {
                   6596:   background-color: $data_table_head;
                   6597:   font-weight: bold;
                   6598:   font-size: small;
                   6599:   border-bottom: 1px solid #000000;
                   6600:   text-align: right;
1.451     albertel 6601: }
1.795     www      6602: 
1.507     raeburn  6603: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6604:   background-color: #CCCCCC;
1.451     albertel 6605:   font-weight: bold;
                   6606:   font-size: small;
1.507     raeburn  6607:   text-align: center;
                   6608: }
1.795     www      6609: 
1.589     raeburn  6610: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6611: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6612:   text-align: left;
1.451     albertel 6613: }
1.795     www      6614: 
1.507     raeburn  6615: table.LC_nested td {
1.735     bisitz   6616:   background-color: #FFFFFF;
1.451     albertel 6617:   font-size: small;
1.507     raeburn  6618: }
1.795     www      6619: 
1.507     raeburn  6620: table.LC_nested_outer tr th.LC_right_item,
                   6621: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6622: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6623: table.LC_nested tr td.LC_right_item {
1.451     albertel 6624:   text-align: right;
                   6625: }
                   6626: 
1.507     raeburn  6627: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6628:   background-color: #EEEEEE;
1.451     albertel 6629: }
                   6630: 
1.473     raeburn  6631: table.LC_createuser {
                   6632: }
                   6633: 
                   6634: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6635:   font-size: small;
1.473     raeburn  6636: }
                   6637: 
                   6638: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6639:   background-color: #CCCCCC;
1.473     raeburn  6640:   font-weight: bold;
                   6641:   text-align: center;
                   6642: }
                   6643: 
1.349     albertel 6644: table.LC_calendar {
                   6645:   border: 1px solid #000000;
                   6646:   border-collapse: collapse;
1.917     raeburn  6647:   width: 98%;
1.349     albertel 6648: }
1.795     www      6649: 
1.349     albertel 6650: table.LC_calendar_pickdate {
                   6651:   font-size: xx-small;
                   6652: }
1.795     www      6653: 
1.349     albertel 6654: table.LC_calendar tr td {
                   6655:   border: 1px solid #000000;
                   6656:   vertical-align: top;
1.917     raeburn  6657:   width: 14%;
1.349     albertel 6658: }
1.795     www      6659: 
1.349     albertel 6660: table.LC_calendar tr td.LC_calendar_day_empty {
                   6661:   background-color: $data_table_dark;
                   6662: }
1.795     www      6663: 
1.779     bisitz   6664: table.LC_calendar tr td.LC_calendar_day_current {
                   6665:   background-color: $data_table_highlight;
1.777     tempelho 6666: }
1.795     www      6667: 
1.938     bisitz   6668: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6669:   background-color: $mail_new;
                   6670: }
1.795     www      6671: 
1.938     bisitz   6672: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6673:   background-color: $mail_new_hover;
                   6674: }
1.795     www      6675: 
1.938     bisitz   6676: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6677:   background-color: $mail_read;
                   6678: }
1.795     www      6679: 
1.938     bisitz   6680: /*
                   6681: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6682:   background-color: $mail_read_hover;
                   6683: }
1.938     bisitz   6684: */
1.795     www      6685: 
1.938     bisitz   6686: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6687:   background-color: $mail_replied;
                   6688: }
1.795     www      6689: 
1.938     bisitz   6690: /*
                   6691: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6692:   background-color: $mail_replied_hover;
                   6693: }
1.938     bisitz   6694: */
1.795     www      6695: 
1.938     bisitz   6696: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6697:   background-color: $mail_other;
                   6698: }
1.795     www      6699: 
1.938     bisitz   6700: /*
                   6701: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6702:   background-color: $mail_other_hover;
                   6703: }
1.938     bisitz   6704: */
1.494     raeburn  6705: 
1.777     tempelho 6706: table.LC_data_table tr > td.LC_browser_file,
                   6707: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6708:   background: #AAEE77;
1.389     albertel 6709: }
1.795     www      6710: 
1.777     tempelho 6711: table.LC_data_table tr > td.LC_browser_file_locked,
                   6712: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6713:   background: #FFAA99;
1.387     albertel 6714: }
1.795     www      6715: 
1.777     tempelho 6716: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6717:   background: #888888;
1.779     bisitz   6718: }
1.795     www      6719: 
1.777     tempelho 6720: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6721: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6722:   background: #F8F866;
1.777     tempelho 6723: }
1.795     www      6724: 
1.696     bisitz   6725: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6726:   background: #E0E8FF;
1.387     albertel 6727: }
1.696     bisitz   6728: 
1.707     bisitz   6729: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6730:   /* background: #77FF77; */
1.707     bisitz   6731: }
1.795     www      6732: 
1.707     bisitz   6733: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6734:   border-right: 8px solid #FFFF77;
1.707     bisitz   6735: }
1.795     www      6736: 
1.707     bisitz   6737: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6738:   border-right: 8px solid #FFAA77;
1.707     bisitz   6739: }
1.795     www      6740: 
1.707     bisitz   6741: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6742:   border-right: 8px solid #FF7777;
1.707     bisitz   6743: }
1.795     www      6744: 
1.707     bisitz   6745: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6746:   border-right: 8px solid #AAFF77;
1.707     bisitz   6747: }
1.795     www      6748: 
1.707     bisitz   6749: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6750:   border-right: 8px solid #11CC55;
1.707     bisitz   6751: }
                   6752: 
1.388     albertel 6753: span.LC_current_location {
1.701     harmsja  6754:   font-size:larger;
1.388     albertel 6755:   background: $pgbg;
                   6756: }
1.387     albertel 6757: 
1.1029    www      6758: span.LC_current_nav_location {
                   6759:   font-weight:bold;
                   6760:   background: $sidebg;
                   6761: }
                   6762: 
1.395     albertel 6763: span.LC_parm_menu_item {
                   6764:   font-size: larger;
                   6765: }
1.795     www      6766: 
1.395     albertel 6767: span.LC_parm_scope_all {
                   6768:   color: red;
                   6769: }
1.795     www      6770: 
1.395     albertel 6771: span.LC_parm_scope_folder {
                   6772:   color: green;
                   6773: }
1.795     www      6774: 
1.395     albertel 6775: span.LC_parm_scope_resource {
                   6776:   color: orange;
                   6777: }
1.795     www      6778: 
1.395     albertel 6779: span.LC_parm_part {
                   6780:   color: blue;
                   6781: }
1.795     www      6782: 
1.911     bisitz   6783: span.LC_parm_folder,
                   6784: span.LC_parm_symb {
1.395     albertel 6785:   font-size: x-small;
                   6786:   font-family: $mono;
                   6787:   color: #AAAAAA;
                   6788: }
                   6789: 
1.977     bisitz   6790: ul.LC_parm_parmlist li {
                   6791:   display: inline-block;
                   6792:   padding: 0.3em 0.8em;
                   6793:   vertical-align: top;
                   6794:   width: 150px;
                   6795:   border-top:1px solid $lg_border_color;
                   6796: }
                   6797: 
1.795     www      6798: td.LC_parm_overview_level_menu,
                   6799: td.LC_parm_overview_map_menu,
                   6800: td.LC_parm_overview_parm_selectors,
                   6801: td.LC_parm_overview_restrictions  {
1.396     albertel 6802:   border: 1px solid black;
                   6803:   border-collapse: collapse;
                   6804: }
1.795     www      6805: 
1.1285    raeburn  6806: span.LC_parm_recursive,
                   6807: td.LC_parm_recursive {
                   6808:   font-weight: bold;
                   6809:   font-size: smaller;
                   6810: }
                   6811: 
1.396     albertel 6812: table.LC_parm_overview_restrictions td {
                   6813:   border-width: 1px 4px 1px 4px;
                   6814:   border-style: solid;
                   6815:   border-color: $pgbg;
                   6816:   text-align: center;
                   6817: }
1.795     www      6818: 
1.396     albertel 6819: table.LC_parm_overview_restrictions th {
                   6820:   background: $tabbg;
                   6821:   border-width: 1px 4px 1px 4px;
                   6822:   border-style: solid;
                   6823:   border-color: $pgbg;
                   6824: }
1.795     www      6825: 
1.398     albertel 6826: table#LC_helpmenu {
1.803     bisitz   6827:   border: none;
1.398     albertel 6828:   height: 55px;
1.803     bisitz   6829:   border-spacing: 0;
1.398     albertel 6830: }
                   6831: 
                   6832: table#LC_helpmenu fieldset legend {
                   6833:   font-size: larger;
                   6834: }
1.795     www      6835: 
1.397     albertel 6836: table#LC_helpmenu_links {
                   6837:   width: 100%;
                   6838:   border: 1px solid black;
                   6839:   background: $pgbg;
1.803     bisitz   6840:   padding: 0;
1.397     albertel 6841:   border-spacing: 1px;
                   6842: }
1.795     www      6843: 
1.397     albertel 6844: table#LC_helpmenu_links tr td {
                   6845:   padding: 1px;
                   6846:   background: $tabbg;
1.399     albertel 6847:   text-align: center;
                   6848:   font-weight: bold;
1.397     albertel 6849: }
1.396     albertel 6850: 
1.795     www      6851: table#LC_helpmenu_links a:link,
                   6852: table#LC_helpmenu_links a:visited,
1.397     albertel 6853: table#LC_helpmenu_links a:active {
                   6854:   text-decoration: none;
                   6855:   color: $font;
                   6856: }
1.795     www      6857: 
1.397     albertel 6858: table#LC_helpmenu_links a:hover {
                   6859:   text-decoration: underline;
                   6860:   color: $vlink;
                   6861: }
1.396     albertel 6862: 
1.417     albertel 6863: .LC_chrt_popup_exists {
                   6864:   border: 1px solid #339933;
                   6865:   margin: -1px;
                   6866: }
1.795     www      6867: 
1.417     albertel 6868: .LC_chrt_popup_up {
                   6869:   border: 1px solid yellow;
                   6870:   margin: -1px;
                   6871: }
1.795     www      6872: 
1.417     albertel 6873: .LC_chrt_popup {
                   6874:   border: 1px solid #8888FF;
                   6875:   background: #CCCCFF;
                   6876: }
1.795     www      6877: 
1.421     albertel 6878: table.LC_pick_box {
                   6879:   border-collapse: separate;
                   6880:   background: white;
                   6881:   border: 1px solid black;
                   6882:   border-spacing: 1px;
                   6883: }
1.795     www      6884: 
1.421     albertel 6885: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6886:   background: $sidebg;
1.421     albertel 6887:   font-weight: bold;
1.900     bisitz   6888:   text-align: left;
1.740     bisitz   6889:   vertical-align: top;
1.421     albertel 6890:   width: 184px;
                   6891:   padding: 8px;
                   6892: }
1.795     www      6893: 
1.579     raeburn  6894: table.LC_pick_box td.LC_pick_box_value {
                   6895:   text-align: left;
                   6896:   padding: 8px;
                   6897: }
1.795     www      6898: 
1.579     raeburn  6899: table.LC_pick_box td.LC_pick_box_select {
                   6900:   text-align: left;
                   6901:   padding: 8px;
                   6902: }
1.795     www      6903: 
1.424     albertel 6904: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6905:   padding: 0;
1.421     albertel 6906:   height: 1px;
                   6907:   background: black;
                   6908: }
1.795     www      6909: 
1.421     albertel 6910: table.LC_pick_box td.LC_pick_box_submit {
                   6911:   text-align: right;
                   6912: }
1.795     www      6913: 
1.579     raeburn  6914: table.LC_pick_box td.LC_evenrow_value {
                   6915:   text-align: left;
                   6916:   padding: 8px;
                   6917:   background-color: $data_table_light;
                   6918: }
1.795     www      6919: 
1.579     raeburn  6920: table.LC_pick_box td.LC_oddrow_value {
                   6921:   text-align: left;
                   6922:   padding: 8px;
                   6923:   background-color: $data_table_light;
                   6924: }
1.795     www      6925: 
1.579     raeburn  6926: span.LC_helpform_receipt_cat {
                   6927:   font-weight: bold;
                   6928: }
1.795     www      6929: 
1.424     albertel 6930: table.LC_group_priv_box {
                   6931:   background: white;
                   6932:   border: 1px solid black;
                   6933:   border-spacing: 1px;
                   6934: }
1.795     www      6935: 
1.424     albertel 6936: table.LC_group_priv_box td.LC_pick_box_title {
                   6937:   background: $tabbg;
                   6938:   font-weight: bold;
                   6939:   text-align: right;
                   6940:   width: 184px;
                   6941: }
1.795     www      6942: 
1.424     albertel 6943: table.LC_group_priv_box td.LC_groups_fixed {
                   6944:   background: $data_table_light;
                   6945:   text-align: center;
                   6946: }
1.795     www      6947: 
1.424     albertel 6948: table.LC_group_priv_box td.LC_groups_optional {
                   6949:   background: $data_table_dark;
                   6950:   text-align: center;
                   6951: }
1.795     www      6952: 
1.424     albertel 6953: table.LC_group_priv_box td.LC_groups_functionality {
                   6954:   background: $data_table_darker;
                   6955:   text-align: center;
                   6956:   font-weight: bold;
                   6957: }
1.795     www      6958: 
1.424     albertel 6959: table.LC_group_priv td {
                   6960:   text-align: left;
1.803     bisitz   6961:   padding: 0;
1.424     albertel 6962: }
                   6963: 
                   6964: .LC_navbuttons {
                   6965:   margin: 2ex 0ex 2ex 0ex;
                   6966: }
1.795     www      6967: 
1.423     albertel 6968: .LC_topic_bar {
                   6969:   font-weight: bold;
                   6970:   background: $tabbg;
1.918     wenzelju 6971:   margin: 1em 0em 1em 2em;
1.805     bisitz   6972:   padding: 3px;
1.918     wenzelju 6973:   font-size: 1.2em;
1.423     albertel 6974: }
1.795     www      6975: 
1.423     albertel 6976: .LC_topic_bar span {
1.918     wenzelju 6977:   left: 0.5em;
                   6978:   position: absolute;
1.423     albertel 6979:   vertical-align: middle;
1.918     wenzelju 6980:   font-size: 1.2em;
1.423     albertel 6981: }
1.795     www      6982: 
1.423     albertel 6983: table.LC_course_group_status {
                   6984:   margin: 20px;
                   6985: }
1.795     www      6986: 
1.423     albertel 6987: table.LC_status_selector td {
                   6988:   vertical-align: top;
                   6989:   text-align: center;
1.424     albertel 6990:   padding: 4px;
                   6991: }
1.795     www      6992: 
1.599     albertel 6993: div.LC_feedback_link {
1.616     albertel 6994:   clear: both;
1.829     kalberla 6995:   background: $sidebg;
1.779     bisitz   6996:   width: 100%;
1.829     kalberla 6997:   padding-bottom: 10px;
                   6998:   border: 1px $tabbg solid;
1.833     kalberla 6999:   height: 22px;
                   7000:   line-height: 22px;
                   7001:   padding-top: 5px;
                   7002: }
                   7003: 
                   7004: div.LC_feedback_link img {
                   7005:   height: 22px;
1.867     kalberla 7006:   vertical-align:middle;
1.829     kalberla 7007: }
                   7008: 
1.911     bisitz   7009: div.LC_feedback_link a {
1.829     kalberla 7010:   text-decoration: none;
1.489     raeburn  7011: }
1.795     www      7012: 
1.867     kalberla 7013: div.LC_comblock {
1.911     bisitz   7014:   display:inline;
1.867     kalberla 7015:   color:$font;
                   7016:   font-size:90%;
                   7017: }
                   7018: 
                   7019: div.LC_feedback_link div.LC_comblock {
                   7020:   padding-left:5px;
                   7021: }
                   7022: 
                   7023: div.LC_feedback_link div.LC_comblock a {
                   7024:   color:$font;
                   7025: }
                   7026: 
1.489     raeburn  7027: span.LC_feedback_link {
1.858     bisitz   7028:   /* background: $feedback_link_bg; */
1.599     albertel 7029:   font-size: larger;
                   7030: }
1.795     www      7031: 
1.599     albertel 7032: span.LC_message_link {
1.858     bisitz   7033:   /* background: $feedback_link_bg; */
1.599     albertel 7034:   font-size: larger;
                   7035:   position: absolute;
                   7036:   right: 1em;
1.489     raeburn  7037: }
1.421     albertel 7038: 
1.515     albertel 7039: table.LC_prior_tries {
1.524     albertel 7040:   border: 1px solid #000000;
                   7041:   border-collapse: separate;
                   7042:   border-spacing: 1px;
1.515     albertel 7043: }
1.523     albertel 7044: 
1.515     albertel 7045: table.LC_prior_tries td {
1.524     albertel 7046:   padding: 2px;
1.515     albertel 7047: }
1.523     albertel 7048: 
                   7049: .LC_answer_correct {
1.795     www      7050:   background: lightgreen;
                   7051:   color: darkgreen;
                   7052:   padding: 6px;
1.523     albertel 7053: }
1.795     www      7054: 
1.523     albertel 7055: .LC_answer_charged_try {
1.797     www      7056:   background: #FFAAAA;
1.795     www      7057:   color: darkred;
                   7058:   padding: 6px;
1.523     albertel 7059: }
1.795     www      7060: 
1.779     bisitz   7061: .LC_answer_not_charged_try,
1.523     albertel 7062: .LC_answer_no_grade,
                   7063: .LC_answer_late {
1.795     www      7064:   background: lightyellow;
1.523     albertel 7065:   color: black;
1.795     www      7066:   padding: 6px;
1.523     albertel 7067: }
1.795     www      7068: 
1.523     albertel 7069: .LC_answer_previous {
1.795     www      7070:   background: lightblue;
                   7071:   color: darkblue;
                   7072:   padding: 6px;
1.523     albertel 7073: }
1.795     www      7074: 
1.779     bisitz   7075: .LC_answer_no_message {
1.777     tempelho 7076:   background: #FFFFFF;
                   7077:   color: black;
1.795     www      7078:   padding: 6px;
1.779     bisitz   7079: }
1.795     www      7080: 
1.779     bisitz   7081: .LC_answer_unknown {
                   7082:   background: orange;
                   7083:   color: black;
1.795     www      7084:   padding: 6px;
1.777     tempelho 7085: }
1.795     www      7086: 
1.529     albertel 7087: span.LC_prior_numerical,
                   7088: span.LC_prior_string,
                   7089: span.LC_prior_custom,
                   7090: span.LC_prior_reaction,
                   7091: span.LC_prior_math {
1.925     bisitz   7092:   font-family: $mono;
1.523     albertel 7093:   white-space: pre;
                   7094: }
                   7095: 
1.525     albertel 7096: span.LC_prior_string {
1.925     bisitz   7097:   font-family: $mono;
1.525     albertel 7098:   white-space: pre;
                   7099: }
                   7100: 
1.523     albertel 7101: table.LC_prior_option {
                   7102:   width: 100%;
                   7103:   border-collapse: collapse;
                   7104: }
1.795     www      7105: 
1.911     bisitz   7106: table.LC_prior_rank,
1.795     www      7107: table.LC_prior_match {
1.528     albertel 7108:   border-collapse: collapse;
                   7109: }
1.795     www      7110: 
1.528     albertel 7111: table.LC_prior_option tr td,
                   7112: table.LC_prior_rank tr td,
                   7113: table.LC_prior_match tr td {
1.524     albertel 7114:   border: 1px solid #000000;
1.515     albertel 7115: }
                   7116: 
1.855     bisitz   7117: .LC_nobreak {
1.544     albertel 7118:   white-space: nowrap;
1.519     raeburn  7119: }
                   7120: 
1.576     raeburn  7121: span.LC_cusr_emph {
                   7122:   font-style: italic;
                   7123: }
                   7124: 
1.633     raeburn  7125: span.LC_cusr_subheading {
                   7126:   font-weight: normal;
                   7127:   font-size: 85%;
                   7128: }
                   7129: 
1.861     bisitz   7130: div.LC_docs_entry_move {
1.859     bisitz   7131:   border: 1px solid #BBBBBB;
1.545     albertel 7132:   background: #DDDDDD;
1.861     bisitz   7133:   width: 22px;
1.859     bisitz   7134:   padding: 1px;
                   7135:   margin: 0;
1.545     albertel 7136: }
                   7137: 
1.861     bisitz   7138: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7139: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7140:   font-size: x-small;
                   7141: }
1.795     www      7142: 
1.861     bisitz   7143: .LC_docs_entry_parameter {
                   7144:   white-space: nowrap;
                   7145: }
                   7146: 
1.544     albertel 7147: .LC_docs_copy {
1.545     albertel 7148:   color: #000099;
1.544     albertel 7149: }
1.795     www      7150: 
1.544     albertel 7151: .LC_docs_cut {
1.545     albertel 7152:   color: #550044;
1.544     albertel 7153: }
1.795     www      7154: 
1.544     albertel 7155: .LC_docs_rename {
1.545     albertel 7156:   color: #009900;
1.544     albertel 7157: }
1.795     www      7158: 
1.544     albertel 7159: .LC_docs_remove {
1.545     albertel 7160:   color: #990000;
                   7161: }
                   7162: 
1.1284    raeburn  7163: .LC_docs_alias {
                   7164:   color: #440055;  
                   7165: }
                   7166: 
1.1286    raeburn  7167: .LC_domprefs_email,
1.1284    raeburn  7168: .LC_docs_alias_name,
1.547     albertel 7169: .LC_docs_reinit_warn,
                   7170: .LC_docs_ext_edit {
                   7171:   font-size: x-small;
                   7172: }
                   7173: 
1.545     albertel 7174: table.LC_docs_adddocs td,
                   7175: table.LC_docs_adddocs th {
                   7176:   border: 1px solid #BBBBBB;
                   7177:   padding: 4px;
                   7178:   background: #DDDDDD;
1.543     albertel 7179: }
                   7180: 
1.584     albertel 7181: table.LC_sty_begin {
                   7182:   background: #BBFFBB;
                   7183: }
1.795     www      7184: 
1.584     albertel 7185: table.LC_sty_end {
                   7186:   background: #FFBBBB;
                   7187: }
                   7188: 
1.589     raeburn  7189: table.LC_double_column {
1.803     bisitz   7190:   border-width: 0;
1.589     raeburn  7191:   border-collapse: collapse;
                   7192:   width: 100%;
                   7193:   padding: 2px;
                   7194: }
                   7195: 
                   7196: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7197:   top: 2px;
1.589     raeburn  7198:   left: 2px;
                   7199:   width: 47%;
                   7200:   vertical-align: top;
                   7201: }
                   7202: 
                   7203: table.LC_double_column tr td.LC_right_col {
                   7204:   top: 2px;
1.779     bisitz   7205:   right: 2px;
1.589     raeburn  7206:   width: 47%;
                   7207:   vertical-align: top;
                   7208: }
                   7209: 
1.591     raeburn  7210: div.LC_left_float {
                   7211:   float: left;
                   7212:   padding-right: 5%;
1.597     albertel 7213:   padding-bottom: 4px;
1.591     raeburn  7214: }
                   7215: 
                   7216: div.LC_clear_float_header {
1.597     albertel 7217:   padding-bottom: 2px;
1.591     raeburn  7218: }
                   7219: 
                   7220: div.LC_clear_float_footer {
1.597     albertel 7221:   padding-top: 10px;
1.591     raeburn  7222:   clear: both;
                   7223: }
                   7224: 
1.597     albertel 7225: div.LC_grade_show_user {
1.941     bisitz   7226: /*  border-left: 5px solid $sidebg; */
                   7227:   border-top: 5px solid #000000;
                   7228:   margin: 50px 0 0 0;
1.936     bisitz   7229:   padding: 15px 0 5px 10px;
1.597     albertel 7230: }
1.795     www      7231: 
1.936     bisitz   7232: div.LC_grade_show_user_odd_row {
1.941     bisitz   7233: /*  border-left: 5px solid #000000; */
                   7234: }
                   7235: 
                   7236: div.LC_grade_show_user div.LC_Box {
                   7237:   margin-right: 50px;
1.597     albertel 7238: }
                   7239: 
                   7240: div.LC_grade_submissions,
                   7241: div.LC_grade_message_center,
1.936     bisitz   7242: div.LC_grade_info_links {
1.597     albertel 7243:   margin: 5px;
                   7244:   width: 99%;
                   7245:   background: #FFFFFF;
                   7246: }
1.795     www      7247: 
1.597     albertel 7248: div.LC_grade_submissions_header,
1.936     bisitz   7249: div.LC_grade_message_center_header {
1.705     tempelho 7250:   font-weight: bold;
                   7251:   font-size: large;
1.597     albertel 7252: }
1.795     www      7253: 
1.597     albertel 7254: div.LC_grade_submissions_body,
1.936     bisitz   7255: div.LC_grade_message_center_body {
1.597     albertel 7256:   border: 1px solid black;
                   7257:   width: 99%;
                   7258:   background: #FFFFFF;
                   7259: }
1.795     www      7260: 
1.613     albertel 7261: table.LC_scantron_action {
                   7262:   width: 100%;
                   7263: }
1.795     www      7264: 
1.613     albertel 7265: table.LC_scantron_action tr th {
1.698     harmsja  7266:   font-weight:bold;
                   7267:   font-style:normal;
1.613     albertel 7268: }
1.795     www      7269: 
1.779     bisitz   7270: .LC_edit_problem_header,
1.614     albertel 7271: div.LC_edit_problem_footer {
1.705     tempelho 7272:   font-weight: normal;
                   7273:   font-size:  medium;
1.602     albertel 7274:   margin: 2px;
1.1060    bisitz   7275:   background-color: $sidebg;
1.600     albertel 7276: }
1.795     www      7277: 
1.600     albertel 7278: div.LC_edit_problem_header,
1.602     albertel 7279: div.LC_edit_problem_header div,
1.614     albertel 7280: div.LC_edit_problem_footer,
                   7281: div.LC_edit_problem_footer div,
1.602     albertel 7282: div.LC_edit_problem_editxml_header,
                   7283: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7284:   z-index: 100;
1.600     albertel 7285: }
1.795     www      7286: 
1.600     albertel 7287: div.LC_edit_problem_header_title {
1.705     tempelho 7288:   font-weight: bold;
                   7289:   font-size: larger;
1.602     albertel 7290:   background: $tabbg;
                   7291:   padding: 3px;
1.1060    bisitz   7292:   margin: 0 0 5px 0;
1.602     albertel 7293: }
1.795     www      7294: 
1.602     albertel 7295: table.LC_edit_problem_header_title {
                   7296:   width: 100%;
1.600     albertel 7297:   background: $tabbg;
1.602     albertel 7298: }
                   7299: 
1.1205    golterma 7300: div.LC_edit_actionbar {
                   7301:     background-color: $sidebg;
1.1218    droeschl 7302:     margin: 0;
                   7303:     padding: 0;
                   7304:     line-height: 200%;
1.602     albertel 7305: }
1.795     www      7306: 
1.1218    droeschl 7307: div.LC_edit_actionbar div{
                   7308:     padding: 0;
                   7309:     margin: 0;
                   7310:     display: inline-block;
1.600     albertel 7311: }
1.795     www      7312: 
1.1124    bisitz   7313: .LC_edit_opt {
                   7314:   padding-left: 1em;
                   7315:   white-space: nowrap;
                   7316: }
                   7317: 
1.1152    golterma 7318: .LC_edit_problem_latexhelper{
                   7319:     text-align: right;
                   7320: }
                   7321: 
                   7322: #LC_edit_problem_colorful div{
                   7323:     margin-left: 40px;
                   7324: }
                   7325: 
1.1205    golterma 7326: #LC_edit_problem_codemirror div{
                   7327:     margin-left: 0px;
                   7328: }
                   7329: 
1.911     bisitz   7330: img.stift {
1.803     bisitz   7331:   border-width: 0;
                   7332:   vertical-align: middle;
1.677     riegler  7333: }
1.680     riegler  7334: 
1.923     bisitz   7335: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7336:   vertical-align: top;
1.777     tempelho 7337: }
1.795     www      7338: 
1.716     raeburn  7339: div.LC_createcourse {
1.911     bisitz   7340:   margin: 10px 10px 10px 10px;
1.716     raeburn  7341: }
                   7342: 
1.917     raeburn  7343: .LC_dccid {
1.1130    raeburn  7344:   float: right;
1.917     raeburn  7345:   margin: 0.2em 0 0 0;
                   7346:   padding: 0;
                   7347:   font-size: 90%;
                   7348:   display:none;
                   7349: }
                   7350: 
1.897     wenzelju 7351: ol.LC_primary_menu a:hover,
1.721     harmsja  7352: ol#LC_MenuBreadcrumbs a:hover,
                   7353: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7354: ul#LC_secondary_menu a:hover,
1.721     harmsja  7355: .LC_FormSectionClearButton input:hover
1.795     www      7356: ul.LC_TabContent   li:hover a {
1.952     onken    7357:   color:$button_hover;
1.911     bisitz   7358:   text-decoration:none;
1.693     droeschl 7359: }
                   7360: 
1.779     bisitz   7361: h1 {
1.911     bisitz   7362:   padding: 0;
                   7363:   line-height:130%;
1.693     droeschl 7364: }
1.698     harmsja  7365: 
1.911     bisitz   7366: h2,
                   7367: h3,
                   7368: h4,
                   7369: h5,
                   7370: h6 {
                   7371:   margin: 5px 0 5px 0;
                   7372:   padding: 0;
                   7373:   line-height:130%;
1.693     droeschl 7374: }
1.795     www      7375: 
                   7376: .LC_hcell {
1.911     bisitz   7377:   padding:3px 15px 3px 15px;
                   7378:   margin: 0;
                   7379:   background-color:$tabbg;
                   7380:   color:$fontmenu;
                   7381:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7382: }
1.795     www      7383: 
1.840     bisitz   7384: .LC_Box > .LC_hcell {
1.911     bisitz   7385:   margin: 0 -10px 10px -10px;
1.835     bisitz   7386: }
                   7387: 
1.721     harmsja  7388: .LC_noBorder {
1.911     bisitz   7389:   border: 0;
1.698     harmsja  7390: }
1.693     droeschl 7391: 
1.721     harmsja  7392: .LC_FormSectionClearButton input {
1.911     bisitz   7393:   background-color:transparent;
                   7394:   border: none;
                   7395:   cursor:pointer;
                   7396:   text-decoration:underline;
1.693     droeschl 7397: }
1.763     bisitz   7398: 
                   7399: .LC_help_open_topic {
1.911     bisitz   7400:   color: #FFFFFF;
                   7401:   background-color: #EEEEFF;
                   7402:   margin: 1px;
                   7403:   padding: 4px;
                   7404:   border: 1px solid #000033;
                   7405:   white-space: nowrap;
                   7406:   /* vertical-align: middle; */
1.759     neumanie 7407: }
1.693     droeschl 7408: 
1.911     bisitz   7409: dl,
                   7410: ul,
                   7411: div,
                   7412: fieldset {
                   7413:   margin: 10px 10px 10px 0;
                   7414:   /* overflow: hidden; */
1.693     droeschl 7415: }
1.795     www      7416: 
1.1211    raeburn  7417: article.geogebraweb div {
                   7418:     margin: 0;
                   7419: }
                   7420: 
1.838     bisitz   7421: fieldset > legend {
1.911     bisitz   7422:   font-weight: bold;
                   7423:   padding: 0 5px 0 5px;
1.838     bisitz   7424: }
                   7425: 
1.813     bisitz   7426: #LC_nav_bar {
1.911     bisitz   7427:   float: left;
1.995     raeburn  7428:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7429:   margin: 0 0 2px 0;
1.807     droeschl 7430: }
                   7431: 
1.916     droeschl 7432: #LC_realm {
                   7433:   margin: 0.2em 0 0 0;
                   7434:   padding: 0;
                   7435:   font-weight: bold;
                   7436:   text-align: center;
1.995     raeburn  7437:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7438: }
                   7439: 
1.911     bisitz   7440: #LC_nav_bar em {
                   7441:   font-weight: bold;
                   7442:   font-style: normal;
1.807     droeschl 7443: }
                   7444: 
1.897     wenzelju 7445: ol.LC_primary_menu {
1.934     droeschl 7446:   margin: 0;
1.1076    raeburn  7447:   padding: 0;
1.807     droeschl 7448: }
                   7449: 
1.852     droeschl 7450: ol#LC_PathBreadcrumbs {
1.911     bisitz   7451:   margin: 0;
1.693     droeschl 7452: }
                   7453: 
1.897     wenzelju 7454: ol.LC_primary_menu li {
1.1076    raeburn  7455:   color: RGB(80, 80, 80);
                   7456:   vertical-align: middle;
                   7457:   text-align: left;
                   7458:   list-style: none;
1.1205    golterma 7459:   position: relative;
1.1076    raeburn  7460:   float: left;
1.1205    golterma 7461:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7462:   line-height: 1.5em;
1.1076    raeburn  7463: }
                   7464: 
1.1205    golterma 7465: ol.LC_primary_menu li a,
                   7466: ol.LC_primary_menu li p {
1.1076    raeburn  7467:   display: block;
                   7468:   margin: 0;
                   7469:   padding: 0 5px 0 10px;
                   7470:   text-decoration: none;
                   7471: }
                   7472: 
1.1205    golterma 7473: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7474:   display: inline-block;
                   7475:   width: 95%;
                   7476:   text-align: left;
                   7477: }
                   7478: 
                   7479: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7480:   display: inline-block;	
                   7481:   width: 5%;
                   7482:   float: right;
                   7483:   text-align: right;
                   7484:   font-size: 70%;
                   7485: }
                   7486: 
                   7487: ol.LC_primary_menu ul {
1.1076    raeburn  7488:   display: none;
1.1205    golterma 7489:   width: 15em;
1.1076    raeburn  7490:   background-color: $data_table_light;
1.1205    golterma 7491:   position: absolute;
                   7492:   top: 100%;
1.1076    raeburn  7493: }
                   7494: 
1.1205    golterma 7495: ol.LC_primary_menu ul ul {
                   7496:   left: 100%;
                   7497:   top: 0;
                   7498: }
                   7499: 
                   7500: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7501:   display: block;
                   7502:   position: absolute;
                   7503:   margin: 0;
                   7504:   padding: 0;
1.1078    raeburn  7505:   z-index: 2;
1.1076    raeburn  7506: }
                   7507: 
                   7508: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7509: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7510:   font-size: 90%;
1.911     bisitz   7511:   vertical-align: top;
1.1076    raeburn  7512:   float: none;
1.1079    raeburn  7513:   border-left: 1px solid black;
                   7514:   border-right: 1px solid black;
1.1205    golterma 7515: /* A dark bottom border to visualize different menu options; 
                   7516: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7517:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7518: }
                   7519: 
1.1205    golterma 7520: ol.LC_primary_menu li li p:hover {
                   7521:   color:$button_hover;
                   7522:   text-decoration:none;
                   7523:   background-color:$data_table_dark;
1.1076    raeburn  7524: }
                   7525: 
                   7526: ol.LC_primary_menu li li a:hover {
                   7527:    color:$button_hover;
                   7528:    background-color:$data_table_dark;
1.693     droeschl 7529: }
                   7530: 
1.1205    golterma 7531: /* Font-size equal to the size of the predecessors*/
                   7532: ol.LC_primary_menu li:hover li li {
                   7533:   font-size: 100%;
                   7534: }
                   7535: 
1.897     wenzelju 7536: ol.LC_primary_menu li img {
1.911     bisitz   7537:   vertical-align: bottom;
1.934     droeschl 7538:   height: 1.1em;
1.1077    raeburn  7539:   margin: 0.2em 0 0 0;
1.693     droeschl 7540: }
                   7541: 
1.897     wenzelju 7542: ol.LC_primary_menu a {
1.911     bisitz   7543:   color: RGB(80, 80, 80);
                   7544:   text-decoration: none;
1.693     droeschl 7545: }
1.795     www      7546: 
1.949     droeschl 7547: ol.LC_primary_menu a.LC_new_message {
                   7548:   font-weight:bold;
                   7549:   color: darkred;
                   7550: }
                   7551: 
1.975     raeburn  7552: ol.LC_docs_parameters {
                   7553:   margin-left: 0;
                   7554:   padding: 0;
                   7555:   list-style: none;
                   7556: }
                   7557: 
                   7558: ol.LC_docs_parameters li {
                   7559:   margin: 0;
                   7560:   padding-right: 20px;
                   7561:   display: inline;
                   7562: }
                   7563: 
1.976     raeburn  7564: ol.LC_docs_parameters li:before {
                   7565:   content: "\\002022 \\0020";
                   7566: }
                   7567: 
                   7568: li.LC_docs_parameters_title {
                   7569:   font-weight: bold;
                   7570: }
                   7571: 
                   7572: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7573:   content: "";
                   7574: }
                   7575: 
1.897     wenzelju 7576: ul#LC_secondary_menu {
1.1107    raeburn  7577:   clear: right;
1.911     bisitz   7578:   color: $fontmenu;
                   7579:   background: $tabbg;
                   7580:   list-style: none;
                   7581:   padding: 0;
                   7582:   margin: 0;
                   7583:   width: 100%;
1.995     raeburn  7584:   text-align: left;
1.1107    raeburn  7585:   float: left;
1.808     droeschl 7586: }
                   7587: 
1.897     wenzelju 7588: ul#LC_secondary_menu li {
1.911     bisitz   7589:   font-weight: bold;
                   7590:   line-height: 1.8em;
1.1107    raeburn  7591:   border-right: 1px solid black;
                   7592:   float: left;
                   7593: }
                   7594: 
                   7595: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7596:   background-color: $data_table_light;
                   7597: }
                   7598: 
                   7599: ul#LC_secondary_menu li a {
1.911     bisitz   7600:   padding: 0 0.8em;
1.1107    raeburn  7601: }
                   7602: 
                   7603: ul#LC_secondary_menu li ul {
                   7604:   display: none;
                   7605: }
                   7606: 
                   7607: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7608:   display: block;
                   7609:   position: absolute;
                   7610:   margin: 0;
                   7611:   padding: 0;
                   7612:   list-style:none;
                   7613:   float: none;
                   7614:   background-color: $data_table_light;
                   7615:   z-index: 2;
                   7616:   margin-left: -1px;
                   7617: }
                   7618: 
                   7619: ul#LC_secondary_menu li ul li {
                   7620:   font-size: 90%;
                   7621:   vertical-align: top;
                   7622:   border-left: 1px solid black;
1.911     bisitz   7623:   border-right: 1px solid black;
1.1119    raeburn  7624:   background-color: $data_table_light;
1.1107    raeburn  7625:   list-style:none;
                   7626:   float: none;
                   7627: }
                   7628: 
                   7629: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7630:   background-color: $data_table_dark;
1.807     droeschl 7631: }
                   7632: 
1.847     tempelho 7633: ul.LC_TabContent {
1.911     bisitz   7634:   display:block;
                   7635:   background: $sidebg;
                   7636:   border-bottom: solid 1px $lg_border_color;
                   7637:   list-style:none;
1.1020    raeburn  7638:   margin: -1px -10px 0 -10px;
1.911     bisitz   7639:   padding: 0;
1.693     droeschl 7640: }
                   7641: 
1.795     www      7642: ul.LC_TabContent li,
                   7643: ul.LC_TabContentBigger li {
1.911     bisitz   7644:   float:left;
1.741     harmsja  7645: }
1.795     www      7646: 
1.897     wenzelju 7647: ul#LC_secondary_menu li a {
1.911     bisitz   7648:   color: $fontmenu;
                   7649:   text-decoration: none;
1.693     droeschl 7650: }
1.795     www      7651: 
1.721     harmsja  7652: ul.LC_TabContent {
1.952     onken    7653:   min-height:20px;
1.721     harmsja  7654: }
1.795     www      7655: 
                   7656: ul.LC_TabContent li {
1.911     bisitz   7657:   vertical-align:middle;
1.959     onken    7658:   padding: 0 16px 0 10px;
1.911     bisitz   7659:   background-color:$tabbg;
                   7660:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7661:   border-left: solid 1px $font;
1.721     harmsja  7662: }
1.795     www      7663: 
1.847     tempelho 7664: ul.LC_TabContent .right {
1.911     bisitz   7665:   float:right;
1.847     tempelho 7666: }
                   7667: 
1.911     bisitz   7668: ul.LC_TabContent li a,
                   7669: ul.LC_TabContent li {
                   7670:   color:rgb(47,47,47);
                   7671:   text-decoration:none;
                   7672:   font-size:95%;
                   7673:   font-weight:bold;
1.952     onken    7674:   min-height:20px;
                   7675: }
                   7676: 
1.959     onken    7677: ul.LC_TabContent li a:hover,
                   7678: ul.LC_TabContent li a:focus {
1.952     onken    7679:   color: $button_hover;
1.959     onken    7680:   background:none;
                   7681:   outline:none;
1.952     onken    7682: }
                   7683: 
                   7684: ul.LC_TabContent li:hover {
                   7685:   color: $button_hover;
                   7686:   cursor:pointer;
1.721     harmsja  7687: }
1.795     www      7688: 
1.911     bisitz   7689: ul.LC_TabContent li.active {
1.952     onken    7690:   color: $font;
1.911     bisitz   7691:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7692:   border-bottom:solid 1px #FFFFFF;
                   7693:   cursor: default;
1.744     ehlerst  7694: }
1.795     www      7695: 
1.959     onken    7696: ul.LC_TabContent li.active a {
                   7697:   color:$font;
                   7698:   background:#FFFFFF;
                   7699:   outline: none;
                   7700: }
1.1047    raeburn  7701: 
                   7702: ul.LC_TabContent li.goback {
                   7703:   float: left;
                   7704:   border-left: none;
                   7705: }
                   7706: 
1.870     tempelho 7707: #maincoursedoc {
1.911     bisitz   7708:   clear:both;
1.870     tempelho 7709: }
                   7710: 
                   7711: ul.LC_TabContentBigger {
1.911     bisitz   7712:   display:block;
                   7713:   list-style:none;
                   7714:   padding: 0;
1.870     tempelho 7715: }
                   7716: 
1.795     www      7717: ul.LC_TabContentBigger li {
1.911     bisitz   7718:   vertical-align:bottom;
                   7719:   height: 30px;
                   7720:   font-size:110%;
                   7721:   font-weight:bold;
                   7722:   color: #737373;
1.841     tempelho 7723: }
                   7724: 
1.957     onken    7725: ul.LC_TabContentBigger li.active {
                   7726:   position: relative;
                   7727:   top: 1px;
                   7728: }
                   7729: 
1.870     tempelho 7730: ul.LC_TabContentBigger li a {
1.911     bisitz   7731:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7732:   height: 30px;
                   7733:   line-height: 30px;
                   7734:   text-align: center;
                   7735:   display: block;
                   7736:   text-decoration: none;
1.958     onken    7737:   outline: none;  
1.741     harmsja  7738: }
1.795     www      7739: 
1.870     tempelho 7740: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7741:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7742:   color:$font;
1.744     ehlerst  7743: }
1.795     www      7744: 
1.870     tempelho 7745: ul.LC_TabContentBigger li b {
1.911     bisitz   7746:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7747:   display: block;
                   7748:   float: left;
                   7749:   padding: 0 30px;
1.957     onken    7750:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7751: }
                   7752: 
1.956     onken    7753: ul.LC_TabContentBigger li:hover b {
                   7754:   color:$button_hover;
                   7755: }
                   7756: 
1.870     tempelho 7757: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7758:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7759:   color:$font;
1.957     onken    7760:   border: 0;
1.741     harmsja  7761: }
1.693     droeschl 7762: 
1.870     tempelho 7763: 
1.862     bisitz   7764: ul.LC_CourseBreadcrumbs {
                   7765:   background: $sidebg;
1.1020    raeburn  7766:   height: 2em;
1.862     bisitz   7767:   padding-left: 10px;
1.1020    raeburn  7768:   margin: 0;
1.862     bisitz   7769:   list-style-position: inside;
                   7770: }
                   7771: 
1.911     bisitz   7772: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7773: ol#LC_PathBreadcrumbs {
1.911     bisitz   7774:   padding-left: 10px;
                   7775:   margin: 0;
1.933     droeschl 7776:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7777: }
                   7778: 
1.911     bisitz   7779: ol#LC_MenuBreadcrumbs li,
                   7780: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7781: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7782:   display: inline;
1.933     droeschl 7783:   white-space: normal;  
1.693     droeschl 7784: }
                   7785: 
1.823     bisitz   7786: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7787: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7788:   text-decoration: none;
                   7789:   font-size:90%;
1.693     droeschl 7790: }
1.795     www      7791: 
1.969     droeschl 7792: ol#LC_MenuBreadcrumbs h1 {
                   7793:   display: inline;
                   7794:   font-size: 90%;
                   7795:   line-height: 2.5em;
                   7796:   margin: 0;
                   7797:   padding: 0;
                   7798: }
                   7799: 
1.795     www      7800: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7801:   text-decoration:none;
                   7802:   font-size:100%;
                   7803:   font-weight:bold;
1.693     droeschl 7804: }
1.795     www      7805: 
1.840     bisitz   7806: .LC_Box {
1.911     bisitz   7807:   border: solid 1px $lg_border_color;
                   7808:   padding: 0 10px 10px 10px;
1.746     neumanie 7809: }
1.795     www      7810: 
1.1020    raeburn  7811: .LC_DocsBox {
                   7812:   border: solid 1px $lg_border_color;
                   7813:   padding: 0 0 10px 10px;
                   7814: }
                   7815: 
1.795     www      7816: .LC_AboutMe_Image {
1.911     bisitz   7817:   float:left;
                   7818:   margin-right:10px;
1.747     neumanie 7819: }
1.795     www      7820: 
                   7821: .LC_Clear_AboutMe_Image {
1.911     bisitz   7822:   clear:left;
1.747     neumanie 7823: }
1.795     www      7824: 
1.721     harmsja  7825: dl.LC_ListStyleClean dt {
1.911     bisitz   7826:   padding-right: 5px;
                   7827:   display: table-header-group;
1.693     droeschl 7828: }
                   7829: 
1.721     harmsja  7830: dl.LC_ListStyleClean dd {
1.911     bisitz   7831:   display: table-row;
1.693     droeschl 7832: }
                   7833: 
1.721     harmsja  7834: .LC_ListStyleClean,
                   7835: .LC_ListStyleSimple,
                   7836: .LC_ListStyleNormal,
1.795     www      7837: .LC_ListStyleSpecial {
1.911     bisitz   7838:   /* display:block; */
                   7839:   list-style-position: inside;
                   7840:   list-style-type: none;
                   7841:   overflow: hidden;
                   7842:   padding: 0;
1.693     droeschl 7843: }
                   7844: 
1.721     harmsja  7845: .LC_ListStyleSimple li,
                   7846: .LC_ListStyleSimple dd,
                   7847: .LC_ListStyleNormal li,
                   7848: .LC_ListStyleNormal dd,
                   7849: .LC_ListStyleSpecial li,
1.795     www      7850: .LC_ListStyleSpecial dd {
1.911     bisitz   7851:   margin: 0;
                   7852:   padding: 5px 5px 5px 10px;
                   7853:   clear: both;
1.693     droeschl 7854: }
                   7855: 
1.721     harmsja  7856: .LC_ListStyleClean li,
                   7857: .LC_ListStyleClean dd {
1.911     bisitz   7858:   padding-top: 0;
                   7859:   padding-bottom: 0;
1.693     droeschl 7860: }
                   7861: 
1.721     harmsja  7862: .LC_ListStyleSimple dd,
1.795     www      7863: .LC_ListStyleSimple li {
1.911     bisitz   7864:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7865: }
                   7866: 
1.721     harmsja  7867: .LC_ListStyleSpecial li,
                   7868: .LC_ListStyleSpecial dd {
1.911     bisitz   7869:   list-style-type: none;
                   7870:   background-color: RGB(220, 220, 220);
                   7871:   margin-bottom: 4px;
1.693     droeschl 7872: }
                   7873: 
1.721     harmsja  7874: table.LC_SimpleTable {
1.911     bisitz   7875:   margin:5px;
                   7876:   border:solid 1px $lg_border_color;
1.795     www      7877: }
1.693     droeschl 7878: 
1.721     harmsja  7879: table.LC_SimpleTable tr {
1.911     bisitz   7880:   padding: 0;
                   7881:   border:solid 1px $lg_border_color;
1.693     droeschl 7882: }
1.795     www      7883: 
                   7884: table.LC_SimpleTable thead {
1.911     bisitz   7885:   background:rgb(220,220,220);
1.693     droeschl 7886: }
                   7887: 
1.721     harmsja  7888: div.LC_columnSection {
1.911     bisitz   7889:   display: block;
                   7890:   clear: both;
                   7891:   overflow: hidden;
                   7892:   margin: 0;
1.693     droeschl 7893: }
                   7894: 
1.721     harmsja  7895: div.LC_columnSection>* {
1.911     bisitz   7896:   float: left;
                   7897:   margin: 10px 20px 10px 0;
                   7898:   overflow:hidden;
1.693     droeschl 7899: }
1.721     harmsja  7900: 
1.795     www      7901: table em {
1.911     bisitz   7902:   font-weight: bold;
                   7903:   font-style: normal;
1.748     schulted 7904: }
1.795     www      7905: 
1.779     bisitz   7906: table.LC_tableBrowseRes,
1.795     www      7907: table.LC_tableOfContent {
1.911     bisitz   7908:   border:none;
                   7909:   border-spacing: 1px;
                   7910:   padding: 3px;
                   7911:   background-color: #FFFFFF;
                   7912:   font-size: 90%;
1.753     droeschl 7913: }
1.789     droeschl 7914: 
1.911     bisitz   7915: table.LC_tableOfContent {
                   7916:   border-collapse: collapse;
1.789     droeschl 7917: }
                   7918: 
1.771     droeschl 7919: table.LC_tableBrowseRes a,
1.768     schulted 7920: table.LC_tableOfContent a {
1.911     bisitz   7921:   background-color: transparent;
                   7922:   text-decoration: none;
1.753     droeschl 7923: }
                   7924: 
1.795     www      7925: table.LC_tableOfContent img {
1.911     bisitz   7926:   border: none;
                   7927:   height: 1.3em;
                   7928:   vertical-align: text-bottom;
                   7929:   margin-right: 0.3em;
1.753     droeschl 7930: }
1.757     schulted 7931: 
1.795     www      7932: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7933:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7934: }
                   7935: 
1.795     www      7936: a#LC_content_toolbar_everything {
1.911     bisitz   7937:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7938: }
                   7939: 
1.795     www      7940: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7941:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7942: }
                   7943: 
1.795     www      7944: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7945:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7946: }
                   7947: 
1.795     www      7948: a#LC_content_toolbar_changefolder {
1.911     bisitz   7949:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7950: }
                   7951: 
1.795     www      7952: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7953:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7954: }
                   7955: 
1.1043    raeburn  7956: a#LC_content_toolbar_edittoplevel {
                   7957:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7958: }
                   7959: 
1.795     www      7960: ul#LC_toolbar li a:hover {
1.911     bisitz   7961:   background-position: bottom center;
1.757     schulted 7962: }
                   7963: 
1.795     www      7964: ul#LC_toolbar {
1.911     bisitz   7965:   padding: 0;
                   7966:   margin: 2px;
                   7967:   list-style:none;
                   7968:   position:relative;
                   7969:   background-color:white;
1.1082    raeburn  7970:   overflow: auto;
1.757     schulted 7971: }
                   7972: 
1.795     www      7973: ul#LC_toolbar li {
1.911     bisitz   7974:   border:1px solid white;
                   7975:   padding: 0;
                   7976:   margin: 0;
                   7977:   float: left;
                   7978:   display:inline;
                   7979:   vertical-align:middle;
1.1082    raeburn  7980:   white-space: nowrap;
1.911     bisitz   7981: }
1.757     schulted 7982: 
1.783     amueller 7983: 
1.795     www      7984: a.LC_toolbarItem {
1.911     bisitz   7985:   display:block;
                   7986:   padding: 0;
                   7987:   margin: 0;
                   7988:   height: 32px;
                   7989:   width: 32px;
                   7990:   color:white;
                   7991:   border: none;
                   7992:   background-repeat:no-repeat;
                   7993:   background-color:transparent;
1.757     schulted 7994: }
                   7995: 
1.915     droeschl 7996: ul.LC_funclist {
                   7997:     margin: 0;
                   7998:     padding: 0.5em 1em 0.5em 0;
                   7999: }
                   8000: 
1.933     droeschl 8001: ul.LC_funclist > li:first-child {
                   8002:     font-weight:bold; 
                   8003:     margin-left:0.8em;
                   8004: }
                   8005: 
1.915     droeschl 8006: ul.LC_funclist + ul.LC_funclist {
                   8007:     /* 
                   8008:        left border as a seperator if we have more than
                   8009:        one list 
                   8010:     */
                   8011:     border-left: 1px solid $sidebg;
                   8012:     /* 
                   8013:        this hides the left border behind the border of the 
                   8014:        outer box if element is wrapped to the next 'line' 
                   8015:     */
                   8016:     margin-left: -1px;
                   8017: }
                   8018: 
1.843     bisitz   8019: ul.LC_funclist li {
1.915     droeschl 8020:   display: inline;
1.782     bisitz   8021:   white-space: nowrap;
1.915     droeschl 8022:   margin: 0 0 0 25px;
                   8023:   line-height: 150%;
1.782     bisitz   8024: }
                   8025: 
1.974     wenzelju 8026: .LC_hidden {
                   8027:   display: none;
                   8028: }
                   8029: 
1.1030    www      8030: .LCmodal-overlay {
                   8031: 		position:fixed;
                   8032: 		top:0;
                   8033: 		right:0;
                   8034: 		bottom:0;
                   8035: 		left:0;
                   8036: 		height:100%;
                   8037: 		width:100%;
                   8038: 		margin:0;
                   8039: 		padding:0;
                   8040: 		background:#999;
                   8041: 		opacity:.75;
                   8042: 		filter: alpha(opacity=75);
                   8043: 		-moz-opacity: 0.75;
                   8044: 		z-index:101;
                   8045: }
                   8046: 
                   8047: * html .LCmodal-overlay {   
                   8048: 		position: absolute;
                   8049: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8050: }
                   8051: 
                   8052: .LCmodal-window {
                   8053: 		position:fixed;
                   8054: 		top:50%;
                   8055: 		left:50%;
                   8056: 		margin:0;
                   8057: 		padding:0;
                   8058: 		z-index:102;
                   8059: 	}
                   8060: 
                   8061: * html .LCmodal-window {
                   8062: 		position:absolute;
                   8063: }
                   8064: 
                   8065: .LCclose-window {
                   8066: 		position:absolute;
                   8067: 		width:32px;
                   8068: 		height:32px;
                   8069: 		right:8px;
                   8070: 		top:8px;
                   8071: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8072: 		text-indent:-99999px;
                   8073: 		overflow:hidden;
                   8074: 		cursor:pointer;
                   8075: }
                   8076: 
1.1100    raeburn  8077: /*
1.1231    damieng  8078:   styles used for response display
                   8079: */
                   8080: div.LC_radiofoil, div.LC_rankfoil {
                   8081:   margin: .5em 0em .5em 0em;
                   8082: }
                   8083: table.LC_itemgroup {
                   8084:   margin-top: 1em;
                   8085: }
                   8086: 
                   8087: /*
1.1100    raeburn  8088:   styles used by TTH when "Default set of options to pass to tth/m
                   8089:   when converting TeX" in course settings has been set
                   8090: 
                   8091:   option passed: -t
                   8092: 
                   8093: */
                   8094: 
                   8095: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8096: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8097: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8098: td div.norm {line-height:normal;}
                   8099: 
                   8100: /*
                   8101:   option passed -y3
                   8102: */
                   8103: 
                   8104: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8105: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8106: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8107: 
1.1230    damieng  8108: /*
                   8109:   sections with roles, for content only
                   8110: */
                   8111: section[class^="role-"] {
                   8112:   padding-left: 10px;
                   8113:   padding-right: 5px;
                   8114:   margin-top: 8px;
                   8115:   margin-bottom: 8px;
                   8116:   border: 1px solid #2A4;
                   8117:   border-radius: 5px;
                   8118:   box-shadow: 0px 1px 1px #BBB;
                   8119: }
                   8120: section[class^="role-"]>h1 {
                   8121:   position: relative;
                   8122:   margin: 0px;
                   8123:   padding-top: 10px;
                   8124:   padding-left: 40px;
                   8125: }
                   8126: section[class^="role-"]>h1:before {
                   8127:   position: absolute;
                   8128:   left: -5px;
                   8129:   top: 5px;
                   8130: }
                   8131: section.role-activity>h1:before {
                   8132:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8133: }
                   8134: section.role-advice>h1:before {
                   8135:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8136: }
                   8137: section.role-bibliography>h1:before {
                   8138:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8139: }
                   8140: section.role-citation>h1:before {
                   8141:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8142: }
                   8143: section.role-conclusion>h1:before {
                   8144:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8145: }
                   8146: section.role-definition>h1:before {
                   8147:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8148: }
                   8149: section.role-demonstration>h1:before {
                   8150:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8151: }
                   8152: section.role-example>h1:before {
                   8153:   content:url('/adm/daxe/images/section_icons/example.png');
                   8154: }
                   8155: section.role-explanation>h1:before {
                   8156:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8157: }
                   8158: section.role-introduction>h1:before {
                   8159:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8160: }
                   8161: section.role-method>h1:before {
                   8162:   content:url('/adm/daxe/images/section_icons/method.png');
                   8163: }
                   8164: section.role-more_information>h1:before {
                   8165:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8166: }
                   8167: section.role-objectives>h1:before {
                   8168:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8169: }
                   8170: section.role-prerequisites>h1:before {
                   8171:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8172: }
                   8173: section.role-remark>h1:before {
                   8174:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8175: }
                   8176: section.role-reminder>h1:before {
                   8177:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8178: }
                   8179: section.role-summary>h1:before {
                   8180:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8181: }
                   8182: section.role-syntax>h1:before {
                   8183:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8184: }
                   8185: section.role-warning>h1:before {
                   8186:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8187: }
                   8188: 
1.1269    raeburn  8189: #LC_minitab_header {
                   8190:   float:left;
                   8191:   width:100%;
                   8192:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8193:   font-size:93%;
                   8194:   line-height:normal;
                   8195:   margin: 0.5em 0 0.5em 0;
                   8196: }
                   8197: #LC_minitab_header ul {
                   8198:   margin:0;
                   8199:   padding:10px 10px 0;
                   8200:   list-style:none;
                   8201: }
                   8202: #LC_minitab_header li {
                   8203:   float:left;
                   8204:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8205:   margin:0;
                   8206:   padding:0 0 0 9px;
                   8207: }
                   8208: #LC_minitab_header a {
                   8209:   display:block;
                   8210:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8211:   padding:5px 15px 4px 6px;
                   8212: }
                   8213: #LC_minitab_header #LC_current_minitab {
                   8214:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8215: }
                   8216: #LC_minitab_header #LC_current_minitab a {
                   8217:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8218:   padding-bottom:5px;
                   8219: }
                   8220: 
                   8221: 
1.343     albertel 8222: END
                   8223: }
                   8224: 
1.306     albertel 8225: =pod
                   8226: 
                   8227: =item * &headtag()
                   8228: 
                   8229: Returns a uniform footer for LON-CAPA web pages.
                   8230: 
1.307     albertel 8231: Inputs: $title - optional title for the head
                   8232:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8233:         $args - optional arguments
1.319     albertel 8234:             force_register - if is true call registerurl so the remote is 
                   8235:                              informed
1.415     albertel 8236:             redirect       -> array ref of
                   8237:                                    1- seconds before redirect occurs
                   8238:                                    2- url to redirect to
                   8239:                                    3- whether the side effect should occur
1.315     albertel 8240:                            (side effect of setting 
                   8241:                                $env{'internal.head.redirect'} to the url 
                   8242:                                redirected too)
1.352     albertel 8243:             domain         -> force to color decorate a page for a specific
                   8244:                                domain
                   8245:             function       -> force usage of a specific rolish color scheme
                   8246:             bgcolor        -> override the default page bgcolor
1.460     albertel 8247:             no_auto_mt_title
                   8248:                            -> prevent &mt()ing the title arg
1.464     albertel 8249: 
1.306     albertel 8250: =cut
                   8251: 
                   8252: sub headtag {
1.313     albertel 8253:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8254:     
1.363     albertel 8255:     my $function = $args->{'function'} || &get_users_function();
                   8256:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8257:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8258:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8259:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8260: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8261: 		   #time(),
1.418     albertel 8262: 		   $env{'environment.color.timestamp'},
1.363     albertel 8263: 		   $function,$domain,$bgcolor);
                   8264: 
1.369     www      8265:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8266: 
1.308     albertel 8267:     my $result =
                   8268: 	'<head>'.
1.1160    raeburn  8269: 	&font_settings($args);
1.319     albertel 8270: 
1.1188    raeburn  8271:     my $inhibitprint;
                   8272:     if ($args->{'print_suppress'}) {
                   8273:         $inhibitprint = &print_suppression();
                   8274:     }
1.1064    raeburn  8275: 
1.461     albertel 8276:     if (!$args->{'frameset'}) {
                   8277: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8278:     }
1.962     droeschl 8279:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8280:         $result .= Apache::lonxml::display_title();
1.319     albertel 8281:     }
1.436     albertel 8282:     if (!$args->{'no_nav_bar'} 
                   8283: 	&& !$args->{'only_body'}
                   8284: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8285: 	$result .= &help_menu_js($httphost);
1.1032    www      8286:         $result.=&modal_window();
1.1038    www      8287:         $result.=&togglebox_script();
1.1034    www      8288:         $result.=&wishlist_window();
1.1041    www      8289:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8290:     } else {
                   8291:         if ($args->{'add_modal'}) {
                   8292:            $result.=&modal_window();
                   8293:         }
                   8294:         if ($args->{'add_wishlist'}) {
                   8295:            $result.=&wishlist_window();
                   8296:         }
1.1038    www      8297:         if ($args->{'add_togglebox'}) {
                   8298:            $result.=&togglebox_script();
                   8299:         }
1.1041    www      8300:         if ($args->{'add_progressbar'}) {
                   8301:            $result.=&LCprogressbarUpdate_script();
                   8302:         }
1.436     albertel 8303:     }
1.314     albertel 8304:     if (ref($args->{'redirect'})) {
1.414     albertel 8305: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8306: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8307: 	if (!$inhibit_continue) {
                   8308: 	    $env{'internal.head.redirect'} = $url;
                   8309: 	}
1.313     albertel 8310: 	$result.=<<ADDMETA
                   8311: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8312: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8313: ADDMETA
1.1210    raeburn  8314:     } else {
                   8315:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8316:             my $requrl = $env{'request.uri'};
                   8317:             if ($requrl eq '') {
                   8318:                 $requrl = $ENV{'REQUEST_URI'};
                   8319:                 $requrl =~ s/\?.+$//;
                   8320:             }
                   8321:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8322:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8323:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8324:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8325:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8326:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   8327:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8328:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   8329:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   8330:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8331:                             if (($newserver) && ($newserver ne $lonhost)) {
                   8332:                                 my $numsec = 5;
                   8333:                                 my $timeout = $numsec * 1000;
                   8334:                                 my ($newurl,$locknum,%locks,$msg);
                   8335:                                 if ($env{'request.role.adv'}) {
                   8336:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8337:                                 }
                   8338:                                 my $disable_submit = 0;
                   8339:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   8340:                                     $disable_submit = 1;
                   8341:                                 }
                   8342:                                 if ($locknum) {
                   8343:                                     my @lockinfo = sort(values(%locks));
                   8344:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   8345:                                            join(", ",sort(values(%locks)))."\\n".
                   8346:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   8347:                                 } else {
                   8348:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8349:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   8350:                                     }
                   8351:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8352:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8353:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8354:                                         $newurl .= '&role='.$env{'request.role'};
                   8355:                                     }
                   8356:                                     if ($env{'request.symb'}) {
                   8357:                                         $newurl .= '&symb='.$env{'request.symb'};
                   8358:                                     } else {
                   8359:                                         $newurl .= '&origurl='.$requrl;
                   8360:                                     }
                   8361:                                 }
1.1222    damieng  8362:                                 &js_escape(\$msg);
1.1210    raeburn  8363:                                 $result.=<<OFFLOAD
                   8364: <meta http-equiv="pragma" content="no-cache" />
                   8365: <script type="text/javascript">
1.1215    raeburn  8366: // <![CDATA[
1.1210    raeburn  8367: function LC_Offload_Now() {
                   8368:     var dest = "$newurl";
                   8369:     if (dest != '') {
                   8370:         window.location.href="$newurl";
                   8371:     }
                   8372: }
1.1214    raeburn  8373: \$(document).ready(function () {
                   8374:     window.alert('$msg');
                   8375:     if ($disable_submit) {
1.1210    raeburn  8376:         \$(".LC_hwk_submit").prop("disabled", true);
                   8377:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8378:     }
                   8379:     setTimeout('LC_Offload_Now()', $timeout);
                   8380: });
1.1215    raeburn  8381: // ]]>
1.1210    raeburn  8382: </script>
                   8383: OFFLOAD
                   8384:                             }
                   8385:                         }
                   8386:                     }
                   8387:                 }
                   8388:             }
                   8389:         }
1.313     albertel 8390:     }
1.306     albertel 8391:     if (!defined($title)) {
                   8392: 	$title = 'The LearningOnline Network with CAPA';
                   8393:     }
1.460     albertel 8394:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8395:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8396: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8397:     if (!$args->{'frameset'}) {
                   8398:         $result .= ' /';
                   8399:     }
                   8400:     $result .= '>' 
1.1064    raeburn  8401:         .$inhibitprint
1.414     albertel 8402: 	.$head_extra;
1.1242    raeburn  8403:     my $clientmobile;
                   8404:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8405:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8406:     } else {
                   8407:         $clientmobile = $env{'browser.mobile'};
                   8408:     }
                   8409:     if ($clientmobile) {
1.1137    raeburn  8410:         $result .= '
                   8411: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8412: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8413:     }
1.1278    raeburn  8414:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8415:     return $result.'</head>';
1.306     albertel 8416: }
                   8417: 
                   8418: =pod
                   8419: 
1.340     albertel 8420: =item * &font_settings()
                   8421: 
                   8422: Returns neccessary <meta> to set the proper encoding
                   8423: 
1.1160    raeburn  8424: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8425: 
                   8426: =cut
                   8427: 
                   8428: sub font_settings {
1.1160    raeburn  8429:     my ($args) = @_;
1.340     albertel 8430:     my $headerstring='';
1.1160    raeburn  8431:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8432:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8433:         $headerstring.=
                   8434:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8435:         if (!$args->{'frameset'}) {
                   8436: 	    $headerstring.= ' /';
                   8437:         }
                   8438: 	$headerstring .= '>'."\n";
1.340     albertel 8439:     }
                   8440:     return $headerstring;
                   8441: }
                   8442: 
1.341     albertel 8443: =pod
                   8444: 
1.1064    raeburn  8445: =item * &print_suppression()
                   8446: 
                   8447: In course context returns css which causes the body to be blank when media="print",
                   8448: if printout generation is unavailable for the current resource.
                   8449: 
                   8450: This could be because:
                   8451: 
                   8452: (a) printstartdate is in the future
                   8453: 
                   8454: (b) printenddate is in the past
                   8455: 
                   8456: (c) there is an active exam block with "printout"
                   8457: functionality blocked
                   8458: 
                   8459: Users with pav, pfo or evb privileges are exempt.
                   8460: 
                   8461: Inputs: none
                   8462: 
                   8463: =cut
                   8464: 
                   8465: 
                   8466: sub print_suppression {
                   8467:     my $noprint;
                   8468:     if ($env{'request.course.id'}) {
                   8469:         my $scope = $env{'request.course.id'};
                   8470:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8471:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8472:             return;
                   8473:         }
                   8474:         if ($env{'request.course.sec'} ne '') {
                   8475:             $scope .= "/$env{'request.course.sec'}";
                   8476:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8477:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8478:                 return;
1.1064    raeburn  8479:             }
                   8480:         }
                   8481:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8482:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8483:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8484:         if ($blocked) {
                   8485:             my $checkrole = "cm./$cdom/$cnum";
                   8486:             if ($env{'request.course.sec'} ne '') {
                   8487:                 $checkrole .= "/$env{'request.course.sec'}";
                   8488:             }
                   8489:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8490:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8491:                 $noprint = 1;
                   8492:             }
                   8493:         }
                   8494:         unless ($noprint) {
                   8495:             my $symb = &Apache::lonnet::symbread();
                   8496:             if ($symb ne '') {
                   8497:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8498:                 if (ref($navmap)) {
                   8499:                     my $res = $navmap->getBySymb($symb);
                   8500:                     if (ref($res)) {
                   8501:                         if (!$res->resprintable()) {
                   8502:                             $noprint = 1;
                   8503:                         }
                   8504:                     }
                   8505:                 }
                   8506:             }
                   8507:         }
                   8508:         if ($noprint) {
                   8509:             return <<"ENDSTYLE";
                   8510: <style type="text/css" media="print">
                   8511:     body { display:none }
                   8512: </style>
                   8513: ENDSTYLE
                   8514:         }
                   8515:     }
                   8516:     return;
                   8517: }
                   8518: 
                   8519: =pod
                   8520: 
1.341     albertel 8521: =item * &xml_begin()
                   8522: 
                   8523: Returns the needed doctype and <html>
                   8524: 
                   8525: Inputs: none
                   8526: 
                   8527: =cut
                   8528: 
                   8529: sub xml_begin {
1.1168    raeburn  8530:     my ($is_frameset) = @_;
1.341     albertel 8531:     my $output='';
                   8532: 
                   8533:     if ($env{'browser.mathml'}) {
                   8534: 	$output='<?xml version="1.0"?>'
                   8535:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8536: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8537:             
                   8538: #	    .'<!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">] >'
                   8539: 	    .'<!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">'
                   8540:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8541: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8542:     } elsif ($is_frameset) {
                   8543:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8544:                 '<html>'."\n";
1.341     albertel 8545:     } else {
1.1168    raeburn  8546: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8547:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8548:     }
                   8549:     return $output;
                   8550: }
1.340     albertel 8551: 
                   8552: =pod
                   8553: 
1.306     albertel 8554: =item * &start_page()
                   8555: 
                   8556: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8557: 
1.648     raeburn  8558: Inputs:
                   8559: 
                   8560: =over 4
                   8561: 
                   8562: $title - optional title for the page
                   8563: 
                   8564: $head_extra - optional extra HTML to incude inside the <head>
                   8565: 
                   8566: $args - additional optional args supported are:
                   8567: 
                   8568: =over 8
                   8569: 
                   8570:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8571:                                     arg on
1.814     bisitz   8572:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8573:              add_entries    -> additional attributes to add to the  <body>
                   8574:              domain         -> force to color decorate a page for a 
1.317     albertel 8575:                                     specific domain
1.648     raeburn  8576:              function       -> force usage of a specific rolish color
1.317     albertel 8577:                                     scheme
1.648     raeburn  8578:              redirect       -> see &headtag()
                   8579:              bgcolor        -> override the default page bg color
                   8580:              js_ready       -> return a string ready for being used in 
1.317     albertel 8581:                                     a javascript writeln
1.648     raeburn  8582:              html_encode    -> return a string ready for being used in 
1.320     albertel 8583:                                     a html attribute
1.648     raeburn  8584:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8585:                                     $forcereg arg
1.648     raeburn  8586:              frameset       -> if true will start with a <frameset>
1.330     albertel 8587:                                     rather than <body>
1.648     raeburn  8588:              skip_phases    -> hash ref of 
1.338     albertel 8589:                                     head -> skip the <html><head> generation
                   8590:                                     body -> skip all <body> generation
1.648     raeburn  8591:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8592:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8593:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  8594:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8595:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  8596:              group          -> includes the current group, if page is for a 
1.1274    raeburn  8597:                                specific group
                   8598:              use_absolute   -> for request for external resource or syllabus, this
                   8599:                                will contain https://<hostname> if server uses
                   8600:                                https (as per hosts.tab), but request is for http
                   8601:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8602: 
1.648     raeburn  8603: =back
1.460     albertel 8604: 
1.648     raeburn  8605: =back
1.562     albertel 8606: 
1.306     albertel 8607: =cut
                   8608: 
                   8609: sub start_page {
1.309     albertel 8610:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8611:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8612: 
1.315     albertel 8613:     $env{'internal.start_page'}++;
1.1096    raeburn  8614:     my ($result,@advtools);
1.964     droeschl 8615: 
1.338     albertel 8616:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8617:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8618:     }
                   8619:     
                   8620:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8621: 	if ($args->{'frameset'}) {
                   8622: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8623: 						$args->{'add_entries'});
                   8624: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8625:         } else {
                   8626:             $result .=
                   8627:                 &bodytag($title, 
                   8628:                          $args->{'function'},       $args->{'add_entries'},
                   8629:                          $args->{'only_body'},      $args->{'domain'},
                   8630:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8631:                          $args->{'bgcolor'},        $args,
                   8632:                          \@advtools);
1.831     bisitz   8633:         }
1.330     albertel 8634:     }
1.338     albertel 8635: 
1.315     albertel 8636:     if ($args->{'js_ready'}) {
1.713     kaisler  8637: 		$result = &js_ready($result);
1.315     albertel 8638:     }
1.320     albertel 8639:     if ($args->{'html_encode'}) {
1.713     kaisler  8640: 		$result = &html_encode($result);
                   8641:     }
                   8642: 
1.813     bisitz   8643:     # Preparation for new and consistent functionlist at top of screen
                   8644:     # if ($args->{'functionlist'}) {
                   8645:     #            $result .= &build_functionlist();
                   8646:     #}
                   8647: 
1.964     droeschl 8648:     # Don't add anything more if only_body wanted or in const space
                   8649:     return $result if    $args->{'only_body'} 
                   8650:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8651: 
                   8652:     #Breadcrumbs
1.758     kaisler  8653:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8654: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8655: 		#if any br links exists, add them to the breadcrumbs
                   8656: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8657: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8658: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8659: 			}
                   8660: 		}
1.1096    raeburn  8661:                 # if @advtools array contains items add then to the breadcrumbs
                   8662:                 if (@advtools > 0) {
                   8663:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8664:                 }
1.1272    raeburn  8665:                 my $menulink;
                   8666:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8667:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
                   8668:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   8669:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   8670:                      (!$env{'request.role.adv'}))) {
                   8671:                     $menulink = 0;
                   8672:                 } else {
                   8673:                     undef($menulink);
                   8674:                 }
1.758     kaisler  8675: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8676: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  8677: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  8678:                 } else {
1.1272    raeburn  8679: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8680: 		}
1.320     albertel 8681:     }
1.315     albertel 8682:     return $result;
1.306     albertel 8683: }
                   8684: 
                   8685: sub end_page {
1.315     albertel 8686:     my ($args) = @_;
                   8687:     $env{'internal.end_page'}++;
1.330     albertel 8688:     my $result;
1.335     albertel 8689:     if ($args->{'discussion'}) {
                   8690: 	my ($target,$parser);
                   8691: 	if (ref($args->{'discussion'})) {
                   8692: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8693: 				$args->{'discussion'}{'parser'});
                   8694: 	}
                   8695: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8696:     }
1.330     albertel 8697:     if ($args->{'frameset'}) {
                   8698: 	$result .= '</frameset>';
                   8699:     } else {
1.635     raeburn  8700: 	$result .= &endbodytag($args);
1.330     albertel 8701:     }
1.1080    raeburn  8702:     unless ($args->{'notbody'}) {
                   8703:         $result .= "\n</html>";
                   8704:     }
1.330     albertel 8705: 
1.315     albertel 8706:     if ($args->{'js_ready'}) {
1.317     albertel 8707: 	$result = &js_ready($result);
1.315     albertel 8708:     }
1.335     albertel 8709: 
1.320     albertel 8710:     if ($args->{'html_encode'}) {
                   8711: 	$result = &html_encode($result);
                   8712:     }
1.335     albertel 8713: 
1.315     albertel 8714:     return $result;
                   8715: }
                   8716: 
1.1034    www      8717: sub wishlist_window {
                   8718:     return(<<'ENDWISHLIST');
1.1046    raeburn  8719: <script type="text/javascript">
1.1034    www      8720: // <![CDATA[
                   8721: // <!-- BEGIN LON-CAPA Internal
                   8722: function set_wishlistlink(title, path) {
                   8723:     if (!title) {
                   8724:         title = document.title;
                   8725:         title = title.replace(/^LON-CAPA /,'');
                   8726:     }
1.1175    raeburn  8727:     title = encodeURIComponent(title);
1.1203    raeburn  8728:     title = title.replace("'","\\\'");
1.1034    www      8729:     if (!path) {
                   8730:         path = location.pathname;
                   8731:     }
1.1175    raeburn  8732:     path = encodeURIComponent(path);
1.1203    raeburn  8733:     path = path.replace("'","\\\'");
1.1034    www      8734:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8735:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8736: }
                   8737: // END LON-CAPA Internal -->
                   8738: // ]]>
                   8739: </script>
                   8740: ENDWISHLIST
                   8741: }
                   8742: 
1.1030    www      8743: sub modal_window {
                   8744:     return(<<'ENDMODAL');
1.1046    raeburn  8745: <script type="text/javascript">
1.1030    www      8746: // <![CDATA[
                   8747: // <!-- BEGIN LON-CAPA Internal
                   8748: var modalWindow = {
                   8749: 	parent:"body",
                   8750: 	windowId:null,
                   8751: 	content:null,
                   8752: 	width:null,
                   8753: 	height:null,
                   8754: 	close:function()
                   8755: 	{
                   8756: 	        $(".LCmodal-window").remove();
                   8757: 	        $(".LCmodal-overlay").remove();
                   8758: 	},
                   8759: 	open:function()
                   8760: 	{
                   8761: 		var modal = "";
                   8762: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8763: 		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;\">";
                   8764: 		modal += this.content;
                   8765: 		modal += "</div>";	
                   8766: 
                   8767: 		$(this.parent).append(modal);
                   8768: 
                   8769: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8770: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8771: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8772: 	}
                   8773: };
1.1140    raeburn  8774: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8775: 	{
1.1266    raeburn  8776:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8777: 		modalWindow.windowId = "myModal";
                   8778: 		modalWindow.width = width;
                   8779: 		modalWindow.height = height;
1.1196    raeburn  8780: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8781: 		modalWindow.open();
1.1208    raeburn  8782: 	};
1.1030    www      8783: // END LON-CAPA Internal -->
                   8784: // ]]>
                   8785: </script>
                   8786: ENDMODAL
                   8787: }
                   8788: 
                   8789: sub modal_link {
1.1140    raeburn  8790:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8791:     unless ($width) { $width=480; }
                   8792:     unless ($height) { $height=400; }
1.1031    www      8793:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8794:     unless ($transparency) { $transparency='true'; }
                   8795: 
1.1074    raeburn  8796:     my $target_attr;
                   8797:     if (defined($target)) {
                   8798:         $target_attr = 'target="'.$target.'"';
                   8799:     }
                   8800:     return <<"ENDLINK";
1.1140    raeburn  8801: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8802:            $linktext</a>
                   8803: ENDLINK
1.1030    www      8804: }
                   8805: 
1.1032    www      8806: sub modal_adhoc_script {
                   8807:     my ($funcname,$width,$height,$content)=@_;
                   8808:     return (<<ENDADHOC);
1.1046    raeburn  8809: <script type="text/javascript">
1.1032    www      8810: // <![CDATA[
                   8811:         var $funcname = function()
                   8812:         {
                   8813:                 modalWindow.windowId = "myModal";
                   8814:                 modalWindow.width = $width;
                   8815:                 modalWindow.height = $height;
                   8816:                 modalWindow.content = '$content';
                   8817:                 modalWindow.open();
                   8818:         };  
                   8819: // ]]>
                   8820: </script>
                   8821: ENDADHOC
                   8822: }
                   8823: 
1.1041    www      8824: sub modal_adhoc_inner {
                   8825:     my ($funcname,$width,$height,$content)=@_;
                   8826:     my $innerwidth=$width-20;
                   8827:     $content=&js_ready(
1.1140    raeburn  8828:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8829:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8830:                  $content.
1.1041    www      8831:                  &end_scrollbox().
1.1140    raeburn  8832:                  &end_page()
1.1041    www      8833:              );
                   8834:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8835: }
                   8836: 
                   8837: sub modal_adhoc_window {
                   8838:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8839:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8840:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8841: }
                   8842: 
                   8843: sub modal_adhoc_launch {
                   8844:     my ($funcname,$width,$height,$content)=@_;
                   8845:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8846: <script type="text/javascript">
                   8847: // <![CDATA[
                   8848: $funcname();
                   8849: // ]]>
                   8850: </script>
                   8851: ENDLAUNCH
                   8852: }
                   8853: 
                   8854: sub modal_adhoc_close {
                   8855:     return (<<ENDCLOSE);
                   8856: <script type="text/javascript">
                   8857: // <![CDATA[
                   8858: modalWindow.close();
                   8859: // ]]>
                   8860: </script>
                   8861: ENDCLOSE
                   8862: }
                   8863: 
1.1038    www      8864: sub togglebox_script {
                   8865:    return(<<ENDTOGGLE);
                   8866: <script type="text/javascript"> 
                   8867: // <![CDATA[
                   8868: function LCtoggleDisplay(id,hidetext,showtext) {
                   8869:    link = document.getElementById(id + "link").childNodes[0];
                   8870:    with (document.getElementById(id).style) {
                   8871:       if (display == "none" ) {
                   8872:           display = "inline";
                   8873:           link.nodeValue = hidetext;
                   8874:         } else {
                   8875:           display = "none";
                   8876:           link.nodeValue = showtext;
                   8877:        }
                   8878:    }
                   8879: }
                   8880: // ]]>
                   8881: </script>
                   8882: ENDTOGGLE
                   8883: }
                   8884: 
1.1039    www      8885: sub start_togglebox {
                   8886:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8887:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8888:     unless ($showtext) { $showtext=&mt('show'); }
                   8889:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8890:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8891:     return &start_data_table().
                   8892:            &start_data_table_header_row().
                   8893:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8894:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8895:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8896:            &end_data_table_header_row().
                   8897:            '<tr id="'.$id.'" style="display:none""><td>';
                   8898: }
                   8899: 
                   8900: sub end_togglebox {
                   8901:     return '</td></tr>'.&end_data_table();
                   8902: }
                   8903: 
1.1041    www      8904: sub LCprogressbar_script {
1.1302    raeburn  8905:    my ($id,$number_to_do)=@_;
                   8906:    if ($number_to_do) {
                   8907:        return(<<ENDPROGRESS);
1.1041    www      8908: <script type="text/javascript">
                   8909: // <![CDATA[
1.1045    www      8910: \$('#progressbar$id').progressbar({
1.1041    www      8911:   value: 0,
                   8912:   change: function(event, ui) {
                   8913:     var newVal = \$(this).progressbar('option', 'value');
                   8914:     \$('.pblabel', this).text(LCprogressTxt);
                   8915:   }
                   8916: });
                   8917: // ]]>
                   8918: </script>
                   8919: ENDPROGRESS
1.1302    raeburn  8920:    } else {
                   8921:        return(<<ENDPROGRESS);
                   8922: <script type="text/javascript">
                   8923: // <![CDATA[
                   8924: \$('#progressbar$id').progressbar({
                   8925:   value: false,
                   8926:   create: function(event, ui) {
                   8927:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   8928:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   8929:   }
                   8930: });
                   8931: // ]]>
                   8932: </script>
                   8933: ENDPROGRESS
                   8934:    }
1.1041    www      8935: }
                   8936: 
                   8937: sub LCprogressbarUpdate_script {
                   8938:    return(<<ENDPROGRESSUPDATE);
                   8939: <style type="text/css">
                   8940: .ui-progressbar { position:relative; }
1.1302    raeburn  8941: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
1.1041    www      8942: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8943: </style>
                   8944: <script type="text/javascript">
                   8945: // <![CDATA[
1.1045    www      8946: var LCprogressTxt='---';
                   8947: 
1.1302    raeburn  8948: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      8949:    LCprogressTxt=progresstext;
1.1302    raeburn  8950:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   8951:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   8952:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  8953:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   8954:    } else {
                   8955:        \$('#progressbar'+id).progressbar('value',percent);
                   8956:    }
1.1041    www      8957: }
                   8958: // ]]>
                   8959: </script>
                   8960: ENDPROGRESSUPDATE
                   8961: }
                   8962: 
1.1042    www      8963: my $LClastpercent;
1.1045    www      8964: my $LCidcnt;
                   8965: my $LCcurrentid;
1.1042    www      8966: 
1.1041    www      8967: sub LCprogressbar {
1.1302    raeburn  8968:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      8969:     $LClastpercent=0;
1.1045    www      8970:     $LCidcnt++;
                   8971:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  8972:     my ($starting,$content);
                   8973:     if ($number_to_do) {
                   8974:         $starting=&mt('Starting');
                   8975:         $content=(<<ENDPROGBAR);
                   8976: $preamble
1.1045    www      8977:   <div id="progressbar$LCcurrentid">
1.1041    www      8978:     <span class="pblabel">$starting</span>
                   8979:   </div>
                   8980: ENDPROGBAR
1.1302    raeburn  8981:     } else {
                   8982:         $starting=&mt('Loading...');
                   8983:         $LClastpercent='false';
                   8984:         $content=(<<ENDPROGBAR);
                   8985: $preamble
                   8986:   <div id="progressbar$LCcurrentid">
                   8987:       <div class="progress-label">$starting</div>
                   8988:   </div>
                   8989: ENDPROGBAR
                   8990:     }
                   8991:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      8992: }
                   8993: 
                   8994: sub LCprogressbarUpdate {
1.1302    raeburn  8995:     my ($r,$val,$text,$number_to_do)=@_;
                   8996:     if ($number_to_do) {
                   8997:         unless ($val) { 
                   8998:             if ($LClastpercent) {
                   8999:                 $val=$LClastpercent;
                   9000:             } else {
                   9001:                 $val=0;
                   9002:             }
                   9003:         }
                   9004:         if ($val<0) { $val=0; }
                   9005:         if ($val>100) { $val=0; }
                   9006:         $LClastpercent=$val;
                   9007:         unless ($text) { $text=$val.'%'; }
                   9008:     } else {
                   9009:         $val = 'false';
1.1042    www      9010:     }
1.1041    www      9011:     $text=&js_ready($text);
1.1044    www      9012:     &r_print($r,<<ENDUPDATE);
1.1041    www      9013: <script type="text/javascript">
                   9014: // <![CDATA[
1.1302    raeburn  9015: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9016: // ]]>
                   9017: </script>
                   9018: ENDUPDATE
1.1035    www      9019: }
                   9020: 
1.1042    www      9021: sub LCprogressbarClose {
                   9022:     my ($r)=@_;
                   9023:     $LClastpercent=0;
1.1044    www      9024:     &r_print($r,<<ENDCLOSE);
1.1042    www      9025: <script type="text/javascript">
                   9026: // <![CDATA[
1.1045    www      9027: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9028: // ]]>
                   9029: </script>
                   9030: ENDCLOSE
1.1044    www      9031: }
                   9032: 
                   9033: sub r_print {
                   9034:     my ($r,$to_print)=@_;
                   9035:     if ($r) {
                   9036:       $r->print($to_print);
                   9037:       $r->rflush();
                   9038:     } else {
                   9039:       print($to_print);
                   9040:     }
1.1042    www      9041: }
                   9042: 
1.320     albertel 9043: sub html_encode {
                   9044:     my ($result) = @_;
                   9045: 
1.322     albertel 9046:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9047:     
                   9048:     return $result;
                   9049: }
1.1044    www      9050: 
1.317     albertel 9051: sub js_ready {
                   9052:     my ($result) = @_;
                   9053: 
1.323     albertel 9054:     $result =~ s/[\n\r]/ /xmsg;
                   9055:     $result =~ s/\\/\\\\/xmsg;
                   9056:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9057:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9058:     
                   9059:     return $result;
                   9060: }
                   9061: 
1.315     albertel 9062: sub validate_page {
                   9063:     if (  exists($env{'internal.start_page'})
1.316     albertel 9064: 	  &&     $env{'internal.start_page'} > 1) {
                   9065: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9066: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9067: 				 $ENV{'request.filename'});
1.315     albertel 9068:     }
                   9069:     if (  exists($env{'internal.end_page'})
1.316     albertel 9070: 	  &&     $env{'internal.end_page'} > 1) {
                   9071: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9072: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9073: 				 $env{'request.filename'});
1.315     albertel 9074:     }
                   9075:     if (     exists($env{'internal.start_page'})
                   9076: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9077: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9078: 				 $env{'request.filename'});
1.315     albertel 9079:     }
                   9080:     if (   ! exists($env{'internal.start_page'})
                   9081: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9082: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9083: 				 $env{'request.filename'});
1.315     albertel 9084:     }
1.306     albertel 9085: }
1.315     albertel 9086: 
1.996     www      9087: 
                   9088: sub start_scrollbox {
1.1140    raeburn  9089:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9090:     unless ($outerwidth) { $outerwidth='520px'; }
                   9091:     unless ($width) { $width='500px'; }
                   9092:     unless ($height) { $height='200px'; }
1.1075    raeburn  9093:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9094:     if ($id ne '') {
1.1140    raeburn  9095:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9096:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9097:     }
1.1075    raeburn  9098:     if ($bgcolor ne '') {
                   9099:         $tdcol = "background-color: $bgcolor;";
                   9100:     }
1.1137    raeburn  9101:     my $nicescroll_js;
                   9102:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9103:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9104:     }
                   9105:     return <<"END";
                   9106: $nicescroll_js
                   9107: 
                   9108: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9109: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9110: END
                   9111: }
                   9112: 
                   9113: sub end_scrollbox {
                   9114:     return '</div></td></tr></table>';
                   9115: }
                   9116: 
                   9117: sub nicescroll_javascript {
                   9118:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9119:     my %options;
                   9120:     if (ref($cursor) eq 'HASH') {
                   9121:         %options = %{$cursor};
                   9122:     }
                   9123:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9124:         $options{'railalign'} = 'left';
                   9125:     }
                   9126:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9127:         my $function  = &get_users_function();
                   9128:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9129:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9130:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9131:         }
1.1140    raeburn  9132:     }
                   9133:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9134:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9135:             $options{'cursoropacity'}='1.0';
                   9136:         }
1.1140    raeburn  9137:     } else {
                   9138:         $options{'cursoropacity'}='1.0';
                   9139:     }
                   9140:     if ($options{'cursorfixedheight'} eq 'none') {
                   9141:         delete($options{'cursorfixedheight'});
                   9142:     } else {
                   9143:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9144:     }
                   9145:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9146:         delete($options{'railoffset'});
                   9147:     }
                   9148:     my @niceoptions;
                   9149:     while (my($key,$value) = each(%options)) {
                   9150:         if ($value =~ /^\{.+\}$/) {
                   9151:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9152:         } else {
1.1140    raeburn  9153:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9154:         }
1.1140    raeburn  9155:     }
                   9156:     my $nicescroll_js = '
1.1137    raeburn  9157: $(document).ready(
1.1140    raeburn  9158:       function() {
                   9159:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9160:       }
1.1137    raeburn  9161: );
                   9162: ';
1.1140    raeburn  9163:     if ($framecheck) {
                   9164:         $nicescroll_js .= '
                   9165: function expand_div(caller) {
                   9166:     if (top === self) {
                   9167:         document.getElementById("'.$id.'").style.width = "auto";
                   9168:         document.getElementById("'.$id.'").style.height = "auto";
                   9169:     } else {
                   9170:         try {
                   9171:             if (parent.frames) {
                   9172:                 if (parent.frames.length > 1) {
                   9173:                     var framesrc = parent.frames[1].location.href;
                   9174:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9175:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9176:                         document.getElementById("'.$id.'").style.width = "auto";
                   9177:                         document.getElementById("'.$id.'").style.height = "auto";
                   9178:                     }
                   9179:                 }
                   9180:             }
                   9181:         } catch (e) {
                   9182:             return;
                   9183:         }
1.1137    raeburn  9184:     }
1.1140    raeburn  9185:     return;
1.996     www      9186: }
1.1140    raeburn  9187: ';
                   9188:     }
                   9189:     if ($needjsready) {
                   9190:         $nicescroll_js = '
                   9191: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9192:     } else {
                   9193:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9194:     }
                   9195:     return $nicescroll_js;
1.996     www      9196: }
                   9197: 
1.318     albertel 9198: sub simple_error_page {
1.1150    bisitz   9199:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  9200:     my %displayargs;
1.1151    raeburn  9201:     if (ref($args) eq 'HASH') {
                   9202:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  9203:         if ($args->{'only_body'}) {
                   9204:             $displayargs{'only_body'} = 1;
                   9205:         }
                   9206:         if ($args->{'no_nav_bar'}) {
                   9207:             $displayargs{'no_nav_bar'} = 1;
                   9208:         }
1.1151    raeburn  9209:     } else {
                   9210:         $msg = &mt($msg);
                   9211:     }
1.1150    bisitz   9212: 
1.318     albertel 9213:     my $page =
1.1304    raeburn  9214: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   9215: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9216: 	&Apache::loncommon::end_page();
                   9217:     if (ref($r)) {
                   9218: 	$r->print($page);
1.327     albertel 9219: 	return;
1.318     albertel 9220:     }
                   9221:     return $page;
                   9222: }
1.347     albertel 9223: 
                   9224: {
1.610     albertel 9225:     my @row_count;
1.961     onken    9226: 
                   9227:     sub start_data_table_count {
                   9228:         unshift(@row_count, 0);
                   9229:         return;
                   9230:     }
                   9231: 
                   9232:     sub end_data_table_count {
                   9233:         shift(@row_count);
                   9234:         return;
                   9235:     }
                   9236: 
1.347     albertel 9237:     sub start_data_table {
1.1018    raeburn  9238: 	my ($add_class,$id) = @_;
1.422     albertel 9239: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9240:         my $table_id;
                   9241:         if (defined($id)) {
                   9242:             $table_id = ' id="'.$id.'"';
                   9243:         }
1.961     onken    9244: 	&start_data_table_count();
1.1018    raeburn  9245: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9246:     }
                   9247: 
                   9248:     sub end_data_table {
1.961     onken    9249: 	&end_data_table_count();
1.389     albertel 9250: 	return '</table>'."\n";;
1.347     albertel 9251:     }
                   9252: 
                   9253:     sub start_data_table_row {
1.974     wenzelju 9254: 	my ($add_class, $id) = @_;
1.610     albertel 9255: 	$row_count[0]++;
                   9256: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9257: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9258:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9259:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9260:     }
1.471     banghart 9261:     
                   9262:     sub continue_data_table_row {
1.974     wenzelju 9263: 	my ($add_class, $id) = @_;
1.610     albertel 9264: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9265: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9266:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9267:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9268:     }
1.347     albertel 9269: 
                   9270:     sub end_data_table_row {
1.389     albertel 9271: 	return '</tr>'."\n";;
1.347     albertel 9272:     }
1.367     www      9273: 
1.421     albertel 9274:     sub start_data_table_empty_row {
1.707     bisitz   9275: #	$row_count[0]++;
1.421     albertel 9276: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9277:     }
                   9278: 
                   9279:     sub end_data_table_empty_row {
                   9280: 	return '</tr>'."\n";;
                   9281:     }
                   9282: 
1.367     www      9283:     sub start_data_table_header_row {
1.389     albertel 9284: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9285:     }
                   9286: 
                   9287:     sub end_data_table_header_row {
1.389     albertel 9288: 	return '</tr>'."\n";;
1.367     www      9289:     }
1.890     droeschl 9290: 
                   9291:     sub data_table_caption {
                   9292:         my $caption = shift;
                   9293:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9294:     }
1.347     albertel 9295: }
                   9296: 
1.548     albertel 9297: =pod
                   9298: 
                   9299: =item * &inhibit_menu_check($arg)
                   9300: 
                   9301: Checks for a inhibitmenu state and generates output to preserve it
                   9302: 
                   9303: Inputs:         $arg - can be any of
                   9304:                      - undef - in which case the return value is a string 
                   9305:                                to add  into arguments list of a uri
                   9306:                      - 'input' - in which case the return value is a HTML
                   9307:                                  <form> <input> field of type hidden to
                   9308:                                  preserve the value
                   9309:                      - a url - in which case the return value is the url with
                   9310:                                the neccesary cgi args added to preserve the
                   9311:                                inhibitmenu state
                   9312:                      - a ref to a url - no return value, but the string is
                   9313:                                         updated to include the neccessary cgi
                   9314:                                         args to preserve the inhibitmenu state
                   9315: 
                   9316: =cut
                   9317: 
                   9318: sub inhibit_menu_check {
                   9319:     my ($arg) = @_;
                   9320:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9321:     if ($arg eq 'input') {
                   9322: 	if ($env{'form.inhibitmenu'}) {
                   9323: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9324: 	} else {
                   9325: 	    return
                   9326: 	}
                   9327:     }
                   9328:     if ($env{'form.inhibitmenu'}) {
                   9329: 	if (ref($arg)) {
                   9330: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9331: 	} elsif ($arg eq '') {
                   9332: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9333: 	} else {
                   9334: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9335: 	}
                   9336:     }
                   9337:     if (!ref($arg)) {
                   9338: 	return $arg;
                   9339:     }
                   9340: }
                   9341: 
1.251     albertel 9342: ###############################################
1.182     matthew  9343: 
                   9344: =pod
                   9345: 
1.549     albertel 9346: =back
                   9347: 
                   9348: =head1 User Information Routines
                   9349: 
                   9350: =over 4
                   9351: 
1.405     albertel 9352: =item * &get_users_function()
1.182     matthew  9353: 
                   9354: Used by &bodytag to determine the current users primary role.
                   9355: Returns either 'student','coordinator','admin', or 'author'.
                   9356: 
                   9357: =cut
                   9358: 
                   9359: ###############################################
                   9360: sub get_users_function {
1.815     tempelho 9361:     my $function = 'norole';
1.818     tempelho 9362:     if ($env{'request.role'}=~/^(st)/) {
                   9363:         $function='student';
                   9364:     }
1.907     raeburn  9365:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9366:         $function='coordinator';
                   9367:     }
1.258     albertel 9368:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9369:         $function='admin';
                   9370:     }
1.826     bisitz   9371:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9372:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9373:         $function='author';
                   9374:     }
                   9375:     return $function;
1.54      www      9376: }
1.99      www      9377: 
                   9378: ###############################################
                   9379: 
1.233     raeburn  9380: =pod
                   9381: 
1.821     raeburn  9382: =item * &show_course()
                   9383: 
                   9384: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9385: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9386: 
                   9387: Inputs:
                   9388: None
                   9389: 
                   9390: Outputs:
                   9391: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9392: 
                   9393: =cut
                   9394: 
                   9395: ###############################################
                   9396: sub show_course {
                   9397:     my $course = !$env{'user.adv'};
                   9398:     if (!$env{'user.adv'}) {
                   9399:         foreach my $env (keys(%env)) {
                   9400:             next if ($env !~ m/^user\.priv\./);
                   9401:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9402:                 $course = 0;
                   9403:                 last;
                   9404:             }
                   9405:         }
                   9406:     }
                   9407:     return $course;
                   9408: }
                   9409: 
                   9410: ###############################################
                   9411: 
                   9412: =pod
                   9413: 
1.542     raeburn  9414: =item * &check_user_status()
1.274     raeburn  9415: 
                   9416: Determines current status of supplied role for a
                   9417: specific user. Roles can be active, previous or future.
                   9418: 
                   9419: Inputs: 
                   9420: user's domain, user's username, course's domain,
1.375     raeburn  9421: course's number, optional section ID.
1.274     raeburn  9422: 
                   9423: Outputs:
                   9424: role status: active, previous or future. 
                   9425: 
                   9426: =cut
                   9427: 
                   9428: sub check_user_status {
1.412     raeburn  9429:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9430:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9431:     my @uroles = keys(%userinfo);
1.274     raeburn  9432:     my $srchstr;
                   9433:     my $active_chk = 'none';
1.412     raeburn  9434:     my $now = time;
1.274     raeburn  9435:     if (@uroles > 0) {
1.908     raeburn  9436:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9437:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9438:         } else {
1.412     raeburn  9439:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9440:         }
                   9441:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9442:             my $role_end = 0;
                   9443:             my $role_start = 0;
                   9444:             $active_chk = 'active';
1.412     raeburn  9445:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9446:                 $role_end = $1;
                   9447:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9448:                     $role_start = $1;
1.274     raeburn  9449:                 }
                   9450:             }
                   9451:             if ($role_start > 0) {
1.412     raeburn  9452:                 if ($now < $role_start) {
1.274     raeburn  9453:                     $active_chk = 'future';
                   9454:                 }
                   9455:             }
                   9456:             if ($role_end > 0) {
1.412     raeburn  9457:                 if ($now > $role_end) {
1.274     raeburn  9458:                     $active_chk = 'previous';
                   9459:                 }
                   9460:             }
                   9461:         }
                   9462:     }
                   9463:     return $active_chk;
                   9464: }
                   9465: 
                   9466: ###############################################
                   9467: 
                   9468: =pod
                   9469: 
1.405     albertel 9470: =item * &get_sections()
1.233     raeburn  9471: 
                   9472: Determines all the sections for a course including
                   9473: sections with students and sections containing other roles.
1.419     raeburn  9474: Incoming parameters: 
                   9475: 
                   9476: 1. domain
                   9477: 2. course number 
                   9478: 3. reference to array containing roles for which sections should 
                   9479: be gathered (optional).
                   9480: 4. reference to array containing status types for which sections 
                   9481: should be gathered (optional).
                   9482: 
                   9483: If the third argument is undefined, sections are gathered for any role. 
                   9484: If the fourth argument is undefined, sections are gathered for any status.
                   9485: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9486:  
1.374     raeburn  9487: Returns section hash (keys are section IDs, values are
                   9488: number of users in each section), subject to the
1.419     raeburn  9489: optional roles filter, optional status filter 
1.233     raeburn  9490: 
                   9491: =cut
                   9492: 
                   9493: ###############################################
                   9494: sub get_sections {
1.419     raeburn  9495:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9496:     if (!defined($cdom) || !defined($cnum)) {
                   9497:         my $cid =  $env{'request.course.id'};
                   9498: 
                   9499: 	return if (!defined($cid));
                   9500: 
                   9501:         $cdom = $env{'course.'.$cid.'.domain'};
                   9502:         $cnum = $env{'course.'.$cid.'.num'};
                   9503:     }
                   9504: 
                   9505:     my %sectioncount;
1.419     raeburn  9506:     my $now = time;
1.240     albertel 9507: 
1.1118    raeburn  9508:     my $check_students = 1;
                   9509:     my $only_students = 0;
                   9510:     if (ref($possible_roles) eq 'ARRAY') {
                   9511:         if (grep(/^st$/,@{$possible_roles})) {
                   9512:             if (@{$possible_roles} == 1) {
                   9513:                 $only_students = 1;
                   9514:             }
                   9515:         } else {
                   9516:             $check_students = 0;
                   9517:         }
                   9518:     }
                   9519: 
                   9520:     if ($check_students) { 
1.276     albertel 9521: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9522: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9523: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9524:         my $start_index = &Apache::loncoursedata::CL_START();
                   9525:         my $end_index = &Apache::loncoursedata::CL_END();
                   9526:         my $status;
1.366     albertel 9527: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9528: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9529: 				                     $data->[$status_index],
                   9530:                                                      $data->[$start_index],
                   9531:                                                      $data->[$end_index]);
                   9532:             if ($stu_status eq 'Active') {
                   9533:                 $status = 'active';
                   9534:             } elsif ($end < $now) {
                   9535:                 $status = 'previous';
                   9536:             } elsif ($start > $now) {
                   9537:                 $status = 'future';
                   9538:             } 
                   9539: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9540:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9541:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9542: 		    $sectioncount{$section}++;
                   9543:                 }
1.240     albertel 9544: 	    }
                   9545: 	}
                   9546:     }
1.1118    raeburn  9547:     if ($only_students) {
                   9548:         return %sectioncount;
                   9549:     }
1.240     albertel 9550:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9551:     foreach my $user (sort(keys(%courseroles))) {
                   9552: 	if ($user !~ /^(\w{2})/) { next; }
                   9553: 	my ($role) = ($user =~ /^(\w{2})/);
                   9554: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9555: 	my ($section,$status);
1.240     albertel 9556: 	if ($role eq 'cr' &&
                   9557: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9558: 	    $section=$1;
                   9559: 	}
                   9560: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9561: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9562:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9563:         if ($end == -1 && $start == -1) {
                   9564:             next; #deleted role
                   9565:         }
                   9566:         if (!defined($possible_status)) { 
                   9567:             $sectioncount{$section}++;
                   9568:         } else {
                   9569:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9570:                 $status = 'active';
                   9571:             } elsif ($end < $now) {
                   9572:                 $status = 'future';
                   9573:             } elsif ($start > $now) {
                   9574:                 $status = 'previous';
                   9575:             }
                   9576:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9577:                 $sectioncount{$section}++;
                   9578:             }
                   9579:         }
1.233     raeburn  9580:     }
1.366     albertel 9581:     return %sectioncount;
1.233     raeburn  9582: }
                   9583: 
1.274     raeburn  9584: ###############################################
1.294     raeburn  9585: 
                   9586: =pod
1.405     albertel 9587: 
                   9588: =item * &get_course_users()
                   9589: 
1.275     raeburn  9590: Retrieves usernames:domains for users in the specified course
                   9591: with specific role(s), and access status. 
                   9592: 
                   9593: Incoming parameters:
1.277     albertel 9594: 1. course domain
                   9595: 2. course number
                   9596: 3. access status: users must have - either active, 
1.275     raeburn  9597: previous, future, or all.
1.277     albertel 9598: 4. reference to array of permissible roles
1.288     raeburn  9599: 5. reference to array of section restrictions (optional)
                   9600: 6. reference to results object (hash of hashes).
                   9601: 7. reference to optional userdata hash
1.609     raeburn  9602: 8. reference to optional statushash
1.630     raeburn  9603: 9. flag if privileged users (except those set to unhide in
                   9604:    course settings) should be excluded    
1.609     raeburn  9605: Keys of top level results hash are roles.
1.275     raeburn  9606: Keys of inner hashes are username:domain, with 
                   9607: values set to access type.
1.288     raeburn  9608: Optional userdata hash returns an array with arguments in the 
                   9609: same order as loncoursedata::get_classlist() for student data.
                   9610: 
1.609     raeburn  9611: Optional statushash returns
                   9612: 
1.288     raeburn  9613: Entries for end, start, section and status are blank because
                   9614: of the possibility of multiple values for non-student roles.
                   9615: 
1.275     raeburn  9616: =cut
1.405     albertel 9617: 
1.275     raeburn  9618: ###############################################
1.405     albertel 9619: 
1.275     raeburn  9620: sub get_course_users {
1.630     raeburn  9621:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9622:     my %idx = ();
1.419     raeburn  9623:     my %seclists;
1.288     raeburn  9624: 
                   9625:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9626:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9627:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9628:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9629:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9630:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9631:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9632:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9633: 
1.290     albertel 9634:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9635:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9636:         my $now = time;
1.277     albertel 9637:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9638:             my $match = 0;
1.412     raeburn  9639:             my $secmatch = 0;
1.419     raeburn  9640:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9641:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9642:             if ($section eq '') {
                   9643:                 $section = 'none';
                   9644:             }
1.291     albertel 9645:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9646:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9647:                     $secmatch = 1;
                   9648:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9649:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9650:                         $secmatch = 1;
                   9651:                     }
                   9652:                 } else {  
1.419     raeburn  9653: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9654: 		        $secmatch = 1;
                   9655:                     }
1.290     albertel 9656: 		}
1.412     raeburn  9657:                 if (!$secmatch) {
                   9658:                     next;
                   9659:                 }
1.419     raeburn  9660:             }
1.275     raeburn  9661:             if (defined($$types{'active'})) {
1.288     raeburn  9662:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9663:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9664:                     $match = 1;
1.275     raeburn  9665:                 }
                   9666:             }
                   9667:             if (defined($$types{'previous'})) {
1.609     raeburn  9668:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9669:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9670:                     $match = 1;
1.275     raeburn  9671:                 }
                   9672:             }
                   9673:             if (defined($$types{'future'})) {
1.609     raeburn  9674:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9675:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9676:                     $match = 1;
1.275     raeburn  9677:                 }
                   9678:             }
1.609     raeburn  9679:             if ($match) {
                   9680:                 push(@{$seclists{$student}},$section);
                   9681:                 if (ref($userdata) eq 'HASH') {
                   9682:                     $$userdata{$student} = $$classlist{$student};
                   9683:                 }
                   9684:                 if (ref($statushash) eq 'HASH') {
                   9685:                     $statushash->{$student}{'st'}{$section} = $status;
                   9686:                 }
1.288     raeburn  9687:             }
1.275     raeburn  9688:         }
                   9689:     }
1.412     raeburn  9690:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9691:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9692:         my $now = time;
1.609     raeburn  9693:         my %displaystatus = ( previous => 'Expired',
                   9694:                               active   => 'Active',
                   9695:                               future   => 'Future',
                   9696:                             );
1.1121    raeburn  9697:         my (%nothide,@possdoms);
1.630     raeburn  9698:         if ($hidepriv) {
                   9699:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9700:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9701:                 if ($user !~ /:/) {
                   9702:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9703:                 } else {
                   9704:                     $nothide{$user} = 1;
                   9705:                 }
                   9706:             }
1.1121    raeburn  9707:             my @possdoms = ($cdom);
                   9708:             if ($coursehash{'checkforpriv'}) {
                   9709:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9710:             }
1.630     raeburn  9711:         }
1.439     raeburn  9712:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9713:             my $match = 0;
1.412     raeburn  9714:             my $secmatch = 0;
1.439     raeburn  9715:             my $status;
1.412     raeburn  9716:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9717:             $user =~ s/:$//;
1.439     raeburn  9718:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9719:             if ($end == -1 || $start == -1) {
                   9720:                 next;
                   9721:             }
                   9722:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9723:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9724:                 my ($uname,$udom) = split(/:/,$user);
                   9725:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9726:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9727:                         $secmatch = 1;
                   9728:                     } elsif ($usec eq '') {
1.420     albertel 9729:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9730:                             $secmatch = 1;
                   9731:                         }
                   9732:                     } else {
                   9733:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9734:                             $secmatch = 1;
                   9735:                         }
                   9736:                     }
                   9737:                     if (!$secmatch) {
                   9738:                         next;
                   9739:                     }
1.288     raeburn  9740:                 }
1.419     raeburn  9741:                 if ($usec eq '') {
                   9742:                     $usec = 'none';
                   9743:                 }
1.275     raeburn  9744:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9745:                     if ($hidepriv) {
1.1121    raeburn  9746:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9747:                             (!$nothide{$uname.':'.$udom})) {
                   9748:                             next;
                   9749:                         }
                   9750:                     }
1.503     raeburn  9751:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9752:                         $status = 'previous';
                   9753:                     } elsif ($start > $now) {
                   9754:                         $status = 'future';
                   9755:                     } else {
                   9756:                         $status = 'active';
                   9757:                     }
1.277     albertel 9758:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9759:                         if ($status eq $type) {
1.420     albertel 9760:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9761:                                 push(@{$$users{$role}{$user}},$type);
                   9762:                             }
1.288     raeburn  9763:                             $match = 1;
                   9764:                         }
                   9765:                     }
1.419     raeburn  9766:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9767:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9768: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9769:                         }
1.420     albertel 9770:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9771:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9772:                         }
1.609     raeburn  9773:                         if (ref($statushash) eq 'HASH') {
                   9774:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9775:                         }
1.275     raeburn  9776:                     }
                   9777:                 }
                   9778:             }
                   9779:         }
1.290     albertel 9780:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9781:             if ((defined($cdom)) && (defined($cnum))) {
                   9782:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9783:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9784:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9785:                     next if ($owner eq '');
                   9786:                     my ($ownername,$ownerdom);
                   9787:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9788:                         $ownername = $1;
                   9789:                         $ownerdom = $2;
                   9790:                     } else {
                   9791:                         $ownername = $owner;
                   9792:                         $ownerdom = $cdom;
                   9793:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9794:                     }
                   9795:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9796:                     if (defined($userdata) && 
1.609     raeburn  9797: 			!exists($$userdata{$owner})) {
                   9798: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9799:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9800:                             push(@{$seclists{$owner}},'none');
                   9801:                         }
                   9802:                         if (ref($statushash) eq 'HASH') {
                   9803:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9804:                         }
1.290     albertel 9805: 		    }
1.279     raeburn  9806:                 }
                   9807:             }
                   9808:         }
1.419     raeburn  9809:         foreach my $user (keys(%seclists)) {
                   9810:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9811:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9812:         }
1.275     raeburn  9813:     }
                   9814:     return;
                   9815: }
                   9816: 
1.288     raeburn  9817: sub get_user_info {
                   9818:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9819:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9820: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9821:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9822:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9823:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9824:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9825:     return;
                   9826: }
1.275     raeburn  9827: 
1.472     raeburn  9828: ###############################################
                   9829: 
                   9830: =pod
                   9831: 
                   9832: =item * &get_user_quota()
                   9833: 
1.1134    raeburn  9834: Retrieves quota assigned for storage of user files.
                   9835: Default is to report quota for portfolio files.
1.472     raeburn  9836: 
                   9837: Incoming parameters:
                   9838: 1. user's username
                   9839: 2. user's domain
1.1134    raeburn  9840: 3. quota name - portfolio, author, or course
1.1136    raeburn  9841:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  9842: 4. crstype - official, unofficial, textbook, placement or community, 
                   9843:    if quota name is course
1.472     raeburn  9844: 
                   9845: Returns:
1.1163    raeburn  9846: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9847: 2. (Optional) Type of setting: custom or default
                   9848:    (individually assigned or default for user's 
                   9849:    institutional status).
                   9850: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9851:    or student - types as defined in localenroll::inst_usertypes 
                   9852:    for user's domain, which determines default quota for user.
                   9853: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9854: 
                   9855: If a value has been stored in the user's environment, 
1.536     raeburn  9856: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9857: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9858: 
                   9859: =cut
                   9860: 
                   9861: ###############################################
                   9862: 
                   9863: 
                   9864: sub get_user_quota {
1.1136    raeburn  9865:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9866:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9867:     if (!defined($udom)) {
                   9868:         $udom = $env{'user.domain'};
                   9869:     }
                   9870:     if (!defined($uname)) {
                   9871:         $uname = $env{'user.name'};
                   9872:     }
                   9873:     if (($udom eq '' || $uname eq '') ||
                   9874:         ($udom eq 'public') && ($uname eq 'public')) {
                   9875:         $quota = 0;
1.536     raeburn  9876:         $quotatype = 'default';
                   9877:         $defquota = 0; 
1.472     raeburn  9878:     } else {
1.536     raeburn  9879:         my $inststatus;
1.1134    raeburn  9880:         if ($quotaname eq 'course') {
                   9881:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9882:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9883:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9884:             } else {
                   9885:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9886:                 $quota = $cenv{'internal.uploadquota'};
                   9887:             }
1.536     raeburn  9888:         } else {
1.1134    raeburn  9889:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9890:                 if ($quotaname eq 'author') {
                   9891:                     $quota = $env{'environment.authorquota'};
                   9892:                 } else {
                   9893:                     $quota = $env{'environment.portfolioquota'};
                   9894:                 }
                   9895:                 $inststatus = $env{'environment.inststatus'};
                   9896:             } else {
                   9897:                 my %userenv = 
                   9898:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9899:                                          'authorquota','inststatus'],$udom,$uname);
                   9900:                 my ($tmp) = keys(%userenv);
                   9901:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9902:                     if ($quotaname eq 'author') {
                   9903:                         $quota = $userenv{'authorquota'};
                   9904:                     } else {
                   9905:                         $quota = $userenv{'portfolioquota'};
                   9906:                     }
                   9907:                     $inststatus = $userenv{'inststatus'};
                   9908:                 } else {
                   9909:                     undef(%userenv);
                   9910:                 }
                   9911:             }
                   9912:         }
                   9913:         if ($quota eq '' || wantarray) {
                   9914:             if ($quotaname eq 'course') {
                   9915:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9916:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  9917:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   9918:                     ($crstype eq 'placement')) { 
1.1136    raeburn  9919:                     $defquota = $domdefs{$crstype.'quota'};
                   9920:                 }
                   9921:                 if ($defquota eq '') {
                   9922:                     $defquota = 500;
                   9923:                 }
1.1134    raeburn  9924:             } else {
                   9925:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9926:             }
                   9927:             if ($quota eq '') {
                   9928:                 $quota = $defquota;
                   9929:                 $quotatype = 'default';
                   9930:             } else {
                   9931:                 $quotatype = 'custom';
                   9932:             }
1.472     raeburn  9933:         }
                   9934:     }
1.536     raeburn  9935:     if (wantarray) {
                   9936:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9937:     } else {
                   9938:         return $quota;
                   9939:     }
1.472     raeburn  9940: }
                   9941: 
                   9942: ###############################################
                   9943: 
                   9944: =pod
                   9945: 
                   9946: =item * &default_quota()
                   9947: 
1.536     raeburn  9948: Retrieves default quota assigned for storage of user portfolio files,
                   9949: given an (optional) user's institutional status.
1.472     raeburn  9950: 
                   9951: Incoming parameters:
1.1142    raeburn  9952: 
1.472     raeburn  9953: 1. domain
1.536     raeburn  9954: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9955:    status types (e.g., faculty, staff, student etc.)
                   9956:    which apply to the user for whom the default is being retrieved.
                   9957:    If the institutional status string in undefined, the domain
1.1134    raeburn  9958:    default quota will be returned.
                   9959: 3.  quota name - portfolio, author, or course
                   9960:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9961: 
                   9962: Returns:
1.1142    raeburn  9963: 
1.1163    raeburn  9964: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9965: 2. (Optional) institutional type which determined the value of the
                   9966:    default quota.
1.472     raeburn  9967: 
                   9968: If a value has been stored in the domain's configuration db,
                   9969: it will return that, otherwise it returns 20 (for backwards 
                   9970: compatibility with domains which have not set up a configuration
1.1163    raeburn  9971: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9972: 
1.536     raeburn  9973: If the user's status includes multiple types (e.g., staff and student),
                   9974: the largest default quota which applies to the user determines the
                   9975: default quota returned.
                   9976: 
1.472     raeburn  9977: =cut
                   9978: 
                   9979: ###############################################
                   9980: 
                   9981: 
                   9982: sub default_quota {
1.1134    raeburn  9983:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9984:     my ($defquota,$settingstatus);
                   9985:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9986:                                             ['quotas'],$udom);
1.1134    raeburn  9987:     my $key = 'defaultquota';
                   9988:     if ($quotaname eq 'author') {
                   9989:         $key = 'authorquota';
                   9990:     }
1.622     raeburn  9991:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9992:         if ($inststatus ne '') {
1.765     raeburn  9993:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9994:             foreach my $item (@statuses) {
1.1134    raeburn  9995:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9996:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9997:                         if ($defquota eq '') {
1.1134    raeburn  9998:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9999:                             $settingstatus = $item;
1.1134    raeburn  10000:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10001:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10002:                             $settingstatus = $item;
                   10003:                         }
                   10004:                     }
1.1134    raeburn  10005:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10006:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10007:                         if ($defquota eq '') {
                   10008:                             $defquota = $quotahash{'quotas'}{$item};
                   10009:                             $settingstatus = $item;
                   10010:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10011:                             $defquota = $quotahash{'quotas'}{$item};
                   10012:                             $settingstatus = $item;
                   10013:                         }
1.536     raeburn  10014:                     }
                   10015:                 }
                   10016:             }
                   10017:         }
                   10018:         if ($defquota eq '') {
1.1134    raeburn  10019:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10020:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10021:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10022:                 $defquota = $quotahash{'quotas'}{'default'};
                   10023:             }
1.536     raeburn  10024:             $settingstatus = 'default';
1.1139    raeburn  10025:             if ($defquota eq '') {
                   10026:                 if ($quotaname eq 'author') {
                   10027:                     $defquota = 500;
                   10028:                 }
                   10029:             }
1.536     raeburn  10030:         }
                   10031:     } else {
                   10032:         $settingstatus = 'default';
1.1134    raeburn  10033:         if ($quotaname eq 'author') {
                   10034:             $defquota = 500;
                   10035:         } else {
                   10036:             $defquota = 20;
                   10037:         }
1.536     raeburn  10038:     }
                   10039:     if (wantarray) {
                   10040:         return ($defquota,$settingstatus);
1.472     raeburn  10041:     } else {
1.536     raeburn  10042:         return $defquota;
1.472     raeburn  10043:     }
                   10044: }
                   10045: 
1.1135    raeburn  10046: ###############################################
                   10047: 
                   10048: =pod
                   10049: 
1.1136    raeburn  10050: =item * &excess_filesize_warning()
1.1135    raeburn  10051: 
                   10052: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10053: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10054: space to be exceeded.
1.1136    raeburn  10055: 
                   10056: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10057: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10058: 
1.1165    raeburn  10059: Inputs: 7 
1.1136    raeburn  10060: 1. username or coursenum
1.1135    raeburn  10061: 2. domain
1.1136    raeburn  10062: 3. context ('author' or 'course')
1.1135    raeburn  10063: 4. filename of file for which action is being requested
                   10064: 5. filesize (kB) of file
                   10065: 6. action being taken: copy or upload.
1.1237    raeburn  10066: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10067: 
                   10068: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10069:          otherwise return null.
                   10070: 
                   10071: =back
1.1135    raeburn  10072: 
                   10073: =cut
                   10074: 
1.1136    raeburn  10075: sub excess_filesize_warning {
1.1165    raeburn  10076:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10077:     my $current_disk_usage = 0;
1.1165    raeburn  10078:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10079:     if ($context eq 'author') {
                   10080:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10081:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10082:     } else {
                   10083:         foreach my $subdir ('docs','supplemental') {
                   10084:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10085:         }
                   10086:     }
1.1135    raeburn  10087:     $disk_quota = int($disk_quota * 1000);
                   10088:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10089:         return '<p class="LC_warning">'.
1.1135    raeburn  10090:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10091:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10092:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10093:                             $disk_quota,$current_disk_usage).
                   10094:                '</p>';
                   10095:     }
                   10096:     return;
                   10097: }
                   10098: 
                   10099: ###############################################
                   10100: 
                   10101: 
1.1136    raeburn  10102: 
                   10103: 
1.384     raeburn  10104: sub get_secgrprole_info {
                   10105:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10106:     my %sections_count = &get_sections($cdom,$cnum);
                   10107:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10108:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10109:     my @groups = sort(keys(%curr_groups));
                   10110:     my $allroles = [];
                   10111:     my $rolehash;
                   10112:     my $accesshash = {
                   10113:                      active => 'Currently has access',
                   10114:                      future => 'Will have future access',
                   10115:                      previous => 'Previously had access',
                   10116:                   };
                   10117:     if ($needroles) {
                   10118:         $rolehash = {'all' => 'all'};
1.385     albertel 10119:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10120: 	if (&Apache::lonnet::error(%user_roles)) {
                   10121: 	    undef(%user_roles);
                   10122: 	}
                   10123:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10124:             my ($role)=split(/\:/,$item,2);
                   10125:             if ($role eq 'cr') { next; }
                   10126:             if ($role =~ /^cr/) {
                   10127:                 $$rolehash{$role} = (split('/',$role))[3];
                   10128:             } else {
                   10129:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10130:             }
                   10131:         }
                   10132:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10133:             push(@{$allroles},$key);
                   10134:         }
                   10135:         push (@{$allroles},'st');
                   10136:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10137:     }
                   10138:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10139: }
                   10140: 
1.555     raeburn  10141: sub user_picker {
1.1279    raeburn  10142:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10143:     my $currdom = $dom;
1.1253    raeburn  10144:     my @alldoms = &Apache::lonnet::all_domains();
                   10145:     if (@alldoms == 1) {
                   10146:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10147:                                                ['directorysrch'],$alldoms[0]);
                   10148:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10149:         my $showdom = $domdesc;
                   10150:         if ($showdom eq '') {
                   10151:             $showdom = $dom;
                   10152:         }
                   10153:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10154:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10155:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10156:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10157:             }
                   10158:         }
                   10159:     }
1.555     raeburn  10160:     my %curr_selected = (
                   10161:                         srchin => 'dom',
1.580     raeburn  10162:                         srchby => 'lastname',
1.555     raeburn  10163:                       );
                   10164:     my $srchterm;
1.625     raeburn  10165:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10166:         if ($srch->{'srchby'} ne '') {
                   10167:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10168:         }
                   10169:         if ($srch->{'srchin'} ne '') {
                   10170:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10171:         }
                   10172:         if ($srch->{'srchtype'} ne '') {
                   10173:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10174:         }
                   10175:         if ($srch->{'srchdomain'} ne '') {
                   10176:             $currdom = $srch->{'srchdomain'};
                   10177:         }
                   10178:         $srchterm = $srch->{'srchterm'};
                   10179:     }
1.1222    damieng  10180:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10181:                     'usr'       => 'Search criteria',
1.563     raeburn  10182:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10183:                     'uname'     => 'username',
                   10184:                     'lastname'  => 'last name',
1.555     raeburn  10185:                     'lastfirst' => 'last name, first name',
1.558     albertel 10186:                     'crs'       => 'in this course',
1.576     raeburn  10187:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10188:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10189:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10190:                     'exact'     => 'is',
                   10191:                     'contains'  => 'contains',
1.569     raeburn  10192:                     'begins'    => 'begins with',
1.1222    damieng  10193:                                        );
                   10194:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10195:                     'youm'      => "You must include some text to search for.",
                   10196:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10197:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10198:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10199:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10200:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10201:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10202:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10203:                                        );
1.1222    damieng  10204:     &html_escape(\%html_lt);
                   10205:     &js_escape(\%js_lt);
1.1255    raeburn  10206:     my $domform;
1.1277    raeburn  10207:     my $allow_blank = 1;
1.1255    raeburn  10208:     if ($fixeddom) {
1.1277    raeburn  10209:         $allow_blank = 0;
                   10210:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  10211:     } else {
1.1287    raeburn  10212:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  10213:         my ($trusted,$untrusted);
1.1287    raeburn  10214:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  10215:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  10216:         } elsif ($context eq 'author') {
1.1288    raeburn  10217:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  10218:         } elsif ($context eq 'domain') {
1.1288    raeburn  10219:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  10220:         }
1.1288    raeburn  10221:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  10222:     }
1.563     raeburn  10223:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10224: 
                   10225:     my @srchins = ('crs','dom','alc','instd');
                   10226: 
                   10227:     foreach my $option (@srchins) {
                   10228:         # FIXME 'alc' option unavailable until 
                   10229:         #       loncreateuser::print_user_query_page()
                   10230:         #       has been completed.
                   10231:         next if ($option eq 'alc');
1.880     raeburn  10232:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10233:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  10234:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10235:         if ($curr_selected{'srchin'} eq $option) {
                   10236:             $srchinsel .= ' 
1.1222    damieng  10237:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10238:         } else {
                   10239:             $srchinsel .= '
1.1222    damieng  10240:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10241:         }
1.555     raeburn  10242:     }
1.563     raeburn  10243:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10244: 
                   10245:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10246:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10247:         if ($curr_selected{'srchby'} eq $option) {
                   10248:             $srchbysel .= '
1.1222    damieng  10249:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10250:         } else {
                   10251:             $srchbysel .= '
1.1222    damieng  10252:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10253:          }
                   10254:     }
                   10255:     $srchbysel .= "\n  </select>\n";
                   10256: 
                   10257:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10258:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10259:         if ($curr_selected{'srchtype'} eq $option) {
                   10260:             $srchtypesel .= '
1.1222    damieng  10261:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10262:         } else {
                   10263:             $srchtypesel .= '
1.1222    damieng  10264:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10265:         }
                   10266:     }
                   10267:     $srchtypesel .= "\n  </select>\n";
                   10268: 
1.558     albertel 10269:     my ($newuserscript,$new_user_create);
1.994     raeburn  10270:     my $context_dom = $env{'request.role.domain'};
                   10271:     if ($context eq 'requestcrs') {
                   10272:         if ($env{'form.coursedom'} ne '') { 
                   10273:             $context_dom = $env{'form.coursedom'};
                   10274:         }
                   10275:     }
1.556     raeburn  10276:     if ($forcenewuser) {
1.576     raeburn  10277:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10278:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10279:                 if ($cancreate) {
                   10280:                     $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>';
                   10281:                 } else {
1.799     bisitz   10282:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10283:                     my %usertypetext = (
                   10284:                         official   => 'institutional',
                   10285:                         unofficial => 'non-institutional',
                   10286:                     );
1.799     bisitz   10287:                     $new_user_create = '<p class="LC_warning">'
                   10288:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10289:                                       .' '
                   10290:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10291:                                           ,'<a href="'.$helplink.'">','</a>')
                   10292:                                       .'</p><br />';
1.627     raeburn  10293:                 }
1.576     raeburn  10294:             }
                   10295:         }
                   10296: 
1.556     raeburn  10297:         $newuserscript = <<"ENDSCRIPT";
                   10298: 
1.570     raeburn  10299: function setSearch(createnew,callingForm) {
1.556     raeburn  10300:     if (createnew == 1) {
1.570     raeburn  10301:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10302:             if (callingForm.srchby.options[i].value == 'uname') {
                   10303:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10304:             }
                   10305:         }
1.570     raeburn  10306:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10307:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10308: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10309:             }
                   10310:         }
1.570     raeburn  10311:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10312:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10313:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10314:             }
                   10315:         }
1.570     raeburn  10316:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10317:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10318:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10319:             }
                   10320:         }
                   10321:     }
                   10322: }
                   10323: ENDSCRIPT
1.558     albertel 10324: 
1.556     raeburn  10325:     }
                   10326: 
1.555     raeburn  10327:     my $output = <<"END_BLOCK";
1.556     raeburn  10328: <script type="text/javascript">
1.824     bisitz   10329: // <![CDATA[
1.570     raeburn  10330: function validateEntry(callingForm) {
1.558     albertel 10331: 
1.556     raeburn  10332:     var checkok = 1;
1.558     albertel 10333:     var srchin;
1.570     raeburn  10334:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10335: 	if ( callingForm.srchin[i].checked ) {
                   10336: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10337: 	}
                   10338:     }
                   10339: 
1.570     raeburn  10340:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10341:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10342:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10343:     var srchterm =  callingForm.srchterm.value;
                   10344:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10345:     var msg = "";
                   10346: 
                   10347:     if (srchterm == "") {
                   10348:         checkok = 0;
1.1222    damieng  10349:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10350:     }
                   10351: 
1.569     raeburn  10352:     if (srchtype== 'begins') {
                   10353:         if (srchterm.length < 2) {
                   10354:             checkok = 0;
1.1222    damieng  10355:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10356:         }
                   10357:     }
                   10358: 
1.556     raeburn  10359:     if (srchtype== 'contains') {
                   10360:         if (srchterm.length < 3) {
                   10361:             checkok = 0;
1.1222    damieng  10362:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10363:         }
                   10364:     }
                   10365:     if (srchin == 'instd') {
                   10366:         if (srchdomain == '') {
                   10367:             checkok = 0;
1.1222    damieng  10368:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10369:         }
                   10370:     }
                   10371:     if (srchin == 'dom') {
                   10372:         if (srchdomain == '') {
                   10373:             checkok = 0;
1.1222    damieng  10374:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10375:         }
                   10376:     }
                   10377:     if (srchby == 'lastfirst') {
                   10378:         if (srchterm.indexOf(",") == -1) {
                   10379:             checkok = 0;
1.1222    damieng  10380:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10381:         }
                   10382:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10383:             checkok = 0;
1.1222    damieng  10384:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10385:         }
                   10386:     }
                   10387:     if (checkok == 0) {
1.1222    damieng  10388:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10389:         return;
                   10390:     }
                   10391:     if (checkok == 1) {
1.570     raeburn  10392:         callingForm.submit();
1.556     raeburn  10393:     }
                   10394: }
                   10395: 
                   10396: $newuserscript
                   10397: 
1.824     bisitz   10398: // ]]>
1.556     raeburn  10399: </script>
1.558     albertel 10400: 
                   10401: $new_user_create
                   10402: 
1.555     raeburn  10403: END_BLOCK
1.558     albertel 10404: 
1.876     raeburn  10405:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10406:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10407:                $domform.
                   10408:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10409:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10410:                $srchbysel.
                   10411:                $srchtypesel. 
                   10412:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10413:                $srchinsel.
                   10414:                &Apache::lonhtmlcommon::row_closure(1). 
                   10415:                &Apache::lonhtmlcommon::end_pick_box().
                   10416:                '<br />';
1.1253    raeburn  10417:     return ($output,1);
1.555     raeburn  10418: }
                   10419: 
1.612     raeburn  10420: sub user_rule_check {
1.615     raeburn  10421:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10422:     my ($response,%inst_response);
1.612     raeburn  10423:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10424:         if (keys(%{$usershash}) > 1) {
                   10425:             my (%by_username,%by_id,%userdoms);
                   10426:             my $checkid; 
                   10427:             if (ref($checks) eq 'HASH') {
                   10428:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10429:                     $checkid = 1;
                   10430:                 }
                   10431:             }
                   10432:             foreach my $user (keys(%{$usershash})) {
                   10433:                 my ($uname,$udom) = split(/:/,$user);
                   10434:                 if ($checkid) {
                   10435:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10436:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10437:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10438:                             $userdoms{$udom} = 1;
1.1227    raeburn  10439:                             if (ref($inst_results) eq 'HASH') {
                   10440:                                 $inst_results->{$uname.':'.$udom} = {};
                   10441:                             }
1.1226    raeburn  10442:                         }
                   10443:                     }
                   10444:                 } else {
                   10445:                     $by_username{$udom}{$uname} = 1;
                   10446:                     $userdoms{$udom} = 1;
1.1227    raeburn  10447:                     if (ref($inst_results) eq 'HASH') {
                   10448:                         $inst_results->{$uname.':'.$udom} = {};
                   10449:                     }
1.1226    raeburn  10450:                 }
                   10451:             }
                   10452:             foreach my $udom (keys(%userdoms)) {
                   10453:                 if (!$got_rules->{$udom}) {
                   10454:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10455:                                                              ['usercreation'],$udom);
                   10456:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10457:                         foreach my $item ('username','id') {
                   10458:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10459:                                 $$curr_rules{$udom}{$item} =
                   10460:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10461:                             }
                   10462:                         }
                   10463:                     }
                   10464:                     $got_rules->{$udom} = 1;
                   10465:                 }
1.612     raeburn  10466:             }
1.1226    raeburn  10467:             if ($checkid) {
                   10468:                 foreach my $udom (keys(%by_id)) {
                   10469:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10470:                     if ($outcome eq 'ok') {
1.1227    raeburn  10471:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10472:                             my $uname = $by_id{$udom}{$id};
                   10473:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10474:                         }
1.1226    raeburn  10475:                         if (ref($results) eq 'HASH') {
                   10476:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  10477:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10478:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10479:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10480:                                 }
1.1226    raeburn  10481:                             }
                   10482:                         }
                   10483:                     }
1.612     raeburn  10484:                 }
1.615     raeburn  10485:             } else {
1.1226    raeburn  10486:                 foreach my $udom (keys(%by_username)) {
                   10487:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10488:                     if ($outcome eq 'ok') {
1.1227    raeburn  10489:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10490:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10491:                         }
1.1226    raeburn  10492:                         if (ref($results) eq 'HASH') {
                   10493:                             foreach my $uname (keys(%{$results})) {
                   10494:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10495:                             }
                   10496:                         }
                   10497:                     }
                   10498:                 }
1.612     raeburn  10499:             }
1.1226    raeburn  10500:         } elsif (keys(%{$usershash}) == 1) {
                   10501:             my $user = (keys(%{$usershash}))[0];
                   10502:             my ($uname,$udom) = split(/:/,$user);
                   10503:             if (($udom ne '') && ($uname ne '')) {
                   10504:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10505:                     if (ref($checks) eq 'HASH') {
                   10506:                         if (defined($checks->{'username'})) {
                   10507:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   10508:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10509:                         } elsif (defined($checks->{'id'})) {
                   10510:                             if ($usershash->{$user}->{'id'} ne '') {
                   10511:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10512:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10513:                                                                   $usershash->{$user}->{'id'});
                   10514:                             } else {
                   10515:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10516:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10517:                             }
1.585     raeburn  10518:                         }
1.1226    raeburn  10519:                     } else {
                   10520:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10521:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10522:                        return;
                   10523:                     }
                   10524:                     if (!$got_rules->{$udom}) {
                   10525:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10526:                                                                  ['usercreation'],$udom);
                   10527:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10528:                             foreach my $item ('username','id') {
                   10529:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10530:                                    $$curr_rules{$udom}{$item} = 
                   10531:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10532:                                 }
                   10533:                             }
                   10534:                         }
                   10535:                         $got_rules->{$udom} = 1;
1.585     raeburn  10536:                     }
                   10537:                 }
1.1226    raeburn  10538:             } else {
                   10539:                 return;
                   10540:             }
                   10541:         } else {
                   10542:             return;
                   10543:         }
                   10544:         foreach my $user (keys(%{$usershash})) {
                   10545:             my ($uname,$udom) = split(/:/,$user);
                   10546:             next if (($udom eq '') || ($uname eq ''));
                   10547:             my $id;
1.1227    raeburn  10548:             if (ref($inst_results) eq 'HASH') {
                   10549:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10550:                     $id = $inst_results->{$user}->{'id'};
                   10551:                 }
                   10552:             }
                   10553:             if ($id eq '') { 
                   10554:                 if (ref($usershash->{$user})) {
                   10555:                     $id = $usershash->{$user}->{'id'};
                   10556:                 }
1.585     raeburn  10557:             }
1.612     raeburn  10558:             foreach my $item (keys(%{$checks})) {
                   10559:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10560:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10561:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10562:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10563:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10564:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10565:                                 if ($rule_check{$rule}) {
                   10566:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10567:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10568:                                         if (ref($inst_results) eq 'HASH') {
                   10569:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10570:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10571:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10572:                                                 } elsif ($item eq 'id') {
                   10573:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10574:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10575:                                                     }
1.615     raeburn  10576:                                                 }
1.612     raeburn  10577:                                             }
                   10578:                                         }
1.615     raeburn  10579:                                     }
                   10580:                                     last;
1.585     raeburn  10581:                                 }
                   10582:                             }
                   10583:                         }
                   10584:                     }
                   10585:                 }
                   10586:             }
                   10587:         }
                   10588:     }
1.612     raeburn  10589:     return;
                   10590: }
                   10591: 
                   10592: sub user_rule_formats {
                   10593:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10594:     my %text = ( 
                   10595:                  'username' => 'Usernames',
                   10596:                  'id'       => 'IDs',
                   10597:                );
                   10598:     my $output;
                   10599:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10600:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10601:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10602:             $output = '<br />'.
                   10603:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10604:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10605:                       ' <ul>';
1.612     raeburn  10606:             foreach my $rule (@{$ruleorder}) {
                   10607:                 if (ref($curr_rules) eq 'ARRAY') {
                   10608:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10609:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10610:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10611:                                         $rules->{$rule}{'desc'}.'</li>';
                   10612:                         }
                   10613:                     }
                   10614:                 }
                   10615:             }
                   10616:             $output .= '</ul>';
                   10617:         }
                   10618:     }
                   10619:     return $output;
                   10620: }
                   10621: 
                   10622: sub instrule_disallow_msg {
1.615     raeburn  10623:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10624:     my $response;
                   10625:     my %text = (
                   10626:                   item   => 'username',
                   10627:                   items  => 'usernames',
                   10628:                   match  => 'matches',
                   10629:                   do     => 'does',
                   10630:                   action => 'a username',
                   10631:                   one    => 'one',
                   10632:                );
                   10633:     if ($count > 1) {
                   10634:         $text{'item'} = 'usernames';
                   10635:         $text{'match'} ='match';
                   10636:         $text{'do'} = 'do';
                   10637:         $text{'action'} = 'usernames',
                   10638:         $text{'one'} = 'ones';
                   10639:     }
                   10640:     if ($checkitem eq 'id') {
                   10641:         $text{'items'} = 'IDs';
                   10642:         $text{'item'} = 'ID';
                   10643:         $text{'action'} = 'an ID';
1.615     raeburn  10644:         if ($count > 1) {
                   10645:             $text{'item'} = 'IDs';
                   10646:             $text{'action'} = 'IDs';
                   10647:         }
1.612     raeburn  10648:     }
1.674     bisitz   10649:     $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  10650:     if ($mode eq 'upload') {
                   10651:         if ($checkitem eq 'username') {
                   10652:             $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'}.");
                   10653:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10654:             $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  10655:         }
1.669     raeburn  10656:     } elsif ($mode eq 'selfcreate') {
                   10657:         if ($checkitem eq 'id') {
                   10658:             $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.");
                   10659:         }
1.615     raeburn  10660:     } else {
                   10661:         if ($checkitem eq 'username') {
                   10662:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10663:         } elsif ($checkitem eq 'id') {
                   10664:             $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.");
                   10665:         }
1.612     raeburn  10666:     }
                   10667:     return $response;
1.585     raeburn  10668: }
                   10669: 
1.624     raeburn  10670: sub personal_data_fieldtitles {
                   10671:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10672:                         id => 'Student/Employee ID',
                   10673:                         permanentemail => 'E-mail address',
                   10674:                         lastname => 'Last Name',
                   10675:                         firstname => 'First Name',
                   10676:                         middlename => 'Middle Name',
                   10677:                         generation => 'Generation',
                   10678:                         gen => 'Generation',
1.765     raeburn  10679:                         inststatus => 'Affiliation',
1.624     raeburn  10680:                    );
                   10681:     return %fieldtitles;
                   10682: }
                   10683: 
1.642     raeburn  10684: sub sorted_inst_types {
                   10685:     my ($dom) = @_;
1.1185    raeburn  10686:     my ($usertypes,$order);
                   10687:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10688:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10689:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10690:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10691:     } else {
                   10692:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10693:     }
1.642     raeburn  10694:     my $othertitle = &mt('All users');
                   10695:     if ($env{'request.course.id'}) {
1.668     raeburn  10696:         $othertitle  = &mt('Any users');
1.642     raeburn  10697:     }
                   10698:     my @types;
                   10699:     if (ref($order) eq 'ARRAY') {
                   10700:         @types = @{$order};
                   10701:     }
                   10702:     if (@types == 0) {
                   10703:         if (ref($usertypes) eq 'HASH') {
                   10704:             @types = sort(keys(%{$usertypes}));
                   10705:         }
                   10706:     }
                   10707:     if (keys(%{$usertypes}) > 0) {
                   10708:         $othertitle = &mt('Other users');
                   10709:     }
                   10710:     return ($othertitle,$usertypes,\@types);
                   10711: }
                   10712: 
1.645     raeburn  10713: sub get_institutional_codes {
                   10714:     my ($settings,$allcourses,$LC_code) = @_;
                   10715: # Get complete list of course sections to update
                   10716:     my @currsections = ();
                   10717:     my @currxlists = ();
                   10718:     my $coursecode = $$settings{'internal.coursecode'};
                   10719: 
                   10720:     if ($$settings{'internal.sectionnums'} ne '') {
                   10721:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10722:     }
                   10723: 
                   10724:     if ($$settings{'internal.crosslistings'} ne '') {
                   10725:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10726:     }
                   10727: 
                   10728:     if (@currxlists > 0) {
                   10729:         foreach (@currxlists) {
                   10730:             if (m/^([^:]+):(\w*)$/) {
                   10731:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  10732:                     push(@{$allcourses},$1);
1.645     raeburn  10733:                     $$LC_code{$1} = $2;
                   10734:                 }
                   10735:             }
                   10736:         }
                   10737:     }
                   10738:  
                   10739:     if (@currsections > 0) {
                   10740:         foreach (@currsections) {
                   10741:             if (m/^(\w+):(\w*)$/) {
                   10742:                 my $sec = $coursecode.$1;
                   10743:                 my $lc_sec = $2;
                   10744:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1263    raeburn  10745:                     push(@{$allcourses},$sec);
1.645     raeburn  10746:                     $$LC_code{$sec} = $lc_sec;
                   10747:                 }
                   10748:             }
                   10749:         }
                   10750:     }
                   10751:     return;
                   10752: }
                   10753: 
1.971     raeburn  10754: sub get_standard_codeitems {
                   10755:     return ('Year','Semester','Department','Number','Section');
                   10756: }
                   10757: 
1.112     bowersj2 10758: =pod
                   10759: 
1.780     raeburn  10760: =head1 Slot Helpers
                   10761: 
                   10762: =over 4
                   10763: 
                   10764: =item * sorted_slots()
                   10765: 
1.1040    raeburn  10766: Sorts an array of slot names in order of an optional sort key,
                   10767: default sort is by slot start time (earliest first). 
1.780     raeburn  10768: 
                   10769: Inputs:
                   10770: 
                   10771: =over 4
                   10772: 
                   10773: slotsarr  - Reference to array of unsorted slot names.
                   10774: 
                   10775: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10776: 
1.1040    raeburn  10777: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10778: 
1.549     albertel 10779: =back
                   10780: 
1.780     raeburn  10781: Returns:
                   10782: 
                   10783: =over 4
                   10784: 
1.1040    raeburn  10785: sorted   - An array of slot names sorted by a specified sort key 
                   10786:            (default sort key is start time of the slot).
1.780     raeburn  10787: 
                   10788: =back
                   10789: 
                   10790: =cut
                   10791: 
                   10792: 
                   10793: sub sorted_slots {
1.1040    raeburn  10794:     my ($slotsarr,$slots,$sortkey) = @_;
                   10795:     if ($sortkey eq '') {
                   10796:         $sortkey = 'starttime';
                   10797:     }
1.780     raeburn  10798:     my @sorted;
                   10799:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10800:         @sorted =
                   10801:             sort {
                   10802:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10803:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10804:                      }
                   10805:                      if (ref($slots->{$a})) { return -1;}
                   10806:                      if (ref($slots->{$b})) { return 1;}
                   10807:                      return 0;
                   10808:                  } @{$slotsarr};
                   10809:     }
                   10810:     return @sorted;
                   10811: }
                   10812: 
1.1040    raeburn  10813: =pod
                   10814: 
                   10815: =item * get_future_slots()
                   10816: 
                   10817: Inputs:
                   10818: 
                   10819: =over 4
                   10820: 
                   10821: cnum - course number
                   10822: 
                   10823: cdom - course domain
                   10824: 
                   10825: now - current UNIX time
                   10826: 
                   10827: symb - optional symb
                   10828: 
                   10829: =back
                   10830: 
                   10831: Returns:
                   10832: 
                   10833: =over 4
                   10834: 
                   10835: sorted_reservable - ref to array of student_schedulable slots currently 
                   10836:                     reservable, ordered by end date of reservation period.
                   10837: 
                   10838: reservable_now - ref to hash of student_schedulable slots currently
                   10839:                  reservable.
                   10840: 
                   10841:     Keys in inner hash are:
                   10842:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10843:     (b) endreserve: end date of reservation period.
                   10844:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10845:         selected.
1.1040    raeburn  10846: 
                   10847: sorted_future - ref to array of student_schedulable slots reservable in
                   10848:                 the future, ordered by start date of reservation period.
                   10849: 
                   10850: future_reservable - ref to hash of student_schedulable slots reservable
                   10851:                     in the future.
                   10852: 
                   10853:     Keys in inner hash are:
                   10854:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10855:     (b) startreserve: start date of reservation period.
                   10856:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10857:         selected.
1.1040    raeburn  10858: 
                   10859: =back
                   10860: 
                   10861: =cut
                   10862: 
                   10863: sub get_future_slots {
                   10864:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  10865:     my $map;
                   10866:     if ($symb) {
                   10867:         ($map) = &Apache::lonnet::decode_symb($symb);
                   10868:     }
1.1040    raeburn  10869:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10870:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10871:     foreach my $slot (keys(%slots)) {
                   10872:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10873:         if ($symb) {
1.1229    raeburn  10874:             if ($slots{$slot}->{'symb'} ne '') {
                   10875:                 my $canuse;
                   10876:                 my %oksymbs;
                   10877:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   10878:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   10879:                 if ($oksymbs{$symb}) {
                   10880:                     $canuse = 1;
                   10881:                 } else {
                   10882:                     foreach my $item (@slotsymbs) {
                   10883:                         if ($item =~ /\.(page|sequence)$/) {
                   10884:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   10885:                             if (($map ne '') && ($map eq $sloturl)) {
                   10886:                                 $canuse = 1;
                   10887:                                 last;
                   10888:                             }
                   10889:                         }
                   10890:                     }
                   10891:                 }
                   10892:                 next unless ($canuse);
                   10893:             }
1.1040    raeburn  10894:         }
                   10895:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10896:             ($slots{$slot}->{'endtime'} > $now)) {
                   10897:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10898:                 my $userallowed = 0;
                   10899:                 if ($slots{$slot}->{'allowedsections'}) {
                   10900:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10901:                     if (!defined($env{'request.role.sec'})
                   10902:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10903:                         $userallowed=1;
                   10904:                     } else {
                   10905:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10906:                             $userallowed=1;
                   10907:                         }
                   10908:                     }
                   10909:                     unless ($userallowed) {
                   10910:                         if (defined($env{'request.course.groups'})) {
                   10911:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10912:                             foreach my $group (@groups) {
                   10913:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10914:                                     $userallowed=1;
                   10915:                                     last;
                   10916:                                 }
                   10917:                             }
                   10918:                         }
                   10919:                     }
                   10920:                 }
                   10921:                 if ($slots{$slot}->{'allowedusers'}) {
                   10922:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10923:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10924:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10925:                         $userallowed = 1;
                   10926:                     }
                   10927:                 }
                   10928:                 next unless($userallowed);
                   10929:             }
                   10930:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10931:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10932:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  10933:             my $uniqueperiod;
                   10934:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10935:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10936:             }
1.1040    raeburn  10937:             if (($startreserve < $now) &&
                   10938:                 (!$endreserve || $endreserve > $now)) {
                   10939:                 my $lastres = $endreserve;
                   10940:                 if (!$lastres) {
                   10941:                     $lastres = $slots{$slot}->{'starttime'};
                   10942:                 }
                   10943:                 $reservable_now{$slot} = {
                   10944:                                            symb       => $symb,
1.1250    raeburn  10945:                                            endreserve => $lastres,
                   10946:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  10947:                                          };
                   10948:             } elsif (($startreserve > $now) &&
                   10949:                      (!$endreserve || $endreserve > $startreserve)) {
                   10950:                 $future_reservable{$slot} = {
                   10951:                                               symb         => $symb,
1.1250    raeburn  10952:                                               startreserve => $startreserve,
                   10953:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10954:                                             };
                   10955:             }
                   10956:         }
                   10957:     }
                   10958:     my @unsorted_reservable = keys(%reservable_now);
                   10959:     if (@unsorted_reservable > 0) {
                   10960:         @sorted_reservable = 
                   10961:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10962:     }
                   10963:     my @unsorted_future = keys(%future_reservable);
                   10964:     if (@unsorted_future > 0) {
                   10965:         @sorted_future =
                   10966:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10967:     }
                   10968:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10969: }
1.780     raeburn  10970: 
                   10971: =pod
                   10972: 
1.1057    foxr     10973: =back
                   10974: 
1.549     albertel 10975: =head1 HTTP Helpers
                   10976: 
                   10977: =over 4
                   10978: 
1.648     raeburn  10979: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10980: 
1.258     albertel 10981: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10982: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10983: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10984: 
                   10985: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10986: $possible_names is an ref to an array of form element names.  As an example:
                   10987: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10988: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10989: 
                   10990: =cut
1.1       albertel 10991: 
1.6       albertel 10992: sub get_unprocessed_cgi {
1.25      albertel 10993:   my ($query,$possible_names)= @_;
1.26      matthew  10994:   # $Apache::lonxml::debug=1;
1.356     albertel 10995:   foreach my $pair (split(/&/,$query)) {
                   10996:     my ($name, $value) = split(/=/,$pair);
1.369     www      10997:     $name = &unescape($name);
1.25      albertel 10998:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10999:       $value =~ tr/+/ /;
                   11000:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11001:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11002:     }
1.16      harris41 11003:   }
1.6       albertel 11004: }
                   11005: 
1.112     bowersj2 11006: =pod
                   11007: 
1.648     raeburn  11008: =item * &cacheheader() 
1.112     bowersj2 11009: 
                   11010: returns cache-controlling header code
                   11011: 
                   11012: =cut
                   11013: 
1.7       albertel 11014: sub cacheheader {
1.258     albertel 11015:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11016:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11017:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11018:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11019:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11020:     return $output;
1.7       albertel 11021: }
                   11022: 
1.112     bowersj2 11023: =pod
                   11024: 
1.648     raeburn  11025: =item * &no_cache($r) 
1.112     bowersj2 11026: 
                   11027: specifies header code to not have cache
                   11028: 
                   11029: =cut
                   11030: 
1.9       albertel 11031: sub no_cache {
1.216     albertel 11032:     my ($r) = @_;
                   11033:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11034: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11035:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11036:     $r->no_cache(1);
                   11037:     $r->header_out("Expires" => $date);
                   11038:     $r->header_out("Pragma" => "no-cache");
1.123     www      11039: }
                   11040: 
                   11041: sub content_type {
1.181     albertel 11042:     my ($r,$type,$charset) = @_;
1.299     foxr     11043:     if ($r) {
                   11044: 	#  Note that printout.pl calls this with undef for $r.
                   11045: 	&no_cache($r);
                   11046:     }
1.258     albertel 11047:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11048:     unless ($charset) {
                   11049: 	$charset=&Apache::lonlocal::current_encoding;
                   11050:     }
                   11051:     if ($charset) { $type.='; charset='.$charset; }
                   11052:     if ($r) {
                   11053: 	$r->content_type($type);
                   11054:     } else {
                   11055: 	print("Content-type: $type\n\n");
                   11056:     }
1.9       albertel 11057: }
1.25      albertel 11058: 
1.112     bowersj2 11059: =pod
                   11060: 
1.648     raeburn  11061: =item * &add_to_env($name,$value) 
1.112     bowersj2 11062: 
1.258     albertel 11063: adds $name to the %env hash with value
1.112     bowersj2 11064: $value, if $name already exists, the entry is converted to an array
                   11065: reference and $value is added to the array.
                   11066: 
                   11067: =cut
                   11068: 
1.25      albertel 11069: sub add_to_env {
                   11070:   my ($name,$value)=@_;
1.258     albertel 11071:   if (defined($env{$name})) {
                   11072:     if (ref($env{$name})) {
1.25      albertel 11073:       #already have multiple values
1.258     albertel 11074:       push(@{ $env{$name} },$value);
1.25      albertel 11075:     } else {
                   11076:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11077:       my $first=$env{$name};
                   11078:       undef($env{$name});
                   11079:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11080:     }
                   11081:   } else {
1.258     albertel 11082:     $env{$name}=$value;
1.25      albertel 11083:   }
1.31      albertel 11084: }
1.149     albertel 11085: 
                   11086: =pod
                   11087: 
1.648     raeburn  11088: =item * &get_env_multiple($name) 
1.149     albertel 11089: 
1.258     albertel 11090: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11091: values may be defined and end up as an array ref.
                   11092: 
                   11093: returns an array of values
                   11094: 
                   11095: =cut
                   11096: 
                   11097: sub get_env_multiple {
                   11098:     my ($name) = @_;
                   11099:     my @values;
1.258     albertel 11100:     if (defined($env{$name})) {
1.149     albertel 11101:         # exists is it an array
1.258     albertel 11102:         if (ref($env{$name})) {
                   11103:             @values=@{ $env{$name} };
1.149     albertel 11104:         } else {
1.258     albertel 11105:             $values[0]=$env{$name};
1.149     albertel 11106:         }
                   11107:     }
                   11108:     return(@values);
                   11109: }
                   11110: 
1.1249    damieng  11111: # Looks at given dependencies, and returns something depending on the context.
                   11112: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11113: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11114: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11115: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11116: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
                   11117: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11118: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11119: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11120: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11121: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11122: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11123: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11124: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
                   11125: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11126: sub ask_for_embedded_content {
1.1249    damieng  11127:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11128:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11129:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11130:         %currsubfile,%unused,$rem);
1.1071    raeburn  11131:     my $counter = 0;
                   11132:     my $numnew = 0;
1.987     raeburn  11133:     my $numremref = 0;
                   11134:     my $numinvalid = 0;
                   11135:     my $numpathchg = 0;
                   11136:     my $numexisting = 0;
1.1071    raeburn  11137:     my $numunused = 0;
                   11138:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11139:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11140:     my $heading = &mt('Upload embedded files');
                   11141:     my $buttontext = &mt('Upload');
                   11142: 
1.1249    damieng  11143:     # fills these variables based on the context:
                   11144:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11145:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11146:     if ($env{'request.course.id'}) {
1.1123    raeburn  11147:         if ($actionurl eq '/adm/dependencies') {
                   11148:             $navmap = Apache::lonnavmaps::navmap->new();
                   11149:         }
                   11150:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11151:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11152:     }
1.1123    raeburn  11153:     if (($actionurl eq '/adm/portfolio') || 
                   11154:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11155:         my $current_path='/';
                   11156:         if ($env{'form.currentpath'}) {
                   11157:             $current_path = $env{'form.currentpath'};
                   11158:         }
                   11159:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11160:             $udom = $cdom;
                   11161:             $uname = $cnum;
1.984     raeburn  11162:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11163:         } else {
                   11164:             $udom = $env{'user.domain'};
                   11165:             $uname = $env{'user.name'};
                   11166:             $url = '/userfiles/portfolio';
                   11167:         }
1.987     raeburn  11168:         $toplevel = $url.'/';
1.984     raeburn  11169:         $url .= $current_path;
                   11170:         $getpropath = 1;
1.987     raeburn  11171:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11172:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11173:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11174:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11175:         $toplevel = $url;
1.984     raeburn  11176:         if ($rest ne '') {
1.987     raeburn  11177:             $url .= $rest;
                   11178:         }
                   11179:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11180:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11181:             $url = $args->{'docs_url'};
                   11182:             $toplevel = $url;
1.1084    raeburn  11183:             if ($args->{'context'} eq 'paste') {
                   11184:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11185:                 ($path) = 
                   11186:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11187:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11188:                 $fileloc =~ s{^/}{};
                   11189:             }
1.1071    raeburn  11190:         }
1.1084    raeburn  11191:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11192:         if ($env{'request.course.id'} ne '') {
                   11193:             if (ref($args) eq 'HASH') {
                   11194:                 $url = $args->{'docs_url'};
                   11195:                 $title = $args->{'docs_title'};
1.1126    raeburn  11196:                 $toplevel = $url; 
                   11197:                 unless ($toplevel =~ m{^/}) {
                   11198:                     $toplevel = "/$url";
                   11199:                 }
1.1085    raeburn  11200:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11201:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11202:                     $path = $1;
                   11203:                 } else {
                   11204:                     ($path) =
                   11205:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11206:                 }
1.1195    raeburn  11207:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11208:                     $fileloc = $toplevel;
                   11209:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11210:                     my ($udom,$uname,$fname) =
                   11211:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11212:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11213:                 } else {
                   11214:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11215:                 }
1.1071    raeburn  11216:                 $fileloc =~ s{^/}{};
                   11217:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11218:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11219:             }
1.987     raeburn  11220:         }
1.1123    raeburn  11221:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11222:         $udom = $cdom;
                   11223:         $uname = $cnum;
                   11224:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11225:         $toplevel = $url;
                   11226:         $path = $url;
                   11227:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11228:         $fileloc =~ s{^/}{};
1.987     raeburn  11229:     }
1.1249    damieng  11230:     
                   11231:     # parses the dependency paths to get some info
                   11232:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11233:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11234:     # (will be completed later)
                   11235:     # $mapping:
                   11236:     #   for external URLs: external URL -> external URL
                   11237:     #   for relative paths: clean path -> original path
                   11238:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11239:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11240:     foreach my $file (keys(%{$allfiles})) {
                   11241:         my $embed_file;
                   11242:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11243:             $embed_file = $1;
                   11244:         } else {
                   11245:             $embed_file = $file;
                   11246:         }
1.1158    raeburn  11247:         my ($absolutepath,$cleaned_file);
                   11248:         if ($embed_file =~ m{^\w+://}) {
                   11249:             $cleaned_file = $embed_file;
1.1147    raeburn  11250:             $newfiles{$cleaned_file} = 1;
                   11251:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11252:         } else {
1.1158    raeburn  11253:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11254:             if ($embed_file =~ m{^/}) {
                   11255:                 $absolutepath = $embed_file;
                   11256:             }
1.1147    raeburn  11257:             if ($cleaned_file =~ m{/}) {
                   11258:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11259:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11260:                 my $item = $fname;
                   11261:                 if ($path ne '') {
                   11262:                     $item = $path.'/'.$fname;
                   11263:                     $subdependencies{$path}{$fname} = 1;
                   11264:                 } else {
                   11265:                     $dependencies{$item} = 1;
                   11266:                 }
                   11267:                 if ($absolutepath) {
                   11268:                     $mapping{$item} = $absolutepath;
                   11269:                 } else {
                   11270:                     $mapping{$item} = $embed_file;
                   11271:                 }
                   11272:             } else {
                   11273:                 $dependencies{$embed_file} = 1;
                   11274:                 if ($absolutepath) {
1.1147    raeburn  11275:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11276:                 } else {
1.1147    raeburn  11277:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11278:                 }
                   11279:             }
1.984     raeburn  11280:         }
                   11281:     }
1.1249    damieng  11282:     
                   11283:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11284:     # and lists
                   11285:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11286:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11287:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11288:     #                                    the path had to be cleaned up
                   11289:     # $existing: hash clean path -> 1 if the file exists
                   11290:     # $numexisting: number of keys in $existing
                   11291:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11292:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11293:     #                                      dependency subdirectories that are
                   11294:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11295:     my $dirptr = 16384;
1.984     raeburn  11296:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11297:         $currsubfile{$path} = {};
1.1123    raeburn  11298:         if (($actionurl eq '/adm/portfolio') || 
                   11299:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11300:             my ($sublistref,$listerror) =
                   11301:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11302:             if (ref($sublistref) eq 'ARRAY') {
                   11303:                 foreach my $line (@{$sublistref}) {
                   11304:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11305:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11306:                 }
1.984     raeburn  11307:             }
1.987     raeburn  11308:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11309:             if (opendir(my $dir,$url.'/'.$path)) {
                   11310:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11311:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11312:             }
1.1084    raeburn  11313:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11314:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11315:                   ($args->{'context'} eq 'paste')) ||
                   11316:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11317:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11318:                 my $dir;
                   11319:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11320:                     $dir = $fileloc;
                   11321:                 } else {
                   11322:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11323:                 }
1.1071    raeburn  11324:                 if ($dir ne '') {
                   11325:                     my ($sublistref,$listerror) =
                   11326:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11327:                     if (ref($sublistref) eq 'ARRAY') {
                   11328:                         foreach my $line (@{$sublistref}) {
                   11329:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11330:                                 undef,$mtime)=split(/\&/,$line,12);
                   11331:                             unless (($testdir&$dirptr) ||
                   11332:                                     ($file_name =~ /^\.\.?$/)) {
                   11333:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11334:                             }
                   11335:                         }
                   11336:                     }
                   11337:                 }
1.984     raeburn  11338:             }
                   11339:         }
                   11340:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11341:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11342:                 my $item = $path.'/'.$file;
                   11343:                 unless ($mapping{$item} eq $item) {
                   11344:                     $pathchanges{$item} = 1;
                   11345:                 }
                   11346:                 $existing{$item} = 1;
                   11347:                 $numexisting ++;
                   11348:             } else {
                   11349:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11350:             }
                   11351:         }
1.1071    raeburn  11352:         if ($actionurl eq '/adm/dependencies') {
                   11353:             foreach my $path (keys(%currsubfile)) {
                   11354:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11355:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11356:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11357:                              next if (($rem ne '') &&
                   11358:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11359:                                        (ref($navmap) &&
                   11360:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11361:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11362:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11363:                              $unused{$path.'/'.$file} = 1; 
                   11364:                          }
                   11365:                     }
                   11366:                 }
                   11367:             }
                   11368:         }
1.984     raeburn  11369:     }
1.1249    damieng  11370:     
                   11371:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11372:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11373:     my %currfile;
1.1123    raeburn  11374:     if (($actionurl eq '/adm/portfolio') ||
                   11375:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11376:         my ($dirlistref,$listerror) =
                   11377:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11378:         if (ref($dirlistref) eq 'ARRAY') {
                   11379:             foreach my $line (@{$dirlistref}) {
                   11380:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11381:                 $currfile{$file_name} = 1;
                   11382:             }
1.984     raeburn  11383:         }
1.987     raeburn  11384:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11385:         if (opendir(my $dir,$url)) {
1.987     raeburn  11386:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11387:             map {$currfile{$_} = 1;} @dir_list;
                   11388:         }
1.1084    raeburn  11389:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11390:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11391:               ($args->{'context'} eq 'paste')) ||
                   11392:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11393:         if ($env{'request.course.id'} ne '') {
                   11394:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11395:             if ($dir ne '') {
                   11396:                 my ($dirlistref,$listerror) =
                   11397:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11398:                 if (ref($dirlistref) eq 'ARRAY') {
                   11399:                     foreach my $line (@{$dirlistref}) {
                   11400:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11401:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11402:                         unless (($testdir&$dirptr) ||
                   11403:                                 ($file_name =~ /^\.\.?$/)) {
                   11404:                             $currfile{$file_name} = [$size,$mtime];
                   11405:                         }
                   11406:                     }
                   11407:                 }
                   11408:             }
                   11409:         }
1.984     raeburn  11410:     }
1.1249    damieng  11411:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11412:     # are not in subdirectories, using $currfile
1.984     raeburn  11413:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11414:         if (exists($currfile{$file})) {
1.987     raeburn  11415:             unless ($mapping{$file} eq $file) {
                   11416:                 $pathchanges{$file} = 1;
                   11417:             }
                   11418:             $existing{$file} = 1;
                   11419:             $numexisting ++;
                   11420:         } else {
1.984     raeburn  11421:             $newfiles{$file} = 1;
                   11422:         }
                   11423:     }
1.1071    raeburn  11424:     foreach my $file (keys(%currfile)) {
                   11425:         unless (($file eq $filename) ||
                   11426:                 ($file eq $filename.'.bak') ||
                   11427:                 ($dependencies{$file})) {
1.1085    raeburn  11428:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11429:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11430:                     next if (($rem ne '') &&
                   11431:                              (($env{"httpref.$rem".$file} ne '') ||
                   11432:                               (ref($navmap) &&
                   11433:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11434:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11435:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11436:                 }
1.1085    raeburn  11437:             }
1.1071    raeburn  11438:             $unused{$file} = 1;
                   11439:         }
                   11440:     }
1.1249    damieng  11441:     
                   11442:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11443:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11444:         ($args->{'context'} eq 'paste')) {
                   11445:         $counter = scalar(keys(%existing));
                   11446:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11447:         return ($output,$counter,$numpathchg,\%existing);
                   11448:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11449:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11450:         $counter = scalar(keys(%existing));
                   11451:         $numpathchg = scalar(keys(%pathchanges));
                   11452:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  11453:     }
1.1249    damieng  11454:     
                   11455:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   11456:     
                   11457:     # $upload_output: missing dependencies (with upload form)
                   11458:     # $modify_output: uploaded dependencies (in use)
                   11459:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  11460:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11461:         if ($actionurl eq '/adm/dependencies') {
                   11462:             next if ($embed_file =~ m{^\w+://});
                   11463:         }
1.660     raeburn  11464:         $upload_output .= &start_data_table_row().
1.1123    raeburn  11465:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11466:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11467:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  11468:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11469:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11470:         }
1.1123    raeburn  11471:         $upload_output .= '</td>';
1.1071    raeburn  11472:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  11473:             $upload_output.='<td align="right">'.
                   11474:                             '<span class="LC_info LC_fontsize_medium">'.
                   11475:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11476:             $numremref++;
1.660     raeburn  11477:         } elsif ($args->{'error_on_invalid_names'}
                   11478:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  11479:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11480:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11481:             $numinvalid++;
1.660     raeburn  11482:         } else {
1.1123    raeburn  11483:             $upload_output .= '<td>'.
                   11484:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11485:                                                      $embed_file,\%mapping,
1.1071    raeburn  11486:                                                      $allfiles,$codebase,'upload');
                   11487:             $counter ++;
                   11488:             $numnew ++;
1.987     raeburn  11489:         }
                   11490:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11491:     }
                   11492:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11493:         if ($actionurl eq '/adm/dependencies') {
                   11494:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11495:             $modify_output .= &start_data_table_row().
                   11496:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11497:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11498:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11499:                               '<td>'.$size.'</td>'.
                   11500:                               '<td>'.$mtime.'</td>'.
                   11501:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11502:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11503:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11504:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11505:                               &embedded_file_element('upload_embedded',$counter,
                   11506:                                                      $embed_file,\%mapping,
                   11507:                                                      $allfiles,$codebase,'modify').
                   11508:                               '</div></td>'.
                   11509:                               &end_data_table_row()."\n";
                   11510:             $counter ++;
                   11511:         } else {
                   11512:             $upload_output .= &start_data_table_row().
1.1123    raeburn  11513:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11514:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11515:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11516:                               &Apache::loncommon::end_data_table_row()."\n";
                   11517:         }
                   11518:     }
                   11519:     my $delidx = $counter;
                   11520:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11521:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11522:         $delete_output .= &start_data_table_row().
                   11523:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11524:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11525:                           '<td>'.$size.'</td>'.
                   11526:                           '<td>'.$mtime.'</td>'.
                   11527:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11528:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11529:                           &embedded_file_element('upload_embedded',$delidx,
                   11530:                                                  $oldfile,\%mapping,$allfiles,
                   11531:                                                  $codebase,'delete').'</td>'.
                   11532:                           &end_data_table_row()."\n"; 
                   11533:         $numunused ++;
                   11534:         $delidx ++;
1.987     raeburn  11535:     }
                   11536:     if ($upload_output) {
                   11537:         $upload_output = &start_data_table().
                   11538:                          $upload_output.
                   11539:                          &end_data_table()."\n";
                   11540:     }
1.1071    raeburn  11541:     if ($modify_output) {
                   11542:         $modify_output = &start_data_table().
                   11543:                          &start_data_table_header_row().
                   11544:                          '<th>'.&mt('File').'</th>'.
                   11545:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11546:                          '<th>'.&mt('Modified').'</th>'.
                   11547:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11548:                          &end_data_table_header_row().
                   11549:                          $modify_output.
                   11550:                          &end_data_table()."\n";
                   11551:     }
                   11552:     if ($delete_output) {
                   11553:         $delete_output = &start_data_table().
                   11554:                          &start_data_table_header_row().
                   11555:                          '<th>'.&mt('File').'</th>'.
                   11556:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11557:                          '<th>'.&mt('Modified').'</th>'.
                   11558:                          '<th>'.&mt('Delete?').'</th>'.
                   11559:                          &end_data_table_header_row().
                   11560:                          $delete_output.
                   11561:                          &end_data_table()."\n";
                   11562:     }
1.987     raeburn  11563:     my $applies = 0;
                   11564:     if ($numremref) {
                   11565:         $applies ++;
                   11566:     }
                   11567:     if ($numinvalid) {
                   11568:         $applies ++;
                   11569:     }
                   11570:     if ($numexisting) {
                   11571:         $applies ++;
                   11572:     }
1.1071    raeburn  11573:     if ($counter || $numunused) {
1.987     raeburn  11574:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11575:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11576:                   $state.'<h3>'.$heading.'</h3>'; 
                   11577:         if ($actionurl eq '/adm/dependencies') {
                   11578:             if ($numnew) {
                   11579:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11580:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11581:                            $upload_output.'<br />'."\n";
                   11582:             }
                   11583:             if ($numexisting) {
                   11584:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11585:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11586:                            $modify_output.'<br />'."\n";
                   11587:                            $buttontext = &mt('Save changes');
                   11588:             }
                   11589:             if ($numunused) {
                   11590:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11591:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11592:                            $delete_output.'<br />'."\n";
                   11593:                            $buttontext = &mt('Save changes');
                   11594:             }
                   11595:         } else {
                   11596:             $output .= $upload_output.'<br />'."\n";
                   11597:         }
                   11598:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11599:                    $counter.'" />'."\n";
                   11600:         if ($actionurl eq '/adm/dependencies') { 
                   11601:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11602:                        $numnew.'" />'."\n";
                   11603:         } elsif ($actionurl eq '') {
1.987     raeburn  11604:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11605:         }
                   11606:     } elsif ($applies) {
                   11607:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11608:         if ($applies > 1) {
                   11609:             $output .=  
1.1123    raeburn  11610:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11611:             if ($numremref) {
                   11612:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11613:             }
                   11614:             if ($numinvalid) {
                   11615:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11616:             }
                   11617:             if ($numexisting) {
                   11618:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11619:             }
                   11620:             $output .= '</ul><br />';
                   11621:         } elsif ($numremref) {
                   11622:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11623:         } elsif ($numinvalid) {
                   11624:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11625:         } elsif ($numexisting) {
                   11626:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11627:         }
                   11628:         $output .= $upload_output.'<br />';
                   11629:     }
                   11630:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11631:     $chgcount = $counter;
1.987     raeburn  11632:     if (keys(%pathchanges) > 0) {
                   11633:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11634:             if ($counter) {
1.987     raeburn  11635:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11636:                                                   $embed_file,\%mapping,
1.1071    raeburn  11637:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11638:             } else {
                   11639:                 $pathchange_output .= 
                   11640:                     &start_data_table_row().
                   11641:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11642:                     $chgcount.'" checked="checked" /></td>'.
                   11643:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11644:                     '<td>'.$embed_file.
                   11645:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11646:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11647:                     '</td>'.&end_data_table_row();
1.660     raeburn  11648:             }
1.987     raeburn  11649:             $numpathchg ++;
                   11650:             $chgcount ++;
1.660     raeburn  11651:         }
                   11652:     }
1.1127    raeburn  11653:     if (($counter) || ($numunused)) {
1.987     raeburn  11654:         if ($numpathchg) {
                   11655:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11656:                        $numpathchg.'" />'."\n";
                   11657:         }
                   11658:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11659:             ($actionurl eq '/adm/imsimport')) {
                   11660:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11661:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11662:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11663:         } elsif ($actionurl eq '/adm/dependencies') {
                   11664:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11665:         }
1.1123    raeburn  11666:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11667:     } elsif ($numpathchg) {
                   11668:         my %pathchange = ();
                   11669:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11670:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11671:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11672:         }
1.987     raeburn  11673:     }
1.1071    raeburn  11674:     return ($output,$counter,$numpathchg);
1.987     raeburn  11675: }
                   11676: 
1.1147    raeburn  11677: =pod
                   11678: 
                   11679: =item * clean_path($name)
                   11680: 
                   11681: Performs clean-up of directories, subdirectories and filename in an
                   11682: embedded object, referenced in an HTML file which is being uploaded
                   11683: to a course or portfolio, where 
                   11684: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11685: checked.
                   11686: 
                   11687: Clean-up is similar to replacements in lonnet::clean_filename()
                   11688: except each / between sub-directory and next level is preserved.
                   11689: 
                   11690: =cut
                   11691: 
                   11692: sub clean_path {
                   11693:     my ($embed_file) = @_;
                   11694:     $embed_file =~s{^/+}{};
                   11695:     my @contents;
                   11696:     if ($embed_file =~ m{/}) {
                   11697:         @contents = split(/\//,$embed_file);
                   11698:     } else {
                   11699:         @contents = ($embed_file);
                   11700:     }
                   11701:     my $lastidx = scalar(@contents)-1;
                   11702:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11703:         $contents[$i]=~s{\\}{/}g;
                   11704:         $contents[$i]=~s/\s+/\_/g;
                   11705:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11706:         if ($i == $lastidx) {
                   11707:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11708:         }
                   11709:     }
                   11710:     if ($lastidx > 0) {
                   11711:         return join('/',@contents);
                   11712:     } else {
                   11713:         return $contents[0];
                   11714:     }
                   11715: }
                   11716: 
1.987     raeburn  11717: sub embedded_file_element {
1.1071    raeburn  11718:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11719:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11720:                    (ref($codebase) eq 'HASH'));
                   11721:     my $output;
1.1071    raeburn  11722:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11723:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11724:     }
                   11725:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11726:                &escape($embed_file).'" />';
                   11727:     unless (($context eq 'upload_embedded') && 
                   11728:             ($mapping->{$embed_file} eq $embed_file)) {
                   11729:         $output .='
                   11730:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11731:     }
                   11732:     my $attrib;
                   11733:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11734:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11735:     }
                   11736:     $output .=
                   11737:         "\n\t\t".
                   11738:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11739:         $attrib.'" />';
                   11740:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11741:         $output .=
                   11742:             "\n\t\t".
                   11743:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11744:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11745:     }
1.987     raeburn  11746:     return $output;
1.660     raeburn  11747: }
                   11748: 
1.1071    raeburn  11749: sub get_dependency_details {
                   11750:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11751:     my ($size,$mtime,$showsize,$showmtime);
                   11752:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11753:         if ($embed_file =~ m{/}) {
                   11754:             my ($path,$fname) = split(/\//,$embed_file);
                   11755:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11756:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11757:             }
                   11758:         } else {
                   11759:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11760:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11761:             }
                   11762:         }
                   11763:         $showsize = $size/1024.0;
                   11764:         $showsize = sprintf("%.1f",$showsize);
                   11765:         if ($mtime > 0) {
                   11766:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11767:         }
                   11768:     }
                   11769:     return ($showsize,$showmtime);
                   11770: }
                   11771: 
                   11772: sub ask_embedded_js {
                   11773:     return <<"END";
                   11774: <script type="text/javascript"">
                   11775: // <![CDATA[
                   11776: function toggleBrowse(counter) {
                   11777:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11778:     var fileid = document.getElementById('embedded_item_'+counter);
                   11779:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11780:     if (chkboxid.checked == true) {
                   11781:         uploaddivid.style.display='block';
                   11782:     } else {
                   11783:         uploaddivid.style.display='none';
                   11784:         fileid.value = '';
                   11785:     }
                   11786: }
                   11787: // ]]>
                   11788: </script>
                   11789: 
                   11790: END
                   11791: }
                   11792: 
1.661     raeburn  11793: sub upload_embedded {
                   11794:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11795:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11796:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11797:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11798:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11799:         my $orig_uploaded_filename =
                   11800:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11801:         foreach my $type ('orig','ref','attrib','codebase') {
                   11802:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11803:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11804:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11805:             }
                   11806:         }
1.661     raeburn  11807:         my ($path,$fname) =
                   11808:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11809:         # no path, whole string is fname
                   11810:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11811:         $fname = &Apache::lonnet::clean_filename($fname);
                   11812:         # See if there is anything left
                   11813:         next if ($fname eq '');
                   11814: 
                   11815:         # Check if file already exists as a file or directory.
                   11816:         my ($state,$msg);
                   11817:         if ($context eq 'portfolio') {
                   11818:             my $port_path = $dirpath;
                   11819:             if ($group ne '') {
                   11820:                 $port_path = "groups/$group/$port_path";
                   11821:             }
1.987     raeburn  11822:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11823:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11824:                                               $dir_root,$port_path,$disk_quota,
                   11825:                                               $current_disk_usage,$uname,$udom);
                   11826:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11827:                 || $state eq 'file_locked') {
1.661     raeburn  11828:                 $output .= $msg;
                   11829:                 next;
                   11830:             }
                   11831:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11832:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11833:             if ($state eq 'exists') {
                   11834:                 $output .= $msg;
                   11835:                 next;
                   11836:             }
                   11837:         }
                   11838:         # Check if extension is valid
                   11839:         if (($fname =~ /\.(\w+)$/) &&
                   11840:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   11841:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11842:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11843:             next;
                   11844:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11845:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11846:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11847:             next;
                   11848:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   11849:             $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  11850:             next;
                   11851:         }
                   11852:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  11853:         my $subdir = $path;
                   11854:         $subdir =~ s{/+$}{};
1.661     raeburn  11855:         if ($context eq 'portfolio') {
1.984     raeburn  11856:             my $result;
                   11857:             if ($state eq 'existingfile') {
                   11858:                 $result=
                   11859:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  11860:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11861:             } else {
1.984     raeburn  11862:                 $result=
                   11863:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11864:                                                     $dirpath.
1.1123    raeburn  11865:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11866:                 if ($result !~ m|^/uploaded/|) {
                   11867:                     $output .= '<span class="LC_error">'
                   11868:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11869:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11870:                                .'</span><br />';
                   11871:                     next;
                   11872:                 } else {
1.987     raeburn  11873:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11874:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11875:                 }
1.661     raeburn  11876:             }
1.1123    raeburn  11877:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  11878:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11879:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11880:             my $result =
1.1126    raeburn  11881:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11882:             if ($result !~ m|^/uploaded/|) {
                   11883:                 $output .= '<span class="LC_error">'
                   11884:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11885:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11886:                            .'</span><br />';
                   11887:                     next;
                   11888:             } else {
                   11889:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11890:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11891:                 if ($context eq 'syllabus') {
                   11892:                     &Apache::lonnet::make_public_indefinitely($result);
                   11893:                 }
1.987     raeburn  11894:             }
1.661     raeburn  11895:         } else {
                   11896: # Save the file
                   11897:             my $target = $env{'form.embedded_item_'.$i};
                   11898:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11899:             my $dest = $fullpath.$fname;
                   11900:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11901:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11902:             my $count;
                   11903:             my $filepath = $dir_root;
1.1027    raeburn  11904:             foreach my $subdir (@parts) {
                   11905:                 $filepath .= "/$subdir";
                   11906:                 if (!-e $filepath) {
1.661     raeburn  11907:                     mkdir($filepath,0770);
                   11908:                 }
                   11909:             }
                   11910:             my $fh;
                   11911:             if (!open($fh,'>'.$dest)) {
                   11912:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11913:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11914:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11915:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11916:                            '</span><br />';
                   11917:             } else {
                   11918:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11919:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11920:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11921:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11922:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11923:                               '</span><br />';
                   11924:                 } else {
1.987     raeburn  11925:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11926:                                $url.'</span>').'<br />';
                   11927:                     unless ($context eq 'testbank') {
                   11928:                         $footer .= &mt('View embedded file: [_1]',
                   11929:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11930:                     }
                   11931:                 }
                   11932:                 close($fh);
                   11933:             }
                   11934:         }
                   11935:         if ($env{'form.embedded_ref_'.$i}) {
                   11936:             $pathchange{$i} = 1;
                   11937:         }
                   11938:     }
                   11939:     if ($output) {
                   11940:         $output = '<p>'.$output.'</p>';
                   11941:     }
                   11942:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11943:     $returnflag = 'ok';
1.1071    raeburn  11944:     my $numpathchgs = scalar(keys(%pathchange));
                   11945:     if ($numpathchgs > 0) {
1.987     raeburn  11946:         if ($context eq 'portfolio') {
                   11947:             $output .= '<p>'.&mt('or').'</p>';
                   11948:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11949:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11950:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11951:             $returnflag = 'modify_orightml';
                   11952:         }
                   11953:     }
1.1071    raeburn  11954:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11955: }
                   11956: 
                   11957: sub modify_html_form {
                   11958:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11959:     my $end = 0;
                   11960:     my $modifyform;
                   11961:     if ($context eq 'upload_embedded') {
                   11962:         return unless (ref($pathchange) eq 'HASH');
                   11963:         if ($env{'form.number_embedded_items'}) {
                   11964:             $end += $env{'form.number_embedded_items'};
                   11965:         }
                   11966:         if ($env{'form.number_pathchange_items'}) {
                   11967:             $end += $env{'form.number_pathchange_items'};
                   11968:         }
                   11969:         if ($end) {
                   11970:             for (my $i=0; $i<$end; $i++) {
                   11971:                 if ($i < $env{'form.number_embedded_items'}) {
                   11972:                     next unless($pathchange->{$i});
                   11973:                 }
                   11974:                 $modifyform .=
                   11975:                     &start_data_table_row().
                   11976:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11977:                     'checked="checked" /></td>'.
                   11978:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11979:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11980:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11981:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11982:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11983:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11984:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11985:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11986:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11987:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11988:                     &end_data_table_row();
1.1071    raeburn  11989:             }
1.987     raeburn  11990:         }
                   11991:     } else {
                   11992:         $modifyform = $pathchgtable;
                   11993:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11994:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11995:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11996:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11997:         }
                   11998:     }
                   11999:     if ($modifyform) {
1.1071    raeburn  12000:         if ($actionurl eq '/adm/dependencies') {
                   12001:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12002:         }
1.987     raeburn  12003:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12004:                '<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".
                   12005:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12006:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12007:                '</ol></p>'."\n".'<p>'.
                   12008:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12009:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12010:                &start_data_table()."\n".
                   12011:                &start_data_table_header_row().
                   12012:                '<th>'.&mt('Change?').'</th>'.
                   12013:                '<th>'.&mt('Current reference').'</th>'.
                   12014:                '<th>'.&mt('Required reference').'</th>'.
                   12015:                &end_data_table_header_row()."\n".
                   12016:                $modifyform.
                   12017:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12018:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12019:                '</form>'."\n";
                   12020:     }
                   12021:     return;
                   12022: }
                   12023: 
                   12024: sub modify_html_refs {
1.1123    raeburn  12025:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12026:     my $container;
                   12027:     if ($context eq 'portfolio') {
                   12028:         $container = $env{'form.container'};
                   12029:     } elsif ($context eq 'coursedoc') {
                   12030:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12031:     } elsif ($context eq 'manage_dependencies') {
                   12032:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12033:         $container = "/$container";
1.1123    raeburn  12034:     } elsif ($context eq 'syllabus') {
                   12035:         $container = $url;
1.987     raeburn  12036:     } else {
1.1027    raeburn  12037:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12038:     }
                   12039:     my (%allfiles,%codebase,$output,$content);
                   12040:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12041:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12042:         if (wantarray) {
                   12043:             return ('',0,0); 
                   12044:         } else {
                   12045:             return;
                   12046:         }
                   12047:     }
                   12048:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12049:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12050:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12051:             if (wantarray) {
                   12052:                 return ('',0,0);
                   12053:             } else {
                   12054:                 return;
                   12055:             }
                   12056:         } 
1.987     raeburn  12057:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12058:         if ($content eq '-1') {
                   12059:             if (wantarray) {
                   12060:                 return ('',0,0);
                   12061:             } else {
                   12062:                 return;
                   12063:             }
                   12064:         }
1.987     raeburn  12065:     } else {
1.1071    raeburn  12066:         unless ($container =~ /^\Q$dir_root\E/) {
                   12067:             if (wantarray) {
                   12068:                 return ('',0,0);
                   12069:             } else {
                   12070:                 return;
                   12071:             }
                   12072:         } 
1.987     raeburn  12073:         if (open(my $fh,"<$container")) {
                   12074:             $content = join('', <$fh>);
                   12075:             close($fh);
                   12076:         } else {
1.1071    raeburn  12077:             if (wantarray) {
                   12078:                 return ('',0,0);
                   12079:             } else {
                   12080:                 return;
                   12081:             }
1.987     raeburn  12082:         }
                   12083:     }
                   12084:     my ($count,$codebasecount) = (0,0);
                   12085:     my $mm = new File::MMagic;
                   12086:     my $mime_type = $mm->checktype_contents($content);
                   12087:     if ($mime_type eq 'text/html') {
                   12088:         my $parse_result = 
                   12089:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12090:                                                     \%codebase,\$content);
                   12091:         if ($parse_result eq 'ok') {
                   12092:             foreach my $i (@changes) {
                   12093:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12094:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12095:                 if ($allfiles{$ref}) {
                   12096:                     my $newname =  $orig;
                   12097:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12098:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12099:                     if ($attrib_regexp =~ /:/) {
                   12100:                         $attrib_regexp =~ s/\:/|/g;
                   12101:                     }
                   12102:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12103:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12104:                         $count += $numchg;
1.1123    raeburn  12105:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12106:                         delete($allfiles{$ref});
1.987     raeburn  12107:                     }
                   12108:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12109:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12110:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12111:                         $codebasecount ++;
                   12112:                     }
                   12113:                 }
                   12114:             }
1.1123    raeburn  12115:             my $skiprewrites;
1.987     raeburn  12116:             if ($count || $codebasecount) {
                   12117:                 my $saveresult;
1.1071    raeburn  12118:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12119:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12120:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12121:                     if ($url eq $container) {
                   12122:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12123:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12124:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12125:                                             $fname.'</span>').'</p>';
1.987     raeburn  12126:                     } else {
                   12127:                          $output = '<p class="LC_error">'.
                   12128:                                    &mt('Error: update failed for: [_1].',
                   12129:                                    '<span class="LC_filename">'.
                   12130:                                    $container.'</span>').'</p>';
                   12131:                     }
1.1123    raeburn  12132:                     if ($context eq 'syllabus') {
                   12133:                         unless ($saveresult eq 'ok') {
                   12134:                             $skiprewrites = 1;
                   12135:                         }
                   12136:                     }
1.987     raeburn  12137:                 } else {
                   12138:                     if (open(my $fh,">$container")) {
                   12139:                         print $fh $content;
                   12140:                         close($fh);
                   12141:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12142:                                   $count,'<span class="LC_filename">'.
                   12143:                                   $container.'</span>').'</p>';
1.661     raeburn  12144:                     } else {
1.987     raeburn  12145:                          $output = '<p class="LC_error">'.
                   12146:                                    &mt('Error: could not update [_1].',
                   12147:                                    '<span class="LC_filename">'.
                   12148:                                    $container.'</span>').'</p>';
1.661     raeburn  12149:                     }
                   12150:                 }
                   12151:             }
1.1123    raeburn  12152:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12153:                 my ($actionurl,$state);
                   12154:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12155:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12156:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12157:                                               \%codebase,
                   12158:                                               {'context' => 'rewrites',
                   12159:                                                'ignore_remote_references' => 1,});
                   12160:                 if (ref($mapping) eq 'HASH') {
                   12161:                     my $rewrites = 0;
                   12162:                     foreach my $key (keys(%{$mapping})) {
                   12163:                         next if ($key =~ m{^https?://});
                   12164:                         my $ref = $mapping->{$key};
                   12165:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12166:                         my $attrib;
                   12167:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12168:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12169:                         }
                   12170:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12171:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12172:                             $rewrites += $numchg;
                   12173:                         }
                   12174:                     }
                   12175:                     if ($rewrites) {
                   12176:                         my $saveresult; 
                   12177:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12178:                         if ($url eq $container) {
                   12179:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12180:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12181:                                             $count,'<span class="LC_filename">'.
                   12182:                                             $fname.'</span>').'</p>';
                   12183:                         } else {
                   12184:                             $output .= '<p class="LC_error">'.
                   12185:                                        &mt('Error: could not update links in [_1].',
                   12186:                                        '<span class="LC_filename">'.
                   12187:                                        $container.'</span>').'</p>';
                   12188: 
                   12189:                         }
                   12190:                     }
                   12191:                 }
                   12192:             }
1.987     raeburn  12193:         } else {
                   12194:             &logthis('Failed to parse '.$container.
                   12195:                      ' to modify references: '.$parse_result);
1.661     raeburn  12196:         }
                   12197:     }
1.1071    raeburn  12198:     if (wantarray) {
                   12199:         return ($output,$count,$codebasecount);
                   12200:     } else {
                   12201:         return $output;
                   12202:     }
1.661     raeburn  12203: }
                   12204: 
                   12205: sub check_for_existing {
                   12206:     my ($path,$fname,$element) = @_;
                   12207:     my ($state,$msg);
                   12208:     if (-d $path.'/'.$fname) {
                   12209:         $state = 'exists';
                   12210:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12211:     } elsif (-e $path.'/'.$fname) {
                   12212:         $state = 'exists';
                   12213:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12214:     }
                   12215:     if ($state eq 'exists') {
                   12216:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12217:     }
                   12218:     return ($state,$msg);
                   12219: }
                   12220: 
                   12221: sub check_for_upload {
                   12222:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12223:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12224:     my $filesize = length($env{'form.'.$element});
                   12225:     if (!$filesize) {
                   12226:         my $msg = '<span class="LC_error">'.
                   12227:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12228:                       '<span class="LC_filename">'.$fname.'</span>',
                   12229:                       $filesize).'<br />'.
1.1007    raeburn  12230:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12231:                   '</span>';
                   12232:         return ('zero_bytes',$msg);
                   12233:     }
                   12234:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12235:     my $getpropath = 1;
1.1021    raeburn  12236:     my ($dirlistref,$listerror) =
                   12237:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12238:     my $found_file = 0;
                   12239:     my $locked_file = 0;
1.991     raeburn  12240:     my @lockers;
                   12241:     my $navmap;
                   12242:     if ($env{'request.course.id'}) {
                   12243:         $navmap = Apache::lonnavmaps::navmap->new();
                   12244:     }
1.1021    raeburn  12245:     if (ref($dirlistref) eq 'ARRAY') {
                   12246:         foreach my $line (@{$dirlistref}) {
                   12247:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12248:             if ($file_name eq $fname){
                   12249:                 $file_name = $path.$file_name;
                   12250:                 if ($group ne '') {
                   12251:                     $file_name = $group.$file_name;
                   12252:                 }
                   12253:                 $found_file = 1;
                   12254:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12255:                     foreach my $lock (@lockers) {
                   12256:                         if (ref($lock) eq 'ARRAY') {
                   12257:                             my ($symb,$crsid) = @{$lock};
                   12258:                             if ($crsid eq $env{'request.course.id'}) {
                   12259:                                 if (ref($navmap)) {
                   12260:                                     my $res = $navmap->getBySymb($symb);
                   12261:                                     foreach my $part (@{$res->parts()}) { 
                   12262:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12263:                                         unless (($slot_status == $res->RESERVED) ||
                   12264:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12265:                                             $locked_file = 1;
                   12266:                                         }
1.991     raeburn  12267:                                     }
1.1021    raeburn  12268:                                 } else {
                   12269:                                     $locked_file = 1;
1.991     raeburn  12270:                                 }
                   12271:                             } else {
                   12272:                                 $locked_file = 1;
                   12273:                             }
                   12274:                         }
1.1021    raeburn  12275:                    }
                   12276:                 } else {
                   12277:                     my @info = split(/\&/,$rest);
                   12278:                     my $currsize = $info[6]/1000;
                   12279:                     if ($currsize < $filesize) {
                   12280:                         my $extra = $filesize - $currsize;
                   12281:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12282:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12283:                                       &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   12284:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12285:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12286:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12287:                             return ('will_exceed_quota',$msg);
                   12288:                         }
1.984     raeburn  12289:                     }
                   12290:                 }
1.661     raeburn  12291:             }
                   12292:         }
                   12293:     }
                   12294:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12295:         my $msg = '<p class="LC_warning">'.
                   12296:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12297:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12298:         return ('will_exceed_quota',$msg);
                   12299:     } elsif ($found_file) {
                   12300:         if ($locked_file) {
1.1179    bisitz   12301:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12302:             $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   12303:             $msg .= '</p>';
1.661     raeburn  12304:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12305:             return ('file_locked',$msg);
                   12306:         } else {
1.1179    bisitz   12307:             my $msg = '<p class="LC_error">';
1.984     raeburn  12308:             $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   12309:             $msg .= '</p>';
1.984     raeburn  12310:             return ('existingfile',$msg);
1.661     raeburn  12311:         }
                   12312:     }
                   12313: }
                   12314: 
1.987     raeburn  12315: sub check_for_traversal {
                   12316:     my ($path,$url,$toplevel) = @_;
                   12317:     my @parts=split(/\//,$path);
                   12318:     my $cleanpath;
                   12319:     my $fullpath = $url;
                   12320:     for (my $i=0;$i<@parts;$i++) {
                   12321:         next if ($parts[$i] eq '.');
                   12322:         if ($parts[$i] eq '..') {
                   12323:             $fullpath =~ s{([^/]+/)$}{};
                   12324:         } else {
                   12325:             $fullpath .= $parts[$i].'/';
                   12326:         }
                   12327:     }
                   12328:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12329:         $cleanpath = $1;
                   12330:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12331:         my $curr_toprel = $1;
                   12332:         my @parts = split(/\//,$curr_toprel);
                   12333:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12334:         my @urlparts = split(/\//,$url_toprel);
                   12335:         my $doubledots;
                   12336:         my $startdiff = -1;
                   12337:         for (my $i=0; $i<@urlparts; $i++) {
                   12338:             if ($startdiff == -1) {
                   12339:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12340:                     $startdiff = $i;
                   12341:                     $doubledots .= '../';
                   12342:                 }
                   12343:             } else {
                   12344:                 $doubledots .= '../';
                   12345:             }
                   12346:         }
                   12347:         if ($startdiff > -1) {
                   12348:             $cleanpath = $doubledots;
                   12349:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12350:                 $cleanpath .= $parts[$i].'/';
                   12351:             }
                   12352:         }
                   12353:     }
                   12354:     $cleanpath =~ s{(/)$}{};
                   12355:     return $cleanpath;
                   12356: }
1.31      albertel 12357: 
1.1053    raeburn  12358: sub is_archive_file {
                   12359:     my ($mimetype) = @_;
                   12360:     if (($mimetype eq 'application/octet-stream') ||
                   12361:         ($mimetype eq 'application/x-stuffit') ||
                   12362:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12363:         return 1;
                   12364:     }
                   12365:     return;
                   12366: }
                   12367: 
                   12368: sub decompress_form {
1.1065    raeburn  12369:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12370:     my %lt = &Apache::lonlocal::texthash (
                   12371:         this => 'This file is an archive file.',
1.1067    raeburn  12372:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12373:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12374:         youm => 'You may wish to extract its contents.',
                   12375:         extr => 'Extract contents',
1.1067    raeburn  12376:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12377:         proa => 'Process automatically?',
1.1053    raeburn  12378:         yes  => 'Yes',
                   12379:         no   => 'No',
1.1067    raeburn  12380:         fold => 'Title for folder containing movie',
                   12381:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12382:     );
1.1065    raeburn  12383:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12384:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12385:     my $info = &list_archive_contents($fileloc,\@paths);
                   12386:     if (@paths) {
                   12387:         foreach my $path (@paths) {
                   12388:             $path =~ s{^/}{};
1.1067    raeburn  12389:             if ($path =~ m{^([^/]+)/$}) {
                   12390:                 $topdir = $1;
                   12391:             }
1.1065    raeburn  12392:             if ($path =~ m{^([^/]+)/}) {
                   12393:                 $toplevel{$1} = $path;
                   12394:             } else {
                   12395:                 $toplevel{$path} = $path;
                   12396:             }
                   12397:         }
                   12398:     }
1.1067    raeburn  12399:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12400:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12401:                         "$topdir/media/",
                   12402:                         "$topdir/media/$topdir.mp4",
                   12403:                         "$topdir/media/FirstFrame.png",
                   12404:                         "$topdir/media/player.swf",
                   12405:                         "$topdir/media/swfobject.js",
                   12406:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12407:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12408:                          "$topdir/$topdir.mp4",
                   12409:                          "$topdir/$topdir\_config.xml",
                   12410:                          "$topdir/$topdir\_controller.swf",
                   12411:                          "$topdir/$topdir\_embed.css",
                   12412:                          "$topdir/$topdir\_First_Frame.png",
                   12413:                          "$topdir/$topdir\_player.html",
                   12414:                          "$topdir/$topdir\_Thumbnails.png",
                   12415:                          "$topdir/playerProductInstall.swf",
                   12416:                          "$topdir/scripts/",
                   12417:                          "$topdir/scripts/config_xml.js",
                   12418:                          "$topdir/scripts/handlebars.js",
                   12419:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12420:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12421:                          "$topdir/scripts/modernizr.js",
                   12422:                          "$topdir/scripts/player-min.js",
                   12423:                          "$topdir/scripts/swfobject.js",
                   12424:                          "$topdir/skins/",
                   12425:                          "$topdir/skins/configuration_express.xml",
                   12426:                          "$topdir/skins/express_show/",
                   12427:                          "$topdir/skins/express_show/player-min.css",
                   12428:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12429:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12430:                          "$topdir/$topdir.mp4",
                   12431:                          "$topdir/$topdir\_config.xml",
                   12432:                          "$topdir/$topdir\_controller.swf",
                   12433:                          "$topdir/$topdir\_embed.css",
                   12434:                          "$topdir/$topdir\_First_Frame.png",
                   12435:                          "$topdir/$topdir\_player.html",
                   12436:                          "$topdir/$topdir\_Thumbnails.png",
                   12437:                          "$topdir/playerProductInstall.swf",
                   12438:                          "$topdir/scripts/",
                   12439:                          "$topdir/scripts/config_xml.js",
                   12440:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12441:                          "$topdir/skins/",
                   12442:                          "$topdir/skins/configuration_express.xml",
                   12443:                          "$topdir/skins/express_show/",
                   12444:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12445:                          "$topdir/skins/express_show/spritesheet.png",
                   12446:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12447:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12448:         if (@diffs == 0) {
1.1164    raeburn  12449:             $is_camtasia = 6;
                   12450:         } else {
1.1197    raeburn  12451:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12452:             if (@diffs == 0) {
                   12453:                 $is_camtasia = 8;
1.1197    raeburn  12454:             } else {
                   12455:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12456:                 if (@diffs == 0) {
                   12457:                     $is_camtasia = 8;
                   12458:                 }
1.1164    raeburn  12459:             }
1.1067    raeburn  12460:         }
                   12461:     }
                   12462:     my $output;
                   12463:     if ($is_camtasia) {
                   12464:         $output = <<"ENDCAM";
                   12465: <script type="text/javascript" language="Javascript">
                   12466: // <![CDATA[
                   12467: 
                   12468: function camtasiaToggle() {
                   12469:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12470:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  12471:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12472:                 document.getElementById('camtasia_titles').style.display='block';
                   12473:             } else {
                   12474:                 document.getElementById('camtasia_titles').style.display='none';
                   12475:             }
                   12476:         }
                   12477:     }
                   12478:     return;
                   12479: }
                   12480: 
                   12481: // ]]>
                   12482: </script>
                   12483: <p>$lt{'camt'}</p>
                   12484: ENDCAM
1.1065    raeburn  12485:     } else {
1.1067    raeburn  12486:         $output = '<p>'.$lt{'this'};
                   12487:         if ($info eq '') {
                   12488:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12489:         } else {
                   12490:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12491:                        '<div><pre>'.$info.'</pre></div>';
                   12492:         }
1.1065    raeburn  12493:     }
1.1067    raeburn  12494:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12495:     my $duplicates;
                   12496:     my $num = 0;
                   12497:     if (ref($dirlist) eq 'ARRAY') {
                   12498:         foreach my $item (@{$dirlist}) {
                   12499:             if (ref($item) eq 'ARRAY') {
                   12500:                 if (exists($toplevel{$item->[0]})) {
                   12501:                     $duplicates .= 
                   12502:                         &start_data_table_row().
                   12503:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12504:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12505:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12506:                         'value="1" />'.&mt('Yes').'</label>'.
                   12507:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12508:                         '<td>'.$item->[0].'</td>';
                   12509:                     if ($item->[2]) {
                   12510:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12511:                     } else {
                   12512:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12513:                     }
                   12514:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12515:                                    '<td>'.
                   12516:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12517:                                    '</td>'.
                   12518:                                    &end_data_table_row();
                   12519:                     $num ++;
                   12520:                 }
                   12521:             }
                   12522:         }
                   12523:     }
                   12524:     my $itemcount;
                   12525:     if (@paths > 0) {
                   12526:         $itemcount = scalar(@paths);
                   12527:     } else {
                   12528:         $itemcount = 1;
                   12529:     }
1.1067    raeburn  12530:     if ($is_camtasia) {
                   12531:         $output .= $lt{'auto'}.'<br />'.
                   12532:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  12533:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12534:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12535:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12536:                    $lt{'no'}.'</label></span><br />'.
                   12537:                    '<div id="camtasia_titles" style="display:block">'.
                   12538:                    &Apache::lonhtmlcommon::start_pick_box().
                   12539:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12540:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12541:                    &Apache::lonhtmlcommon::row_closure().
                   12542:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12543:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12544:                    &Apache::lonhtmlcommon::row_closure(1).
                   12545:                    &Apache::lonhtmlcommon::end_pick_box().
                   12546:                    '</div>';
                   12547:     }
1.1065    raeburn  12548:     $output .= 
                   12549:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12550:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12551:         "\n";
1.1065    raeburn  12552:     if ($duplicates ne '') {
                   12553:         $output .= '<p><span class="LC_warning">'.
                   12554:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12555:                    &start_data_table().
                   12556:                    &start_data_table_header_row().
                   12557:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12558:                    '<th>'.&mt('Name').'</th>'.
                   12559:                    '<th>'.&mt('Type').'</th>'.
                   12560:                    '<th>'.&mt('Size').'</th>'.
                   12561:                    '<th>'.&mt('Last modified').'</th>'.
                   12562:                    &end_data_table_header_row().
                   12563:                    $duplicates.
                   12564:                    &end_data_table().
                   12565:                    '</p>';
                   12566:     }
1.1067    raeburn  12567:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12568:     if (ref($hiddenelements) eq 'HASH') {
                   12569:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12570:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12571:         }
                   12572:     }
                   12573:     $output .= <<"END";
1.1067    raeburn  12574: <br />
1.1053    raeburn  12575: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12576: </form>
                   12577: $noextract
                   12578: END
                   12579:     return $output;
                   12580: }
                   12581: 
1.1065    raeburn  12582: sub decompression_utility {
                   12583:     my ($program) = @_;
                   12584:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12585:     my $location;
                   12586:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12587:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12588:                          '/usr/sbin/') {
                   12589:             if (-x $dir.$program) {
                   12590:                 $location = $dir.$program;
                   12591:                 last;
                   12592:             }
                   12593:         }
                   12594:     }
                   12595:     return $location;
                   12596: }
                   12597: 
                   12598: sub list_archive_contents {
                   12599:     my ($file,$pathsref) = @_;
                   12600:     my (@cmd,$output);
                   12601:     my $needsregexp;
                   12602:     if ($file =~ /\.zip$/) {
                   12603:         @cmd = (&decompression_utility('unzip'),"-l");
                   12604:         $needsregexp = 1;
                   12605:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12606:              ($file =~ /\.tgz$/)) {
                   12607:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12608:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12609:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12610:     } elsif ($file =~ m|\.tar$|) {
                   12611:         @cmd = (&decompression_utility('tar'),"-tf");
                   12612:     }
                   12613:     if (@cmd) {
                   12614:         undef($!);
                   12615:         undef($@);
                   12616:         if (open(my $fh,"-|", @cmd, $file)) {
                   12617:             while (my $line = <$fh>) {
                   12618:                 $output .= $line;
                   12619:                 chomp($line);
                   12620:                 my $item;
                   12621:                 if ($needsregexp) {
                   12622:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12623:                 } else {
                   12624:                     $item = $line;
                   12625:                 }
                   12626:                 if ($item ne '') {
                   12627:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12628:                         push(@{$pathsref},$item);
                   12629:                     } 
                   12630:                 }
                   12631:             }
                   12632:             close($fh);
                   12633:         }
                   12634:     }
                   12635:     return $output;
                   12636: }
                   12637: 
1.1053    raeburn  12638: sub decompress_uploaded_file {
                   12639:     my ($file,$dir) = @_;
                   12640:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12641:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12642:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12643:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12644:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12645:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12646:     my $decompressed = $env{'cgi.decompressed'};
                   12647:     &Apache::lonnet::delenv('cgi.file');
                   12648:     &Apache::lonnet::delenv('cgi.dir');
                   12649:     &Apache::lonnet::delenv('cgi.decompressed');
                   12650:     return ($decompressed,$result);
                   12651: }
                   12652: 
1.1055    raeburn  12653: sub process_decompression {
                   12654:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  12655:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12656:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12657:                &mt('Unexpected file path.').'</p>'."\n";
                   12658:     }
                   12659:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12660:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12661:                &mt('Unexpected course context.').'</p>'."\n";
                   12662:     }
1.1293    raeburn  12663:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  12664:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12665:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12666:     }
1.1055    raeburn  12667:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12668:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12669:         $error = &mt('Filename not a supported archive file type.').
                   12670:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12671:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12672:     } else {
                   12673:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12674:         if ($docuhome eq 'no_host') {
                   12675:             $error = &mt('Could not determine home server for course.');
                   12676:         } else {
                   12677:             my @ids=&Apache::lonnet::current_machine_ids();
                   12678:             my $currdir = "$dir_root/$destination";
                   12679:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12680:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12681:                        "$dir_root/$destination";
                   12682:             } else {
                   12683:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12684:                        "$dir_root/$docudom/$docuname/$destination";
                   12685:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12686:                     $error = &mt('Archive file not found.');
                   12687:                 }
                   12688:             }
1.1065    raeburn  12689:             my (@to_overwrite,@to_skip);
                   12690:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12691:                 my $total = $env{'form.archive_overwrite_total'};
                   12692:                 for (my $i=0; $i<$total; $i++) {
                   12693:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12694:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12695:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12696:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12697:                     }
                   12698:                 }
                   12699:             }
                   12700:             my $numskip = scalar(@to_skip);
1.1292    raeburn  12701:             my $numoverwrite = scalar(@to_overwrite);
                   12702:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  12703:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12704:             } elsif ($dir eq '') {
1.1055    raeburn  12705:                 $error = &mt('Directory containing archive file unavailable.');
                   12706:             } elsif (!$error) {
1.1065    raeburn  12707:                 my ($decompressed,$display);
1.1292    raeburn  12708:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12709:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12710:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  12711:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12712:                         ($decompressed,$display) = 
                   12713:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12714:                         foreach my $item (@to_skip) {
                   12715:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12716:                                 if (-f "$dir/$tempdir/$item") { 
                   12717:                                     unlink("$dir/$tempdir/$item");
                   12718:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  12719:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  12720:                                 }
                   12721:                             }
                   12722:                         }
                   12723:                         foreach my $item (@to_overwrite) {
                   12724:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12725:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12726:                                     if (-f "$dir/$item") {
                   12727:                                         unlink("$dir/$item");
                   12728:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  12729:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  12730:                                     }
                   12731:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12732:                                 }
1.1065    raeburn  12733:                             }
                   12734:                         }
1.1292    raeburn  12735:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  12736:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  12737:                         }
1.1065    raeburn  12738:                     }
                   12739:                 } else {
                   12740:                     ($decompressed,$display) = 
                   12741:                         &decompress_uploaded_file($file,$dir);
                   12742:                 }
1.1055    raeburn  12743:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12744:                     $output = '<p class="LC_info">'.
                   12745:                               &mt('Files extracted successfully from archive.').
                   12746:                               '</p>'."\n";
1.1055    raeburn  12747:                     my ($warning,$result,@contents);
                   12748:                     my ($newdirlistref,$newlisterror) =
                   12749:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12750:                                                  $docuname,1);
                   12751:                     my (%is_dir,%changes,@newitems);
                   12752:                     my $dirptr = 16384;
1.1065    raeburn  12753:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12754:                         foreach my $dir_line (@{$newdirlistref}) {
                   12755:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  12756:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  12757:                                 push(@newitems,$item);
                   12758:                                 if ($dirptr&$testdir) {
                   12759:                                     $is_dir{$item} = 1;
                   12760:                                 }
                   12761:                                 $changes{$item} = 1;
                   12762:                             }
                   12763:                         }
                   12764:                     }
                   12765:                     if (keys(%changes) > 0) {
                   12766:                         foreach my $item (sort(@newitems)) {
                   12767:                             if ($changes{$item}) {
                   12768:                                 push(@contents,$item);
                   12769:                             }
                   12770:                         }
                   12771:                     }
                   12772:                     if (@contents > 0) {
1.1067    raeburn  12773:                         my $wantform;
                   12774:                         unless ($env{'form.autoextract_camtasia'}) {
                   12775:                             $wantform = 1;
                   12776:                         }
1.1056    raeburn  12777:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12778:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12779:                                                                 $currdir,\%is_dir,
                   12780:                                                                 \%children,\%parent,
1.1056    raeburn  12781:                                                                 \@contents,\%dirorder,
                   12782:                                                                 \%titles,$wantform);
1.1055    raeburn  12783:                         if ($datatable ne '') {
                   12784:                             $output .= &archive_options_form('decompressed',$datatable,
                   12785:                                                              $count,$hiddenelem);
1.1065    raeburn  12786:                             my $startcount = 6;
1.1055    raeburn  12787:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12788:                                                            \%titles,\%children);
1.1055    raeburn  12789:                         }
1.1067    raeburn  12790:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  12791:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12792:                             my %displayed;
                   12793:                             my $total = 1;
                   12794:                             $env{'form.archive_directory'} = [];
                   12795:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12796:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12797:                                 $path =~ s{/$}{};
                   12798:                                 my $item;
                   12799:                                 if ($path ne '') {
                   12800:                                     $item = "$path/$titles{$i}";
                   12801:                                 } else {
                   12802:                                     $item = $titles{$i};
                   12803:                                 }
                   12804:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12805:                                 if ($item eq $contents[0]) {
                   12806:                                     push(@{$env{'form.archive_directory'}},$i);
                   12807:                                     $env{'form.archive_'.$i} = 'display';
                   12808:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12809:                                     $displayed{'folder'} = $i;
1.1164    raeburn  12810:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12811:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  12812:                                     $env{'form.archive_'.$i} = 'display';
                   12813:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12814:                                     $displayed{'web'} = $i;
                   12815:                                 } else {
1.1164    raeburn  12816:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12817:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12818:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12819:                                         push(@{$env{'form.archive_directory'}},$i);
                   12820:                                     }
                   12821:                                     $env{'form.archive_'.$i} = 'dependency';
                   12822:                                 }
                   12823:                                 $total ++;
                   12824:                             }
                   12825:                             for (my $i=1; $i<$total; $i++) {
                   12826:                                 next if ($i == $displayed{'web'});
                   12827:                                 next if ($i == $displayed{'folder'});
                   12828:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12829:                             }
                   12830:                             $env{'form.phase'} = 'decompress_cleanup';
                   12831:                             $env{'form.archivedelete'} = 1;
                   12832:                             $env{'form.archive_count'} = $total-1;
                   12833:                             $output .=
                   12834:                                 &process_extracted_files('coursedocs',$docudom,
                   12835:                                                          $docuname,$destination,
                   12836:                                                          $dir_root,$hiddenelem);
                   12837:                         }
1.1055    raeburn  12838:                     } else {
                   12839:                         $warning = &mt('No new items extracted from archive file.');
                   12840:                     }
                   12841:                 } else {
                   12842:                     $output = $display;
                   12843:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12844:                 }
                   12845:             }
                   12846:         }
                   12847:     }
                   12848:     if ($error) {
                   12849:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12850:                    $error.'</p>'."\n";
                   12851:     }
                   12852:     if ($warning) {
                   12853:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12854:     }
                   12855:     return $output;
                   12856: }
                   12857: 
                   12858: sub get_extracted {
1.1056    raeburn  12859:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12860:         $titles,$wantform) = @_;
1.1055    raeburn  12861:     my $count = 0;
                   12862:     my $depth = 0;
                   12863:     my $datatable;
1.1056    raeburn  12864:     my @hierarchy;
1.1055    raeburn  12865:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12866:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12867:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12868:     foreach my $item (@{$contents}) {
                   12869:         $count ++;
1.1056    raeburn  12870:         @{$dirorder->{$count}} = @hierarchy;
                   12871:         $titles->{$count} = $item;
1.1055    raeburn  12872:         &archive_hierarchy($depth,$count,$parent,$children);
                   12873:         if ($wantform) {
                   12874:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12875:                                        $currdir,$depth,$count);
                   12876:         }
                   12877:         if ($is_dir->{$item}) {
                   12878:             $depth ++;
1.1056    raeburn  12879:             push(@hierarchy,$count);
                   12880:             $parent->{$depth} = $count;
1.1055    raeburn  12881:             $datatable .=
                   12882:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12883:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12884:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12885:             $depth --;
1.1056    raeburn  12886:             pop(@hierarchy);
1.1055    raeburn  12887:         }
                   12888:     }
                   12889:     return ($count,$datatable);
                   12890: }
                   12891: 
                   12892: sub recurse_extracted_archive {
1.1056    raeburn  12893:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12894:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12895:     my $result='';
1.1056    raeburn  12896:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12897:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12898:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12899:         return $result;
                   12900:     }
                   12901:     my $dirptr = 16384;
                   12902:     my ($newdirlistref,$newlisterror) =
                   12903:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12904:     if (ref($newdirlistref) eq 'ARRAY') {
                   12905:         foreach my $dir_line (@{$newdirlistref}) {
                   12906:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12907:             unless ($item =~ /^\.+$/) {
                   12908:                 $$count ++;
1.1056    raeburn  12909:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12910:                 $titles->{$$count} = $item;
1.1055    raeburn  12911:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12912: 
1.1055    raeburn  12913:                 my $is_dir;
                   12914:                 if ($dirptr&$testdir) {
                   12915:                     $is_dir = 1;
                   12916:                 }
                   12917:                 if ($wantform) {
                   12918:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12919:                 }
                   12920:                 if ($is_dir) {
                   12921:                     $$depth ++;
1.1056    raeburn  12922:                     push(@{$hierarchy},$$count);
                   12923:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12924:                     $result .=
                   12925:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12926:                                                    $docuname,$depth,$count,
1.1056    raeburn  12927:                                                    $hierarchy,$dirorder,$children,
                   12928:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12929:                     $$depth --;
1.1056    raeburn  12930:                     pop(@{$hierarchy});
1.1055    raeburn  12931:                 }
                   12932:             }
                   12933:         }
                   12934:     }
                   12935:     return $result;
                   12936: }
                   12937: 
                   12938: sub archive_hierarchy {
                   12939:     my ($depth,$count,$parent,$children) =@_;
                   12940:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12941:         if (exists($parent->{$depth})) {
                   12942:              $children->{$parent->{$depth}} .= $count.':';
                   12943:         }
                   12944:     }
                   12945:     return;
                   12946: }
                   12947: 
                   12948: sub archive_row {
                   12949:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12950:     my ($name) = ($item =~ m{([^/]+)$});
                   12951:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12952:                                        'display'    => 'Add as file',
1.1055    raeburn  12953:                                        'dependency' => 'Include as dependency',
                   12954:                                        'discard'    => 'Discard',
                   12955:                                       );
                   12956:     if ($is_dir) {
1.1059    raeburn  12957:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12958:     }
1.1056    raeburn  12959:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12960:     my $offset = 0;
1.1055    raeburn  12961:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12962:         $offset ++;
1.1065    raeburn  12963:         if ($action ne 'display') {
                   12964:             $offset ++;
                   12965:         }  
1.1055    raeburn  12966:         $output .= '<td><span class="LC_nobreak">'.
                   12967:                    '<label><input type="radio" name="archive_'.$count.
                   12968:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12969:         my $text = $choices{$action};
                   12970:         if ($is_dir) {
                   12971:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12972:             if ($action eq 'display') {
1.1059    raeburn  12973:                 $text = &mt('Add as folder');
1.1055    raeburn  12974:             }
1.1056    raeburn  12975:         } else {
                   12976:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12977: 
                   12978:         }
                   12979:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12980:         if ($action eq 'dependency') {
                   12981:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12982:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12983:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12984:                        '<option value=""></option>'."\n".
                   12985:                        '</select>'."\n".
                   12986:                        '</div>';
1.1059    raeburn  12987:         } elsif ($action eq 'display') {
                   12988:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12989:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12990:                        '</div>';
1.1055    raeburn  12991:         }
1.1056    raeburn  12992:         $output .= '</td>';
1.1055    raeburn  12993:     }
                   12994:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12995:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12996:     for (my $i=0; $i<$depth; $i++) {
                   12997:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12998:     }
                   12999:     if ($is_dir) {
                   13000:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13001:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13002:     } else {
                   13003:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13004:     }
                   13005:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13006:                &end_data_table_row();
                   13007:     return $output;
                   13008: }
                   13009: 
                   13010: sub archive_options_form {
1.1065    raeburn  13011:     my ($form,$display,$count,$hiddenelem) = @_;
                   13012:     my %lt = &Apache::lonlocal::texthash(
                   13013:                perm => 'Permanently remove archive file?',
                   13014:                hows => 'How should each extracted item be incorporated in the course?',
                   13015:                cont => 'Content actions for all',
                   13016:                addf => 'Add as folder/file',
                   13017:                incd => 'Include as dependency for a displayed file',
                   13018:                disc => 'Discard',
                   13019:                no   => 'No',
                   13020:                yes  => 'Yes',
                   13021:                save => 'Save',
                   13022:     );
                   13023:     my $output = <<"END";
                   13024: <form name="$form" method="post" action="">
                   13025: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13026: <label>
                   13027:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13028: </label>
                   13029: &nbsp;
                   13030: <label>
                   13031:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13032: </span>
                   13033: </p>
                   13034: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13035: <br />$lt{'hows'}
                   13036: <div class="LC_columnSection">
                   13037:   <fieldset>
                   13038:     <legend>$lt{'cont'}</legend>
                   13039:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13040:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13041:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13042:   </fieldset>
                   13043: </div>
                   13044: END
                   13045:     return $output.
1.1055    raeburn  13046:            &start_data_table()."\n".
1.1065    raeburn  13047:            $display."\n".
1.1055    raeburn  13048:            &end_data_table()."\n".
                   13049:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13050:            $hiddenelem.
1.1065    raeburn  13051:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13052:            '</form>';
                   13053: }
                   13054: 
                   13055: sub archive_javascript {
1.1056    raeburn  13056:     my ($startcount,$numitems,$titles,$children) = @_;
                   13057:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13058:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13059:     my $scripttag = <<START;
                   13060: <script type="text/javascript">
                   13061: // <![CDATA[
                   13062: 
                   13063: function checkAll(form,prefix) {
                   13064:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13065:     for (var i=0; i < form.elements.length; i++) {
                   13066:         var id = form.elements[i].id;
                   13067:         if ((id != '') && (id != undefined)) {
                   13068:             if (idstr.test(id)) {
                   13069:                 if (form.elements[i].type == 'radio') {
                   13070:                     form.elements[i].checked = true;
1.1056    raeburn  13071:                     var nostart = i-$startcount;
1.1059    raeburn  13072:                     var offset = nostart%7;
                   13073:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13074:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13075:                 }
                   13076:             }
                   13077:         }
                   13078:     }
                   13079: }
                   13080: 
                   13081: function propagateCheck(form,count) {
                   13082:     if (count > 0) {
1.1059    raeburn  13083:         var startelement = $startcount + ((count-1) * 7);
                   13084:         for (var j=1; j<6; j++) {
                   13085:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13086:                 var item = startelement + j; 
                   13087:                 if (form.elements[item].type == 'radio') {
                   13088:                     if (form.elements[item].checked) {
                   13089:                         containerCheck(form,count,j);
                   13090:                         break;
                   13091:                     }
1.1055    raeburn  13092:                 }
                   13093:             }
                   13094:         }
                   13095:     }
                   13096: }
                   13097: 
                   13098: numitems = $numitems
1.1056    raeburn  13099: var titles = new Array(numitems);
                   13100: var parents = new Array(numitems);
1.1055    raeburn  13101: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13102:     parents[i] = new Array;
1.1055    raeburn  13103: }
1.1059    raeburn  13104: var maintitle = '$maintitle';
1.1055    raeburn  13105: 
                   13106: START
                   13107: 
1.1056    raeburn  13108:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13109:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13110:         for (my $i=0; $i<@contents; $i ++) {
                   13111:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13112:         }
                   13113:     }
                   13114: 
1.1056    raeburn  13115:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13116:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13117:     }
                   13118: 
1.1055    raeburn  13119:     $scripttag .= <<END;
                   13120: 
                   13121: function containerCheck(form,count,offset) {
                   13122:     if (count > 0) {
1.1056    raeburn  13123:         dependencyCheck(form,count,offset);
1.1059    raeburn  13124:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13125:         form.elements[item].checked = true;
                   13126:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13127:             if (parents[count].length > 0) {
                   13128:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13129:                     containerCheck(form,parents[count][j],offset);
                   13130:                 }
                   13131:             }
                   13132:         }
                   13133:     }
                   13134: }
                   13135: 
                   13136: function dependencyCheck(form,count,offset) {
                   13137:     if (count > 0) {
1.1059    raeburn  13138:         var chosen = (offset+$startcount)+7*(count-1);
                   13139:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13140:         var currtype = form.elements[depitem].type;
                   13141:         if (form.elements[chosen].value == 'dependency') {
                   13142:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13143:             form.elements[depitem].options.length = 0;
                   13144:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13145:             for (var i=1; i<=numitems; i++) {
                   13146:                 if (i == count) {
                   13147:                     continue;
                   13148:                 }
1.1059    raeburn  13149:                 var startelement = $startcount + (i-1) * 7;
                   13150:                 for (var j=1; j<6; j++) {
                   13151:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13152:                         var item = startelement + j;
                   13153:                         if (form.elements[item].type == 'radio') {
                   13154:                             if (form.elements[item].checked) {
                   13155:                                 if (form.elements[item].value == 'display') {
                   13156:                                     var n = form.elements[depitem].options.length;
                   13157:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13158:                                 }
                   13159:                             }
                   13160:                         }
                   13161:                     }
                   13162:                 }
                   13163:             }
                   13164:         } else {
                   13165:             document.getElementById('arc_depon_'+count).style.display='none';
                   13166:             form.elements[depitem].options.length = 0;
                   13167:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13168:         }
1.1059    raeburn  13169:         titleCheck(form,count,offset);
1.1056    raeburn  13170:     }
                   13171: }
                   13172: 
                   13173: function propagateSelect(form,count,offset) {
                   13174:     if (count > 0) {
1.1065    raeburn  13175:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13176:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13177:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13178:             if (parents[count].length > 0) {
                   13179:                 for (var j=0; j<parents[count].length; j++) {
                   13180:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13181:                 }
                   13182:             }
                   13183:         }
                   13184:     }
                   13185: }
1.1056    raeburn  13186: 
                   13187: function containerSelect(form,count,offset,picked) {
                   13188:     if (count > 0) {
1.1065    raeburn  13189:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13190:         if (form.elements[item].type == 'radio') {
                   13191:             if (form.elements[item].value == 'dependency') {
                   13192:                 if (form.elements[item+1].type == 'select-one') {
                   13193:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13194:                         if (form.elements[item+1].options[i].value == picked) {
                   13195:                             form.elements[item+1].selectedIndex = i;
                   13196:                             break;
                   13197:                         }
                   13198:                     }
                   13199:                 }
                   13200:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13201:                     if (parents[count].length > 0) {
                   13202:                         for (var j=0; j<parents[count].length; j++) {
                   13203:                             containerSelect(form,parents[count][j],offset,picked);
                   13204:                         }
                   13205:                     }
                   13206:                 }
                   13207:             }
                   13208:         }
                   13209:     }
                   13210: }
                   13211: 
1.1059    raeburn  13212: function titleCheck(form,count,offset) {
                   13213:     if (count > 0) {
                   13214:         var chosen = (offset+$startcount)+7*(count-1);
                   13215:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13216:         var currtype = form.elements[depitem].type;
                   13217:         if (form.elements[chosen].value == 'display') {
                   13218:             document.getElementById('arc_title_'+count).style.display='block';
                   13219:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13220:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13221:             }
                   13222:         } else {
                   13223:             document.getElementById('arc_title_'+count).style.display='none';
                   13224:             if (currtype == 'text') { 
                   13225:                 document.getElementById('archive_title_'+count).value='';
                   13226:             }
                   13227:         }
                   13228:     }
                   13229:     return;
                   13230: }
                   13231: 
1.1055    raeburn  13232: // ]]>
                   13233: </script>
                   13234: END
                   13235:     return $scripttag;
                   13236: }
                   13237: 
                   13238: sub process_extracted_files {
1.1067    raeburn  13239:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13240:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  13241:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13242:     my @ids=&Apache::lonnet::current_machine_ids();
                   13243:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13244:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13245:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13246:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13247:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13248:         $pathtocheck = "$dir_root/$destination";
                   13249:         $dir = $dir_root;
                   13250:         $ishome = 1;
                   13251:     } else {
                   13252:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13253:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  13254:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13255:     }
                   13256:     my $currdir = "$dir_root/$destination";
                   13257:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13258:     if ($env{'form.folderpath'}) {
                   13259:         my @items = split('&',$env{'form.folderpath'});
                   13260:         $folders{'0'} = $items[-2];
1.1099    raeburn  13261:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13262:             $containers{'0'}='page';
                   13263:         } else {  
                   13264:             $containers{'0'}='sequence';
                   13265:         }
1.1055    raeburn  13266:     }
                   13267:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13268:     if ($numitems) {
                   13269:         for (my $i=1; $i<=$numitems; $i++) {
                   13270:             my $path = $env{'form.archive_content_'.$i};
                   13271:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13272:                 my $item = $1;
                   13273:                 $toplevelitems{$item} = $i;
                   13274:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13275:                     $is_dir{$item} = 1;
                   13276:                 }
                   13277:             }
                   13278:         }
                   13279:     }
1.1067    raeburn  13280:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13281:     if (keys(%toplevelitems) > 0) {
                   13282:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13283:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13284:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13285:     }
1.1066    raeburn  13286:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13287:     if ($numitems) {
                   13288:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13289:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13290:             my $path = $env{'form.archive_content_'.$i};
                   13291:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13292:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13293:                     if ($prefix ne '' && $path ne '') {
                   13294:                         if (-e $prefix.$path) {
1.1066    raeburn  13295:                             if ((@archdirs > 0) && 
                   13296:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13297:                                 $todeletedir{$prefix.$path} = 1;
                   13298:                             } else {
                   13299:                                 $todelete{$prefix.$path} = 1;
                   13300:                             }
1.1055    raeburn  13301:                         }
                   13302:                     }
                   13303:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13304:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13305:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13306:                     $docstitle = $env{'form.archive_title_'.$i};
                   13307:                     if ($docstitle eq '') {
                   13308:                         $docstitle = $title;
                   13309:                     }
1.1055    raeburn  13310:                     $outer = 0;
1.1056    raeburn  13311:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13312:                         if (@{$dirorder{$i}} > 0) {
                   13313:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13314:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13315:                                     $outer = $item;
                   13316:                                     last;
                   13317:                                 }
                   13318:                             }
                   13319:                         }
                   13320:                     }
                   13321:                     my ($errtext,$fatal) = 
                   13322:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13323:                                                '/'.$folders{$outer}.'.'.
                   13324:                                                $containers{$outer});
                   13325:                     next if ($fatal);
                   13326:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13327:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13328:                             $mapinner{$i} = time;
1.1055    raeburn  13329:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13330:                             $containers{$i} = 'sequence';
                   13331:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13332:                                       $folders{$i}.'.'.$containers{$i};
                   13333:                             my $newidx = &LONCAPA::map::getresidx();
                   13334:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13335:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13336:                             push(@LONCAPA::map::order,$newidx);
                   13337:                             my ($outtext,$errtext) =
                   13338:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13339:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13340:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13341:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13342:                             unless ($errtext) {
1.1294    raeburn  13343:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13344:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   13345:                                             '</li>'."\n";
1.1067    raeburn  13346:                             }
1.1055    raeburn  13347:                         }
                   13348:                     } else {
                   13349:                         if ($context eq 'coursedocs') {
                   13350:                             my $newidx=&LONCAPA::map::getresidx();
                   13351:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13352:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13353:                                       $title;
1.1294    raeburn  13354:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13355:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13356:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13357:                                 }
                   13358:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13359:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13360:                                 }
                   13361:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13362:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13363:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13364:                                         unless ($ishome) {
                   13365:                                             my $fetch = "$newdest{$i}/$title";
                   13366:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13367:                                             $prompttofetch{$fetch} = 1;
                   13368:                                         }
1.1292    raeburn  13369:                                     }
1.1067    raeburn  13370:                                 }
1.1294    raeburn  13371:                                 $LONCAPA::map::resources[$newidx]=
                   13372:                                     $docstitle.':'.$url.':false:normal:res';
                   13373:                                 push(@LONCAPA::map::order, $newidx);
                   13374:                                 my ($outtext,$errtext)=
                   13375:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13376:                                                             $docuname.'/'.$folders{$outer}.
                   13377:                                                             '.'.$containers{$outer},1,1);
                   13378:                                 unless ($errtext) {
                   13379:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13380:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13381:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13382:                                                    '</li>'."\n";
                   13383:                                     }
1.1067    raeburn  13384:                                 }
1.1294    raeburn  13385:                             } else {
                   13386:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13387:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  13388:                             }
1.1055    raeburn  13389:                         }
                   13390:                     }
1.1086    raeburn  13391:                 }
                   13392:             } else {
1.1294    raeburn  13393:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13394:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  13395:             }
                   13396:         }
                   13397:         for (my $i=1; $i<=$numitems; $i++) {
                   13398:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13399:             my $path = $env{'form.archive_content_'.$i};
                   13400:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13401:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13402:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13403:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13404:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13405:                         my ($itemidx,$fullpath,$relpath);
                   13406:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13407:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13408:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13409:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13410:                                     $itemidx = $j;
1.1056    raeburn  13411:                                 }
                   13412:                             }
1.1086    raeburn  13413:                         }
                   13414:                         if ($itemidx eq '') {
                   13415:                             $itemidx =  0;
                   13416:                         } 
                   13417:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13418:                             if ($mapinner{$referrer{$i}}) {
                   13419:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13420:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13421:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13422:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13423:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13424:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13425:                                             if (!-e $fullpath) {
                   13426:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13427:                                             }
                   13428:                                         }
1.1086    raeburn  13429:                                     } else {
                   13430:                                         last;
1.1056    raeburn  13431:                                     }
1.1086    raeburn  13432:                                 }
                   13433:                             }
                   13434:                         } elsif ($newdest{$referrer{$i}}) {
                   13435:                             $fullpath = $newdest{$referrer{$i}};
                   13436:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13437:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13438:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13439:                                     last;
                   13440:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13441:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13442:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13443:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13444:                                         if (!-e $fullpath) {
                   13445:                                             mkdir($fullpath,0755);
1.1056    raeburn  13446:                                         }
                   13447:                                     }
1.1086    raeburn  13448:                                 } else {
                   13449:                                     last;
1.1056    raeburn  13450:                                 }
1.1055    raeburn  13451:                             }
                   13452:                         }
1.1086    raeburn  13453:                         if ($fullpath ne '') {
                   13454:                             if (-e "$prefix$path") {
1.1292    raeburn  13455:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13456:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13457:                                 }
1.1086    raeburn  13458:                             }
                   13459:                             if (-e "$fullpath/$title") {
                   13460:                                 my $showpath;
                   13461:                                 if ($relpath ne '') {
                   13462:                                     $showpath = "$relpath/$title";
                   13463:                                 } else {
                   13464:                                     $showpath = "/$title";
                   13465:                                 } 
1.1294    raeburn  13466:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13467:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13468:                                            '</li>'."\n";
1.1292    raeburn  13469:                                 unless ($ishome) {
                   13470:                                     my $fetch = "$fullpath/$title";
                   13471:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   13472:                                     $prompttofetch{$fetch} = 1;
                   13473:                                 }
1.1086    raeburn  13474:                             }
                   13475:                         }
1.1055    raeburn  13476:                     }
1.1086    raeburn  13477:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13478:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  13479:                                     &HTML::Entities::encode($path,'<>&"'),
                   13480:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13481:                                 '<br />';
1.1055    raeburn  13482:                 }
                   13483:             } else {
1.1294    raeburn  13484:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  13485:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13486:             }
                   13487:         }
                   13488:         if (keys(%todelete)) {
                   13489:             foreach my $key (keys(%todelete)) {
                   13490:                 unlink($key);
1.1066    raeburn  13491:             }
                   13492:         }
                   13493:         if (keys(%todeletedir)) {
                   13494:             foreach my $key (keys(%todeletedir)) {
                   13495:                 rmdir($key);
                   13496:             }
                   13497:         }
                   13498:         foreach my $dir (sort(keys(%is_dir))) {
                   13499:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13500:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13501:             }
                   13502:         }
1.1067    raeburn  13503:         if ($result ne '') {
                   13504:             $output .= '<ul>'."\n".
                   13505:                        $result."\n".
                   13506:                        '</ul>';
                   13507:         }
                   13508:         unless ($ishome) {
                   13509:             my $replicationfail;
                   13510:             foreach my $item (keys(%prompttofetch)) {
                   13511:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13512:                 unless ($fetchresult eq 'ok') {
                   13513:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13514:                 }
                   13515:             }
                   13516:             if ($replicationfail) {
                   13517:                 $output .= '<p class="LC_error">'.
                   13518:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13519:                            $replicationfail.
                   13520:                            '</ul></p>';
                   13521:             }
                   13522:         }
1.1055    raeburn  13523:     } else {
                   13524:         $warning = &mt('No items found in archive.');
                   13525:     }
                   13526:     if ($error) {
                   13527:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13528:                    $error.'</p>'."\n";
                   13529:     }
                   13530:     if ($warning) {
                   13531:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13532:     }
                   13533:     return $output;
                   13534: }
                   13535: 
1.1066    raeburn  13536: sub cleanup_empty_dirs {
                   13537:     my ($path) = @_;
                   13538:     if (($path ne '') && (-d $path)) {
                   13539:         if (opendir(my $dirh,$path)) {
                   13540:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13541:             my $numitems = 0;
                   13542:             foreach my $item (@dircontents) {
                   13543:                 if (-d "$path/$item") {
1.1111    raeburn  13544:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13545:                     if (-e "$path/$item") {
                   13546:                         $numitems ++;
                   13547:                     }
                   13548:                 } else {
                   13549:                     $numitems ++;
                   13550:                 }
                   13551:             }
                   13552:             if ($numitems == 0) {
                   13553:                 rmdir($path);
                   13554:             }
                   13555:             closedir($dirh);
                   13556:         }
                   13557:     }
                   13558:     return;
                   13559: }
                   13560: 
1.41      ng       13561: =pod
1.45      matthew  13562: 
1.1162    raeburn  13563: =item * &get_folder_hierarchy()
1.1068    raeburn  13564: 
                   13565: Provides hierarchy of names of folders/sub-folders containing the current
                   13566: item,
                   13567: 
                   13568: Inputs: 3
                   13569:      - $navmap - navmaps object
                   13570: 
                   13571:      - $map - url for map (either the trigger itself, or map containing
                   13572:                            the resource, which is the trigger).
                   13573: 
                   13574:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13575: 
                   13576: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13577: 
                   13578: =cut
                   13579: 
                   13580: sub get_folder_hierarchy {
                   13581:     my ($navmap,$map,$showitem) = @_;
                   13582:     my @pathitems;
                   13583:     if (ref($navmap)) {
                   13584:         my $mapres = $navmap->getResourceByUrl($map);
                   13585:         if (ref($mapres)) {
                   13586:             my $pcslist = $mapres->map_hierarchy();
                   13587:             if ($pcslist ne '') {
                   13588:                 my @pcs = split(/,/,$pcslist);
                   13589:                 foreach my $pc (@pcs) {
                   13590:                     if ($pc == 1) {
1.1129    raeburn  13591:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13592:                     } else {
                   13593:                         my $res = $navmap->getByMapPc($pc);
                   13594:                         if (ref($res)) {
                   13595:                             my $title = $res->compTitle();
                   13596:                             $title =~ s/\W+/_/g;
                   13597:                             if ($title ne '') {
                   13598:                                 push(@pathitems,$title);
                   13599:                             }
                   13600:                         }
                   13601:                     }
                   13602:                 }
                   13603:             }
1.1071    raeburn  13604:             if ($showitem) {
                   13605:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  13606:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13607:                 } else {
                   13608:                     my $maptitle = $mapres->compTitle();
                   13609:                     $maptitle =~ s/\W+/_/g;
                   13610:                     if ($maptitle ne '') {
                   13611:                         push(@pathitems,$maptitle);
                   13612:                     }
1.1068    raeburn  13613:                 }
                   13614:             }
                   13615:         }
                   13616:     }
                   13617:     return @pathitems;
                   13618: }
                   13619: 
                   13620: =pod
                   13621: 
1.1015    raeburn  13622: =item * &get_turnedin_filepath()
                   13623: 
                   13624: Determines path in a user's portfolio file for storage of files uploaded
                   13625: to a specific essayresponse or dropbox item.
                   13626: 
                   13627: Inputs: 3 required + 1 optional.
                   13628: $symb is symb for resource, $uname and $udom are for current user (required).
                   13629: $caller is optional (can be "submission", if routine is called when storing
                   13630: an upoaded file when "Submit Answer" button was pressed).
                   13631: 
                   13632: Returns array containing $path and $multiresp. 
                   13633: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13634: than one file upload item.  Callers of routine should append partid as a 
                   13635: subdirectory to $path in cases where $multiresp is 1.
                   13636: 
                   13637: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13638: 
                   13639: =cut
                   13640: 
                   13641: sub get_turnedin_filepath {
                   13642:     my ($symb,$uname,$udom,$caller) = @_;
                   13643:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13644:     my $turnindir;
                   13645:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13646:     $turnindir = $userhash{'turnindir'};
                   13647:     my ($path,$multiresp);
                   13648:     if ($turnindir eq '') {
                   13649:         if ($caller eq 'submission') {
                   13650:             $turnindir = &mt('turned in');
                   13651:             $turnindir =~ s/\W+/_/g;
                   13652:             my %newhash = (
                   13653:                             'turnindir' => $turnindir,
                   13654:                           );
                   13655:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13656:         }
                   13657:     }
                   13658:     if ($turnindir ne '') {
                   13659:         $path = '/'.$turnindir.'/';
                   13660:         my ($multipart,$turnin,@pathitems);
                   13661:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13662:         if (defined($navmap)) {
                   13663:             my $mapres = $navmap->getResourceByUrl($map);
                   13664:             if (ref($mapres)) {
                   13665:                 my $pcslist = $mapres->map_hierarchy();
                   13666:                 if ($pcslist ne '') {
                   13667:                     foreach my $pc (split(/,/,$pcslist)) {
                   13668:                         my $res = $navmap->getByMapPc($pc);
                   13669:                         if (ref($res)) {
                   13670:                             my $title = $res->compTitle();
                   13671:                             $title =~ s/\W+/_/g;
                   13672:                             if ($title ne '') {
1.1149    raeburn  13673:                                 if (($pc > 1) && (length($title) > 12)) {
                   13674:                                     $title = substr($title,0,12);
                   13675:                                 }
1.1015    raeburn  13676:                                 push(@pathitems,$title);
                   13677:                             }
                   13678:                         }
                   13679:                     }
                   13680:                 }
                   13681:                 my $maptitle = $mapres->compTitle();
                   13682:                 $maptitle =~ s/\W+/_/g;
                   13683:                 if ($maptitle ne '') {
1.1149    raeburn  13684:                     if (length($maptitle) > 12) {
                   13685:                         $maptitle = substr($maptitle,0,12);
                   13686:                     }
1.1015    raeburn  13687:                     push(@pathitems,$maptitle);
                   13688:                 }
                   13689:                 unless ($env{'request.state'} eq 'construct') {
                   13690:                     my $res = $navmap->getBySymb($symb);
                   13691:                     if (ref($res)) {
                   13692:                         my $partlist = $res->parts();
                   13693:                         my $totaluploads = 0;
                   13694:                         if (ref($partlist) eq 'ARRAY') {
                   13695:                             foreach my $part (@{$partlist}) {
                   13696:                                 my @types = $res->responseType($part);
                   13697:                                 my @ids = $res->responseIds($part);
                   13698:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13699:                                     if ($types[$i] eq 'essay') {
                   13700:                                         my $partid = $part.'_'.$ids[$i];
                   13701:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13702:                                             $totaluploads ++;
                   13703:                                         }
                   13704:                                     }
                   13705:                                 }
                   13706:                             }
                   13707:                             if ($totaluploads > 1) {
                   13708:                                 $multiresp = 1;
                   13709:                             }
                   13710:                         }
                   13711:                     }
                   13712:                 }
                   13713:             } else {
                   13714:                 return;
                   13715:             }
                   13716:         } else {
                   13717:             return;
                   13718:         }
                   13719:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13720:         $restitle =~ s/\W+/_/g;
                   13721:         if ($restitle eq '') {
                   13722:             $restitle = ($resurl =~ m{/[^/]+$});
                   13723:             if ($restitle eq '') {
                   13724:                 $restitle = time;
                   13725:             }
                   13726:         }
1.1149    raeburn  13727:         if (length($restitle) > 12) {
                   13728:             $restitle = substr($restitle,0,12);
                   13729:         }
1.1015    raeburn  13730:         push(@pathitems,$restitle);
                   13731:         $path .= join('/',@pathitems);
                   13732:     }
                   13733:     return ($path,$multiresp);
                   13734: }
                   13735: 
                   13736: =pod
                   13737: 
1.464     albertel 13738: =back
1.41      ng       13739: 
1.112     bowersj2 13740: =head1 CSV Upload/Handling functions
1.38      albertel 13741: 
1.41      ng       13742: =over 4
                   13743: 
1.648     raeburn  13744: =item * &upfile_store($r)
1.41      ng       13745: 
                   13746: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13747: needs $env{'form.upfile'}
1.41      ng       13748: returns $datatoken to be put into hidden field
                   13749: 
                   13750: =cut
1.31      albertel 13751: 
                   13752: sub upfile_store {
                   13753:     my $r=shift;
1.258     albertel 13754:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13755:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13756:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13757:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13758: 
1.1299    raeburn  13759:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13760:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13761:                                      time.'_'.$$);
                   13762:     return if ($datatoken eq '');
                   13763: 
1.31      albertel 13764:     {
1.158     raeburn  13765:         my $datafile = $r->dir_config('lonDaemons').
                   13766:                            '/tmp/'.$datatoken.'.tmp';
                   13767:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13768:             print $fh $env{'form.upfile'};
1.158     raeburn  13769:             close($fh);
                   13770:         }
1.31      albertel 13771:     }
                   13772:     return $datatoken;
                   13773: }
                   13774: 
1.56      matthew  13775: =pod
                   13776: 
1.1290    raeburn  13777: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13778: 
                   13779: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  13780: $datatoken is the name to assign to the temporary file.
1.258     albertel 13781: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13782: 
                   13783: =cut
1.31      albertel 13784: 
                   13785: sub load_tmp_file {
1.1290    raeburn  13786:     my ($r,$datatoken) = @_;
                   13787:     return if ($datatoken eq '');
1.31      albertel 13788:     my @studentdata=();
                   13789:     {
1.158     raeburn  13790:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  13791:                               '/tmp/'.$datatoken.'.tmp';
1.158     raeburn  13792:         if ( open(my $fh,"<$studentfile") ) {
                   13793:             @studentdata=<$fh>;
                   13794:             close($fh);
                   13795:         }
1.31      albertel 13796:     }
1.258     albertel 13797:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13798: }
                   13799: 
1.1290    raeburn  13800: sub valid_datatoken {
                   13801:     my ($datatoken) = @_;
1.1291    raeburn  13802:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_$match_domain\_$match_courseid\_\d+_\d+$/) {
1.1290    raeburn  13803:         return $datatoken;
                   13804:     }
                   13805:     return;
                   13806: }
                   13807: 
1.56      matthew  13808: =pod
                   13809: 
1.648     raeburn  13810: =item * &upfile_record_sep()
1.41      ng       13811: 
                   13812: Separate uploaded file into records
                   13813: returns array of records,
1.258     albertel 13814: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13815: 
                   13816: =cut
1.31      albertel 13817: 
                   13818: sub upfile_record_sep {
1.258     albertel 13819:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13820:     } else {
1.248     albertel 13821: 	my @records;
1.258     albertel 13822: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13823: 	    if ($line=~/^\s*$/) { next; }
                   13824: 	    push(@records,$line);
                   13825: 	}
                   13826: 	return @records;
1.31      albertel 13827:     }
                   13828: }
                   13829: 
1.56      matthew  13830: =pod
                   13831: 
1.648     raeburn  13832: =item * &record_sep($record)
1.41      ng       13833: 
1.258     albertel 13834: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13835: 
                   13836: =cut
                   13837: 
1.263     www      13838: sub takeleft {
                   13839:     my $index=shift;
                   13840:     return substr('0000'.$index,-4,4);
                   13841: }
                   13842: 
1.31      albertel 13843: sub record_sep {
                   13844:     my $record=shift;
                   13845:     my %components=();
1.258     albertel 13846:     if ($env{'form.upfiletype'} eq 'xml') {
                   13847:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13848:         my $i=0;
1.356     albertel 13849:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13850:             $field=~s/^(\"|\')//;
                   13851:             $field=~s/(\"|\')$//;
1.263     www      13852:             $components{&takeleft($i)}=$field;
1.31      albertel 13853:             $i++;
                   13854:         }
1.258     albertel 13855:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13856:         my $i=0;
1.356     albertel 13857:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13858:             $field=~s/^(\"|\')//;
                   13859:             $field=~s/(\"|\')$//;
1.263     www      13860:             $components{&takeleft($i)}=$field;
1.31      albertel 13861:             $i++;
                   13862:         }
                   13863:     } else {
1.561     www      13864:         my $separator=',';
1.480     banghart 13865:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13866:             $separator=';';
1.480     banghart 13867:         }
1.31      albertel 13868:         my $i=0;
1.561     www      13869: # the character we are looking for to indicate the end of a quote or a record 
                   13870:         my $looking_for=$separator;
                   13871: # do not add the characters to the fields
                   13872:         my $ignore=0;
                   13873: # we just encountered a separator (or the beginning of the record)
                   13874:         my $just_found_separator=1;
                   13875: # store the field we are working on here
                   13876:         my $field='';
                   13877: # work our way through all characters in record
                   13878:         foreach my $character ($record=~/(.)/g) {
                   13879:             if ($character eq $looking_for) {
                   13880:                if ($character ne $separator) {
                   13881: # Found the end of a quote, again looking for separator
                   13882:                   $looking_for=$separator;
                   13883:                   $ignore=1;
                   13884:                } else {
                   13885: # Found a separator, store away what we got
                   13886:                   $components{&takeleft($i)}=$field;
                   13887: 	          $i++;
                   13888:                   $just_found_separator=1;
                   13889:                   $ignore=0;
                   13890:                   $field='';
                   13891:                }
                   13892:                next;
                   13893:             }
                   13894: # single or double quotation marks after a separator indicate beginning of a quote
                   13895: # we are now looking for the end of the quote and need to ignore separators
                   13896:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13897:                $looking_for=$character;
                   13898:                next;
                   13899:             }
                   13900: # ignore would be true after we reached the end of a quote
                   13901:             if ($ignore) { next; }
                   13902:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13903:             $field.=$character;
                   13904:             $just_found_separator=0; 
1.31      albertel 13905:         }
1.561     www      13906: # catch the very last entry, since we never encountered the separator
                   13907:         $components{&takeleft($i)}=$field;
1.31      albertel 13908:     }
                   13909:     return %components;
                   13910: }
                   13911: 
1.144     matthew  13912: ######################################################
                   13913: ######################################################
                   13914: 
1.56      matthew  13915: =pod
                   13916: 
1.648     raeburn  13917: =item * &upfile_select_html()
1.41      ng       13918: 
1.144     matthew  13919: Return HTML code to select a file from the users machine and specify 
                   13920: the file type.
1.41      ng       13921: 
                   13922: =cut
                   13923: 
1.144     matthew  13924: ######################################################
                   13925: ######################################################
1.31      albertel 13926: sub upfile_select_html {
1.144     matthew  13927:     my %Types = (
                   13928:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13929:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13930:                  space => &mt('Space separated'),
                   13931:                  tab   => &mt('Tabulator separated'),
                   13932: #                 xml   => &mt('HTML/XML'),
                   13933:                  );
                   13934:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13935:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13936:     foreach my $type (sort(keys(%Types))) {
                   13937:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13938:     }
                   13939:     $Str .= "</select>\n";
                   13940:     return $Str;
1.31      albertel 13941: }
                   13942: 
1.301     albertel 13943: sub get_samples {
                   13944:     my ($records,$toget) = @_;
                   13945:     my @samples=({});
                   13946:     my $got=0;
                   13947:     foreach my $rec (@$records) {
                   13948: 	my %temp = &record_sep($rec);
                   13949: 	if (! grep(/\S/, values(%temp))) { next; }
                   13950: 	if (%temp) {
                   13951: 	    $samples[$got]=\%temp;
                   13952: 	    $got++;
                   13953: 	    if ($got == $toget) { last; }
                   13954: 	}
                   13955:     }
                   13956:     return \@samples;
                   13957: }
                   13958: 
1.144     matthew  13959: ######################################################
                   13960: ######################################################
                   13961: 
1.56      matthew  13962: =pod
                   13963: 
1.648     raeburn  13964: =item * &csv_print_samples($r,$records)
1.41      ng       13965: 
                   13966: Prints a table of sample values from each column uploaded $r is an
                   13967: Apache Request ref, $records is an arrayref from
                   13968: &Apache::loncommon::upfile_record_sep
                   13969: 
                   13970: =cut
                   13971: 
1.144     matthew  13972: ######################################################
                   13973: ######################################################
1.31      albertel 13974: sub csv_print_samples {
                   13975:     my ($r,$records) = @_;
1.662     bisitz   13976:     my $samples = &get_samples($records,5);
1.301     albertel 13977: 
1.594     raeburn  13978:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13979:               &start_data_table_header_row());
1.356     albertel 13980:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13981:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13982:     $r->print(&end_data_table_header_row());
1.301     albertel 13983:     foreach my $hash (@$samples) {
1.594     raeburn  13984: 	$r->print(&start_data_table_row());
1.356     albertel 13985: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13986: 	    $r->print('<td>');
1.356     albertel 13987: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13988: 	    $r->print('</td>');
                   13989: 	}
1.594     raeburn  13990: 	$r->print(&end_data_table_row());
1.31      albertel 13991:     }
1.594     raeburn  13992:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13993: }
                   13994: 
1.144     matthew  13995: ######################################################
                   13996: ######################################################
                   13997: 
1.56      matthew  13998: =pod
                   13999: 
1.648     raeburn  14000: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14001: 
                   14002: Prints a table to create associations between values and table columns.
1.144     matthew  14003: 
1.41      ng       14004: $r is an Apache Request ref,
                   14005: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14006: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14007: 
                   14008: =cut
                   14009: 
1.144     matthew  14010: ######################################################
                   14011: ######################################################
1.31      albertel 14012: sub csv_print_select_table {
                   14013:     my ($r,$records,$d) = @_;
1.301     albertel 14014:     my $i=0;
                   14015:     my $samples = &get_samples($records,1);
1.144     matthew  14016:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14017: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14018:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14019:               '<th>'.&mt('Column').'</th>'.
                   14020:               &end_data_table_header_row()."\n");
1.356     albertel 14021:     foreach my $array_ref (@$d) {
                   14022: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14023: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14024: 
1.875     bisitz   14025: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14026: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14027: 	$r->print('<option value="none"></option>');
1.356     albertel 14028: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14029: 	    $r->print('<option value="'.$sample.'"'.
                   14030:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14031:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14032: 	}
1.594     raeburn  14033: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14034: 	$i++;
                   14035:     }
1.594     raeburn  14036:     $r->print(&end_data_table());
1.31      albertel 14037:     $i--;
                   14038:     return $i;
                   14039: }
1.56      matthew  14040: 
1.144     matthew  14041: ######################################################
                   14042: ######################################################
                   14043: 
1.56      matthew  14044: =pod
1.31      albertel 14045: 
1.648     raeburn  14046: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14047: 
                   14048: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14049: 
                   14050: $r is an Apache Request ref,
                   14051: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14052: $d is an array of 2 element arrays (internal name, displayed name)
                   14053: 
                   14054: =cut
                   14055: 
1.144     matthew  14056: ######################################################
                   14057: ######################################################
1.31      albertel 14058: sub csv_samples_select_table {
                   14059:     my ($r,$records,$d) = @_;
                   14060:     my $i=0;
1.144     matthew  14061:     #
1.662     bisitz   14062:     my $max_samples = 5;
                   14063:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14064:     $r->print(&start_data_table().
                   14065:               &start_data_table_header_row().'<th>'.
                   14066:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14067:               &end_data_table_header_row());
1.301     albertel 14068: 
                   14069:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14070: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14071: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14072: 	foreach my $option (@$d) {
                   14073: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14074: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14075:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14076:                       $display.'</option>');
1.31      albertel 14077: 	}
                   14078: 	$r->print('</select></td><td>');
1.662     bisitz   14079: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14080: 	    if (defined($samples->[$line]{$key})) { 
                   14081: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14082: 	    }
                   14083: 	}
1.594     raeburn  14084: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14085: 	$i++;
                   14086:     }
1.594     raeburn  14087:     $r->print(&end_data_table());
1.31      albertel 14088:     $i--;
                   14089:     return($i);
1.115     matthew  14090: }
                   14091: 
1.144     matthew  14092: ######################################################
                   14093: ######################################################
                   14094: 
1.115     matthew  14095: =pod
                   14096: 
1.648     raeburn  14097: =item * &clean_excel_name($name)
1.115     matthew  14098: 
                   14099: Returns a replacement for $name which does not contain any illegal characters.
                   14100: 
                   14101: =cut
                   14102: 
1.144     matthew  14103: ######################################################
                   14104: ######################################################
1.115     matthew  14105: sub clean_excel_name {
                   14106:     my ($name) = @_;
                   14107:     $name =~ s/[:\*\?\/\\]//g;
                   14108:     if (length($name) > 31) {
                   14109:         $name = substr($name,0,31);
                   14110:     }
                   14111:     return $name;
1.25      albertel 14112: }
1.84      albertel 14113: 
1.85      albertel 14114: =pod
                   14115: 
1.648     raeburn  14116: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14117: 
                   14118: Returns either 1 or undef
                   14119: 
                   14120: 1 if the part is to be hidden, undef if it is to be shown
                   14121: 
                   14122: Arguments are:
                   14123: 
                   14124: $id the id of the part to be checked
                   14125: $symb, optional the symb of the resource to check
                   14126: $udom, optional the domain of the user to check for
                   14127: $uname, optional the username of the user to check for
                   14128: 
                   14129: =cut
1.84      albertel 14130: 
                   14131: sub check_if_partid_hidden {
                   14132:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14133:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14134: 					 $symb,$udom,$uname);
1.141     albertel 14135:     my $truth=1;
                   14136:     #if the string starts with !, then the list is the list to show not hide
                   14137:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14138:     my @hiddenlist=split(/,/,$hiddenparts);
                   14139:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14140: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14141:     }
1.141     albertel 14142:     return !$truth;
1.84      albertel 14143: }
1.127     matthew  14144: 
1.138     matthew  14145: 
                   14146: ############################################################
                   14147: ############################################################
                   14148: 
                   14149: =pod
                   14150: 
1.157     matthew  14151: =back 
                   14152: 
1.138     matthew  14153: =head1 cgi-bin script and graphing routines
                   14154: 
1.157     matthew  14155: =over 4
                   14156: 
1.648     raeburn  14157: =item * &get_cgi_id()
1.138     matthew  14158: 
                   14159: Inputs: none
                   14160: 
                   14161: Returns an id which can be used to pass environment variables
                   14162: to various cgi-bin scripts.  These environment variables will
                   14163: be removed from the users environment after a given time by
                   14164: the routine &Apache::lonnet::transfer_profile_to_env.
                   14165: 
                   14166: =cut
                   14167: 
                   14168: ############################################################
                   14169: ############################################################
1.152     albertel 14170: my $uniq=0;
1.136     matthew  14171: sub get_cgi_id {
1.154     albertel 14172:     $uniq=($uniq+1)%100000;
1.280     albertel 14173:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14174: }
                   14175: 
1.127     matthew  14176: ############################################################
                   14177: ############################################################
                   14178: 
                   14179: =pod
                   14180: 
1.648     raeburn  14181: =item * &DrawBarGraph()
1.127     matthew  14182: 
1.138     matthew  14183: Facilitates the plotting of data in a (stacked) bar graph.
                   14184: Puts plot definition data into the users environment in order for 
                   14185: graph.png to plot it.  Returns an <img> tag for the plot.
                   14186: The bars on the plot are labeled '1','2',...,'n'.
                   14187: 
                   14188: Inputs:
                   14189: 
                   14190: =over 4
                   14191: 
                   14192: =item $Title: string, the title of the plot
                   14193: 
                   14194: =item $xlabel: string, text describing the X-axis of the plot
                   14195: 
                   14196: =item $ylabel: string, text describing the Y-axis of the plot
                   14197: 
                   14198: =item $Max: scalar, the maximum Y value to use in the plot
                   14199: If $Max is < any data point, the graph will not be rendered.
                   14200: 
1.140     matthew  14201: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14202: they are plotted.  If undefined, default values will be used.
                   14203: 
1.178     matthew  14204: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14205: 
1.138     matthew  14206: =item @Values: An array of array references.  Each array reference holds data
                   14207: to be plotted in a stacked bar chart.
                   14208: 
1.239     matthew  14209: =item If the final element of @Values is a hash reference the key/value
                   14210: pairs will be added to the graph definition.
                   14211: 
1.138     matthew  14212: =back
                   14213: 
                   14214: Returns:
                   14215: 
                   14216: An <img> tag which references graph.png and the appropriate identifying
                   14217: information for the plot.
                   14218: 
1.127     matthew  14219: =cut
                   14220: 
                   14221: ############################################################
                   14222: ############################################################
1.134     matthew  14223: sub DrawBarGraph {
1.178     matthew  14224:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14225:     #
                   14226:     if (! defined($colors)) {
                   14227:         $colors = ['#33ff00', 
                   14228:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14229:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14230:                   ]; 
                   14231:     }
1.228     matthew  14232:     my $extra_settings = {};
                   14233:     if (ref($Values[-1]) eq 'HASH') {
                   14234:         $extra_settings = pop(@Values);
                   14235:     }
1.127     matthew  14236:     #
1.136     matthew  14237:     my $identifier = &get_cgi_id();
                   14238:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14239:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14240:         return '';
                   14241:     }
1.225     matthew  14242:     #
                   14243:     my @Labels;
                   14244:     if (defined($labels)) {
                   14245:         @Labels = @$labels;
                   14246:     } else {
                   14247:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14248:             push(@Labels,$i+1);
1.225     matthew  14249:         }
                   14250:     }
                   14251:     #
1.129     matthew  14252:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14253:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14254:     my %ValuesHash;
                   14255:     my $NumSets=1;
                   14256:     foreach my $array (@Values) {
                   14257:         next if (! ref($array));
1.136     matthew  14258:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14259:             join(',',@$array);
1.129     matthew  14260:     }
1.127     matthew  14261:     #
1.136     matthew  14262:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14263:     if ($NumBars < 3) {
                   14264:         $width = 120+$NumBars*32;
1.220     matthew  14265:         $xskip = 1;
1.225     matthew  14266:         $bar_width = 30;
                   14267:     } elsif ($NumBars < 5) {
                   14268:         $width = 120+$NumBars*20;
                   14269:         $xskip = 1;
                   14270:         $bar_width = 20;
1.220     matthew  14271:     } elsif ($NumBars < 10) {
1.136     matthew  14272:         $width = 120+$NumBars*15;
                   14273:         $xskip = 1;
                   14274:         $bar_width = 15;
                   14275:     } elsif ($NumBars <= 25) {
                   14276:         $width = 120+$NumBars*11;
                   14277:         $xskip = 5;
                   14278:         $bar_width = 8;
                   14279:     } elsif ($NumBars <= 50) {
                   14280:         $width = 120+$NumBars*8;
                   14281:         $xskip = 5;
                   14282:         $bar_width = 4;
                   14283:     } else {
                   14284:         $width = 120+$NumBars*8;
                   14285:         $xskip = 5;
                   14286:         $bar_width = 4;
                   14287:     }
                   14288:     #
1.137     matthew  14289:     $Max = 1 if ($Max < 1);
                   14290:     if ( int($Max) < $Max ) {
                   14291:         $Max++;
                   14292:         $Max = int($Max);
                   14293:     }
1.127     matthew  14294:     $Title  = '' if (! defined($Title));
                   14295:     $xlabel = '' if (! defined($xlabel));
                   14296:     $ylabel = '' if (! defined($ylabel));
1.369     www      14297:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14298:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14299:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14300:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14301:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14302:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14303:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14304:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14305:     $ValuesHash{$id.'.height'}   = $height;
                   14306:     $ValuesHash{$id.'.width'}    = $width;
                   14307:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14308:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14309:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14310:     #
1.228     matthew  14311:     # Deal with other parameters
                   14312:     while (my ($key,$value) = each(%$extra_settings)) {
                   14313:         $ValuesHash{$id.'.'.$key} = $value;
                   14314:     }
                   14315:     #
1.646     raeburn  14316:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14317:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14318: }
                   14319: 
                   14320: ############################################################
                   14321: ############################################################
                   14322: 
                   14323: =pod
                   14324: 
1.648     raeburn  14325: =item * &DrawXYGraph()
1.137     matthew  14326: 
1.138     matthew  14327: Facilitates the plotting of data in an XY graph.
                   14328: Puts plot definition data into the users environment in order for 
                   14329: graph.png to plot it.  Returns an <img> tag for the plot.
                   14330: 
                   14331: Inputs:
                   14332: 
                   14333: =over 4
                   14334: 
                   14335: =item $Title: string, the title of the plot
                   14336: 
                   14337: =item $xlabel: string, text describing the X-axis of the plot
                   14338: 
                   14339: =item $ylabel: string, text describing the Y-axis of the plot
                   14340: 
                   14341: =item $Max: scalar, the maximum Y value to use in the plot
                   14342: If $Max is < any data point, the graph will not be rendered.
                   14343: 
                   14344: =item $colors: Array ref containing the hex color codes for the data to be 
                   14345: plotted in.  If undefined, default values will be used.
                   14346: 
                   14347: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14348: 
                   14349: =item $Ydata: Array ref containing Array refs.  
1.185     www      14350: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14351: 
                   14352: =item %Values: hash indicating or overriding any default values which are 
                   14353: passed to graph.png.  
                   14354: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14355: 
                   14356: =back
                   14357: 
                   14358: Returns:
                   14359: 
                   14360: An <img> tag which references graph.png and the appropriate identifying
                   14361: information for the plot.
                   14362: 
1.137     matthew  14363: =cut
                   14364: 
                   14365: ############################################################
                   14366: ############################################################
                   14367: sub DrawXYGraph {
                   14368:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14369:     #
                   14370:     # Create the identifier for the graph
                   14371:     my $identifier = &get_cgi_id();
                   14372:     my $id = 'cgi.'.$identifier;
                   14373:     #
                   14374:     $Title  = '' if (! defined($Title));
                   14375:     $xlabel = '' if (! defined($xlabel));
                   14376:     $ylabel = '' if (! defined($ylabel));
                   14377:     my %ValuesHash = 
                   14378:         (
1.369     www      14379:          $id.'.title'  => &escape($Title),
                   14380:          $id.'.xlabel' => &escape($xlabel),
                   14381:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14382:          $id.'.y_max_value'=> $Max,
                   14383:          $id.'.labels'     => join(',',@$Xlabels),
                   14384:          $id.'.PlotType'   => 'XY',
                   14385:          );
                   14386:     #
                   14387:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14388:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14389:     }
                   14390:     #
                   14391:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14392:         return '';
                   14393:     }
                   14394:     my $NumSets=1;
1.138     matthew  14395:     foreach my $array (@{$Ydata}){
1.137     matthew  14396:         next if (! ref($array));
                   14397:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14398:     }
1.138     matthew  14399:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14400:     #
                   14401:     # Deal with other parameters
                   14402:     while (my ($key,$value) = each(%Values)) {
                   14403:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14404:     }
                   14405:     #
1.646     raeburn  14406:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14407:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14408: }
                   14409: 
                   14410: ############################################################
                   14411: ############################################################
                   14412: 
                   14413: =pod
                   14414: 
1.648     raeburn  14415: =item * &DrawXYYGraph()
1.138     matthew  14416: 
                   14417: Facilitates the plotting of data in an XY graph with two Y axes.
                   14418: Puts plot definition data into the users environment in order for 
                   14419: graph.png to plot it.  Returns an <img> tag for the plot.
                   14420: 
                   14421: Inputs:
                   14422: 
                   14423: =over 4
                   14424: 
                   14425: =item $Title: string, the title of the plot
                   14426: 
                   14427: =item $xlabel: string, text describing the X-axis of the plot
                   14428: 
                   14429: =item $ylabel: string, text describing the Y-axis of the plot
                   14430: 
                   14431: =item $colors: Array ref containing the hex color codes for the data to be 
                   14432: plotted in.  If undefined, default values will be used.
                   14433: 
                   14434: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14435: 
                   14436: =item $Ydata1: The first data set
                   14437: 
                   14438: =item $Min1: The minimum value of the left Y-axis
                   14439: 
                   14440: =item $Max1: The maximum value of the left Y-axis
                   14441: 
                   14442: =item $Ydata2: The second data set
                   14443: 
                   14444: =item $Min2: The minimum value of the right Y-axis
                   14445: 
                   14446: =item $Max2: The maximum value of the left Y-axis
                   14447: 
                   14448: =item %Values: hash indicating or overriding any default values which are 
                   14449: passed to graph.png.  
                   14450: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14451: 
                   14452: =back
                   14453: 
                   14454: Returns:
                   14455: 
                   14456: An <img> tag which references graph.png and the appropriate identifying
                   14457: information for the plot.
1.136     matthew  14458: 
                   14459: =cut
                   14460: 
                   14461: ############################################################
                   14462: ############################################################
1.137     matthew  14463: sub DrawXYYGraph {
                   14464:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14465:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14466:     #
                   14467:     # Create the identifier for the graph
                   14468:     my $identifier = &get_cgi_id();
                   14469:     my $id = 'cgi.'.$identifier;
                   14470:     #
                   14471:     $Title  = '' if (! defined($Title));
                   14472:     $xlabel = '' if (! defined($xlabel));
                   14473:     $ylabel = '' if (! defined($ylabel));
                   14474:     my %ValuesHash = 
                   14475:         (
1.369     www      14476:          $id.'.title'  => &escape($Title),
                   14477:          $id.'.xlabel' => &escape($xlabel),
                   14478:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14479:          $id.'.labels' => join(',',@$Xlabels),
                   14480:          $id.'.PlotType' => 'XY',
                   14481:          $id.'.NumSets' => 2,
1.137     matthew  14482:          $id.'.two_axes' => 1,
                   14483:          $id.'.y1_max_value' => $Max1,
                   14484:          $id.'.y1_min_value' => $Min1,
                   14485:          $id.'.y2_max_value' => $Max2,
                   14486:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14487:          );
                   14488:     #
1.137     matthew  14489:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14490:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14491:     }
                   14492:     #
                   14493:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14494:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14495:         return '';
                   14496:     }
                   14497:     my $NumSets=1;
1.137     matthew  14498:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14499:         next if (! ref($array));
                   14500:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14501:     }
                   14502:     #
                   14503:     # Deal with other parameters
                   14504:     while (my ($key,$value) = each(%Values)) {
                   14505:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14506:     }
                   14507:     #
1.646     raeburn  14508:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14509:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14510: }
                   14511: 
                   14512: ############################################################
                   14513: ############################################################
                   14514: 
                   14515: =pod
                   14516: 
1.157     matthew  14517: =back 
                   14518: 
1.139     matthew  14519: =head1 Statistics helper routines?  
                   14520: 
                   14521: Bad place for them but what the hell.
                   14522: 
1.157     matthew  14523: =over 4
                   14524: 
1.648     raeburn  14525: =item * &chartlink()
1.139     matthew  14526: 
                   14527: Returns a link to the chart for a specific student.  
                   14528: 
                   14529: Inputs:
                   14530: 
                   14531: =over 4
                   14532: 
                   14533: =item $linktext: The text of the link
                   14534: 
                   14535: =item $sname: The students username
                   14536: 
                   14537: =item $sdomain: The students domain
                   14538: 
                   14539: =back
                   14540: 
1.157     matthew  14541: =back
                   14542: 
1.139     matthew  14543: =cut
                   14544: 
                   14545: ############################################################
                   14546: ############################################################
                   14547: sub chartlink {
                   14548:     my ($linktext, $sname, $sdomain) = @_;
                   14549:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14550:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14551:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14552:        '">'.$linktext.'</a>';
1.153     matthew  14553: }
                   14554: 
                   14555: #######################################################
                   14556: #######################################################
                   14557: 
                   14558: =pod
                   14559: 
                   14560: =head1 Course Environment Routines
1.157     matthew  14561: 
                   14562: =over 4
1.153     matthew  14563: 
1.648     raeburn  14564: =item * &restore_course_settings()
1.153     matthew  14565: 
1.648     raeburn  14566: =item * &store_course_settings()
1.153     matthew  14567: 
                   14568: Restores/Store indicated form parameters from the course environment.
                   14569: Will not overwrite existing values of the form parameters.
                   14570: 
                   14571: Inputs: 
                   14572: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14573: 
                   14574: a hash ref describing the data to be stored.  For example:
                   14575:    
                   14576: %Save_Parameters = ('Status' => 'scalar',
                   14577:     'chartoutputmode' => 'scalar',
                   14578:     'chartoutputdata' => 'scalar',
                   14579:     'Section' => 'array',
1.373     raeburn  14580:     'Group' => 'array',
1.153     matthew  14581:     'StudentData' => 'array',
                   14582:     'Maps' => 'array');
                   14583: 
                   14584: Returns: both routines return nothing
                   14585: 
1.631     raeburn  14586: =back
                   14587: 
1.153     matthew  14588: =cut
                   14589: 
                   14590: #######################################################
                   14591: #######################################################
                   14592: sub store_course_settings {
1.496     albertel 14593:     return &store_settings($env{'request.course.id'},@_);
                   14594: }
                   14595: 
                   14596: sub store_settings {
1.153     matthew  14597:     # save to the environment
                   14598:     # appenv the same items, just to be safe
1.300     albertel 14599:     my $udom  = $env{'user.domain'};
                   14600:     my $uname = $env{'user.name'};
1.496     albertel 14601:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14602:     my %SaveHash;
                   14603:     my %AppHash;
                   14604:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14605:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14606:         my $envname = 'environment.'.$basename;
1.258     albertel 14607:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14608:             # Save this value away
                   14609:             if ($type eq 'scalar' &&
1.258     albertel 14610:                 (! exists($env{$envname}) || 
                   14611:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14612:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14613:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14614:             } elsif ($type eq 'array') {
                   14615:                 my $stored_form;
1.258     albertel 14616:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14617:                     $stored_form = join(',',
                   14618:                                         map {
1.369     www      14619:                                             &escape($_);
1.258     albertel 14620:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14621:                 } else {
                   14622:                     $stored_form = 
1.369     www      14623:                         &escape($env{'form.'.$setting});
1.153     matthew  14624:                 }
                   14625:                 # Determine if the array contents are the same.
1.258     albertel 14626:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14627:                     $SaveHash{$basename} = $stored_form;
                   14628:                     $AppHash{$envname}   = $stored_form;
                   14629:                 }
                   14630:             }
                   14631:         }
                   14632:     }
                   14633:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14634:                                           $udom,$uname);
1.153     matthew  14635:     if ($put_result !~ /^(ok|delayed)/) {
                   14636:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14637:                                  'got error:'.$put_result);
                   14638:     }
                   14639:     # Make sure these settings stick around in this session, too
1.646     raeburn  14640:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14641:     return;
                   14642: }
                   14643: 
                   14644: sub restore_course_settings {
1.499     albertel 14645:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14646: }
                   14647: 
                   14648: sub restore_settings {
                   14649:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14650:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14651:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14652:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14653:             '.'.$setting;
1.258     albertel 14654:         if (exists($env{$envname})) {
1.153     matthew  14655:             if ($type eq 'scalar') {
1.258     albertel 14656:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14657:             } elsif ($type eq 'array') {
1.258     albertel 14658:                 $env{'form.'.$setting} = [ 
1.153     matthew  14659:                                            map { 
1.369     www      14660:                                                &unescape($_); 
1.258     albertel 14661:                                            } split(',',$env{$envname})
1.153     matthew  14662:                                            ];
                   14663:             }
                   14664:         }
                   14665:     }
1.127     matthew  14666: }
                   14667: 
1.618     raeburn  14668: #######################################################
                   14669: #######################################################
                   14670: 
                   14671: =pod
                   14672: 
                   14673: =head1 Domain E-mail Routines  
                   14674: 
                   14675: =over 4
                   14676: 
1.648     raeburn  14677: =item * &build_recipient_list()
1.618     raeburn  14678: 
1.1144    raeburn  14679: Build recipient lists for following types of e-mail:
1.766     raeburn  14680: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14681: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14682: module change checking, student/employee ID conflict checks, as
                   14683: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14684: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14685: 
                   14686: Inputs:
1.619     raeburn  14687: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14688: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14689: requestsmail, updatesmail, or idconflictsmail).
                   14690: 
1.619     raeburn  14691: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14692: 
1.619     raeburn  14693: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  14694: i.e., predates configuration by DC via domainprefs.pm
                   14695: 
                   14696: $requname username of requester (if mailing type is helpdeskmail)
                   14697: 
                   14698: $requdom domain of requester (if mailing type is helpdeskmail)
                   14699: 
                   14700: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14701: 
1.618     raeburn  14702: 
1.655     raeburn  14703: Returns: comma separated list of addresses to which to send e-mail.
                   14704: 
                   14705: =back
1.618     raeburn  14706: 
                   14707: =cut
                   14708: 
                   14709: ############################################################
                   14710: ############################################################
                   14711: sub build_recipient_list {
1.1297    raeburn  14712:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14713:     my @recipients;
1.1270    raeburn  14714:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14715:     my %domconfig =
1.1270    raeburn  14716:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14717:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14718:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14719:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14720:                 my @contacts = ('adminemail','supportemail');
                   14721:                 foreach my $item (@contacts) {
                   14722:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14723:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14724:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14725:                             push(@recipients,$addr);
                   14726:                         }
1.619     raeburn  14727:                     }
1.1270    raeburn  14728:                 }
                   14729:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14730:                 if ($mailing eq 'helpdeskmail') {
                   14731:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14732:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14733:                         my @ok_bccs;
                   14734:                         foreach my $bcc (@bccs) {
                   14735:                             $bcc =~ s/^\s+//g;
                   14736:                             $bcc =~ s/\s+$//g;
                   14737:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14738:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14739:                                     push(@ok_bccs,$bcc);
                   14740:                                 }
                   14741:                             }
                   14742:                         }
                   14743:                         if (@ok_bccs > 0) {
                   14744:                             $allbcc = join(', ',@ok_bccs);
                   14745:                         }
                   14746:                     }
                   14747:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14748:                 }
                   14749:             }
1.766     raeburn  14750:         } elsif ($origmail ne '') {
1.1270    raeburn  14751:             $lastresort = $origmail;
1.618     raeburn  14752:         }
1.1297    raeburn  14753:         if ($mailing eq 'helpdeskmail') {
                   14754:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14755:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14756:                 my ($inststatus,$inststatus_checked);
                   14757:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14758:                     ($env{'user.domain'} ne 'public')) {
                   14759:                     $inststatus_checked = 1;
                   14760:                     $inststatus = $env{'environment.inststatus'};
                   14761:                 }
                   14762:                 unless ($inststatus_checked) {
                   14763:                     if (($requname ne '') && ($requdom ne '')) {
                   14764:                         if (($requname =~ /^$match_username$/) &&
                   14765:                             ($requdom =~ /^$match_domain$/) &&
                   14766:                             (&Apache::lonnet::domain($requdom))) {
                   14767:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14768:                                                                       $requdom);
                   14769:                             unless ($requhome eq 'no_host') {
                   14770:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14771:                                 $inststatus = $userenv{'inststatus'};
                   14772:                                 $inststatus_checked = 1;
                   14773:                             }
                   14774:                         }
                   14775:                     }
                   14776:                 }
                   14777:                 unless ($inststatus_checked) {
                   14778:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14779:                         my %srch = (srchby     => 'email',
                   14780:                                     srchdomain => $defdom,
                   14781:                                     srchterm   => $reqemail,
                   14782:                                     srchtype   => 'exact');
                   14783:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   14784:                         foreach my $uname (keys(%srch_results)) {
                   14785:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14786:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14787:                                 $inststatus_checked = 1;
                   14788:                                 last;
                   14789:                             }
                   14790:                         }
                   14791:                         unless ($inststatus_checked) {
                   14792:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   14793:                             if ($dirsrchres eq 'ok') {
                   14794:                                 foreach my $uname (keys(%srch_results)) {
                   14795:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14796:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14797:                                         $inststatus_checked = 1;
                   14798:                                         last;
                   14799:                                     }
                   14800:                                 }
                   14801:                             }
                   14802:                         }
                   14803:                     }
                   14804:                 }
                   14805:                 if ($inststatus ne '') {
                   14806:                     foreach my $status (split(/\:/,$inststatus)) {
                   14807:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   14808:                             my @contacts = ('adminemail','supportemail');
                   14809:                             foreach my $item (@contacts) {
                   14810:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   14811:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   14812:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14813:                                         push(@recipients,$addr);
                   14814:                                     }
                   14815:                                 }
                   14816:                             }
                   14817:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   14818:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   14819:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   14820:                                 my @ok_bccs;
                   14821:                                 foreach my $bcc (@bccs) {
                   14822:                                     $bcc =~ s/^\s+//g;
                   14823:                                     $bcc =~ s/\s+$//g;
                   14824:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14825:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14826:                                             push(@ok_bccs,$bcc);
                   14827:                                         }
                   14828:                                     }
                   14829:                                 }
                   14830:                                 if (@ok_bccs > 0) {
                   14831:                                     $allbcc = join(', ',@ok_bccs);
                   14832:                                 }
                   14833:                             }
                   14834:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   14835:                             last;
                   14836:                         }
                   14837:                     }
                   14838:                 }
                   14839:             }
                   14840:         }
1.619     raeburn  14841:     } elsif ($origmail ne '') {
1.1270    raeburn  14842:         $lastresort = $origmail;
                   14843:     }
1.1297    raeburn  14844:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  14845:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14846:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14847:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14848:             my %what = (
                   14849:                           perlvar => 1,
                   14850:                        );
                   14851:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14852:             if ($primary) {
                   14853:                 my $gotaddr;
                   14854:                 my ($result,$returnhash) =
                   14855:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14856:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14857:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14858:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14859:                         $gotaddr = 1;
                   14860:                     }
                   14861:                 }
                   14862:                 unless ($gotaddr) {
                   14863:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14864:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14865:                     unless ($uintdom eq $intdom) {
                   14866:                         my %domconfig =
                   14867:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14868:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14869:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14870:                                 my @contacts = ('adminemail','supportemail');
                   14871:                                 foreach my $item (@contacts) {
                   14872:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14873:                                         my $addr = $domconfig{'contacts'}{$item};
                   14874:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14875:                                             push(@recipients,$addr);
                   14876:                                         }
                   14877:                                     }
                   14878:                                 }
                   14879:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14880:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14881:                                 }
                   14882:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14883:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14884:                                     my @ok_bccs;
                   14885:                                     foreach my $bcc (@bccs) {
                   14886:                                         $bcc =~ s/^\s+//g;
                   14887:                                         $bcc =~ s/\s+$//g;
                   14888:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14889:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14890:                                                 push(@ok_bccs,$bcc);
                   14891:                                             }
                   14892:                                         }
                   14893:                                     }
                   14894:                                     if (@ok_bccs > 0) {
                   14895:                                         $allbcc = join(', ',@ok_bccs);
                   14896:                                     }
                   14897:                                 }
                   14898:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14899:                             }
                   14900:                         }
                   14901:                     }
                   14902:                 }
                   14903:             }
                   14904:         }
1.618     raeburn  14905:     }
1.688     raeburn  14906:     if (defined($defmail)) {
                   14907:         if ($defmail ne '') {
                   14908:             push(@recipients,$defmail);
                   14909:         }
1.618     raeburn  14910:     }
                   14911:     if ($otheremails) {
1.619     raeburn  14912:         my @others;
                   14913:         if ($otheremails =~ /,/) {
                   14914:             @others = split(/,/,$otheremails);
1.618     raeburn  14915:         } else {
1.619     raeburn  14916:             push(@others,$otheremails);
                   14917:         }
                   14918:         foreach my $addr (@others) {
                   14919:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14920:                 push(@recipients,$addr);
                   14921:             }
1.618     raeburn  14922:         }
                   14923:     }
1.1298    raeburn  14924:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  14925:         if ((!@recipients) && ($lastresort ne '')) {
                   14926:             push(@recipients,$lastresort);
                   14927:         }
                   14928:     } elsif ($lastresort ne '') {
                   14929:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14930:             push(@recipients,$lastresort);
                   14931:         }
                   14932:     }
1.1271    raeburn  14933:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  14934:     if (wantarray) {
                   14935:         return ($recipientlist,$allbcc,$addtext);
                   14936:     } else {
                   14937:         return $recipientlist;
                   14938:     }
1.618     raeburn  14939: }
                   14940: 
1.127     matthew  14941: ############################################################
                   14942: ############################################################
1.154     albertel 14943: 
1.655     raeburn  14944: =pod
                   14945: 
1.1224    musolffc 14946: =over 4
                   14947: 
1.1223    musolffc 14948: =item * &mime_email()
                   14949: 
                   14950: Sends an email with a possible attachment
                   14951: 
                   14952: Inputs:
                   14953: 
                   14954: =over 4
                   14955: 
                   14956: from -              Sender's email address
                   14957: 
                   14958: to -                Email address of recipient
                   14959: 
                   14960: subject -           Subject of email
                   14961: 
                   14962: body -              Body of email
                   14963: 
                   14964: cc_string -         Carbon copy email address
                   14965: 
                   14966: bcc -               Blind carbon copy email address
                   14967: 
                   14968: type -              File type of attachment
                   14969: 
                   14970: attachment_path -   Path of file to be attached
                   14971: 
                   14972: file_name -         Name of file to be attached
                   14973: 
                   14974: attachment_text -   The body of an attachment of type "TEXT"
                   14975: 
                   14976: =back
                   14977: 
                   14978: =back
                   14979: 
                   14980: =cut
                   14981: 
                   14982: ############################################################
                   14983: ############################################################
                   14984: 
                   14985: sub mime_email {
                   14986:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   14987:         $file_name, $attachment_text) = @_;
                   14988:     my $msg = MIME::Lite->new(
                   14989:              From    => $from,
                   14990:              To      => $to,
                   14991:              Subject => $subject,
                   14992:              Type    =>'TEXT',
                   14993:              Data    => $body,
                   14994:              );
                   14995:     if ($cc_string ne '') {
                   14996:         $msg->add("Cc" => $cc_string);
                   14997:     }
                   14998:     if ($bcc ne '') {
                   14999:         $msg->add("Bcc" => $bcc);
                   15000:     }
                   15001:     $msg->attr("content-type"         => "text/plain");
                   15002:     $msg->attr("content-type.charset" => "UTF-8");
                   15003:     # Attach file if given
                   15004:     if ($attachment_path) {
                   15005:         unless ($file_name) {
                   15006:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15007:         }
                   15008:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15009:         $msg->attach(Type     => $type,
                   15010:                      Path     => $attachment_path,
                   15011:                      Filename => $file_name
                   15012:                      );
                   15013:     # Otherwise attach text if given
                   15014:     } elsif ($attachment_text) {
                   15015:         $msg->attach(Type => 'TEXT',
                   15016:                      Data => $attachment_text);
                   15017:     }
                   15018:     # Send it
                   15019:     $msg->send('sendmail');
                   15020: }
                   15021: 
                   15022: ############################################################
                   15023: ############################################################
                   15024: 
                   15025: =pod
                   15026: 
1.655     raeburn  15027: =head1 Course Catalog Routines
                   15028: 
                   15029: =over 4
                   15030: 
                   15031: =item * &gather_categories()
                   15032: 
                   15033: Converts category definitions - keys of categories hash stored in  
                   15034: coursecategories in configuration.db on the primary library server in a 
                   15035: domain - to an array.  Also generates javascript and idx hash used to 
                   15036: generate Domain Coordinator interface for editing Course Categories.
                   15037: 
                   15038: Inputs:
1.663     raeburn  15039: 
1.655     raeburn  15040: categories (reference to hash of category definitions).
1.663     raeburn  15041: 
1.655     raeburn  15042: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15043:       categories and subcategories).
1.663     raeburn  15044: 
1.655     raeburn  15045: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15046:       editing Course Categories).
1.663     raeburn  15047: 
1.655     raeburn  15048: jsarray (reference to array of categories used to create Javascript arrays for
                   15049:          Domain Coordinator interface for editing Course Categories).
                   15050: 
                   15051: Returns: nothing
                   15052: 
                   15053: Side effects: populates cats, idx and jsarray. 
                   15054: 
                   15055: =cut
                   15056: 
                   15057: sub gather_categories {
                   15058:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15059:     my %counters;
                   15060:     my $num = 0;
                   15061:     foreach my $item (keys(%{$categories})) {
                   15062:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15063:         if ($container eq '' && $depth == 0) {
                   15064:             $cats->[$depth][$categories->{$item}] = $cat;
                   15065:         } else {
                   15066:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15067:         }
                   15068:         my ($escitem,$tail) = split(/:/,$item,2);
                   15069:         if ($counters{$tail} eq '') {
                   15070:             $counters{$tail} = $num;
                   15071:             $num ++;
                   15072:         }
                   15073:         if (ref($idx) eq 'HASH') {
                   15074:             $idx->{$item} = $counters{$tail};
                   15075:         }
                   15076:         if (ref($jsarray) eq 'ARRAY') {
                   15077:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15078:         }
                   15079:     }
                   15080:     return;
                   15081: }
                   15082: 
                   15083: =pod
                   15084: 
                   15085: =item * &extract_categories()
                   15086: 
                   15087: Used to generate breadcrumb trails for course categories.
                   15088: 
                   15089: Inputs:
1.663     raeburn  15090: 
1.655     raeburn  15091: categories (reference to hash of category definitions).
1.663     raeburn  15092: 
1.655     raeburn  15093: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15094:       categories and subcategories).
1.663     raeburn  15095: 
1.655     raeburn  15096: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15097: 
1.655     raeburn  15098: allitems (reference to hash - key is category key 
                   15099:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15100: 
1.655     raeburn  15101: idx (reference to hash of counters used in Domain Coordinator interface for
                   15102:       editing Course Categories).
1.663     raeburn  15103: 
1.655     raeburn  15104: jsarray (reference to array of categories used to create Javascript arrays for
                   15105:          Domain Coordinator interface for editing Course Categories).
                   15106: 
1.665     raeburn  15107: subcats (reference to hash of arrays containing all subcategories within each 
                   15108:          category, -recursive)
                   15109: 
1.655     raeburn  15110: Returns: nothing
                   15111: 
                   15112: Side effects: populates trails and allitems hash references.
                   15113: 
                   15114: =cut
                   15115: 
                   15116: sub extract_categories {
1.665     raeburn  15117:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  15118:     if (ref($categories) eq 'HASH') {
                   15119:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15120:         if (ref($cats->[0]) eq 'ARRAY') {
                   15121:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15122:                 my $name = $cats->[0][$i];
                   15123:                 my $item = &escape($name).'::0';
                   15124:                 my $trailstr;
                   15125:                 if ($name eq 'instcode') {
                   15126:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15127:                 } elsif ($name eq 'communities') {
                   15128:                     $trailstr = &mt('Communities');
1.1239    raeburn  15129:                 } elsif ($name eq 'placement') {
                   15130:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15131:                 } else {
                   15132:                     $trailstr = $name;
                   15133:                 }
                   15134:                 if ($allitems->{$item} eq '') {
                   15135:                     push(@{$trails},$trailstr);
                   15136:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15137:                 }
                   15138:                 my @parents = ($name);
                   15139:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15140:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15141:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15142:                         if (ref($subcats) eq 'HASH') {
                   15143:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15144:                         }
                   15145:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   15146:                     }
                   15147:                 } else {
                   15148:                     if (ref($subcats) eq 'HASH') {
                   15149:                         $subcats->{$item} = [];
1.655     raeburn  15150:                     }
                   15151:                 }
                   15152:             }
                   15153:         }
                   15154:     }
                   15155:     return;
                   15156: }
                   15157: 
                   15158: =pod
                   15159: 
1.1162    raeburn  15160: =item * &recurse_categories()
1.655     raeburn  15161: 
                   15162: Recursively used to generate breadcrumb trails for course categories.
                   15163: 
                   15164: Inputs:
1.663     raeburn  15165: 
1.655     raeburn  15166: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15167:       categories and subcategories).
1.663     raeburn  15168: 
1.655     raeburn  15169: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15170: 
                   15171: category (current course category, for which breadcrumb trail is being generated).
                   15172: 
                   15173: trails (reference to array of breadcrumb trails for each category).
                   15174: 
1.655     raeburn  15175: allitems (reference to hash - key is category key
                   15176:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15177: 
1.655     raeburn  15178: parents (array containing containers directories for current category, 
                   15179:          back to top level). 
                   15180: 
                   15181: Returns: nothing
                   15182: 
                   15183: Side effects: populates trails and allitems hash references
                   15184: 
                   15185: =cut
                   15186: 
                   15187: sub recurse_categories {
1.665     raeburn  15188:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  15189:     my $shallower = $depth - 1;
                   15190:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15191:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15192:             my $name = $cats->[$depth]{$category}[$k];
                   15193:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   15194:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   15195:             if ($allitems->{$item} eq '') {
                   15196:                 push(@{$trails},$trailstr);
                   15197:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15198:             }
                   15199:             my $deeper = $depth+1;
                   15200:             push(@{$parents},$category);
1.665     raeburn  15201:             if (ref($subcats) eq 'HASH') {
                   15202:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15203:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15204:                     my $higher;
                   15205:                     if ($j > 0) {
                   15206:                         $higher = &escape($parents->[$j]).':'.
                   15207:                                   &escape($parents->[$j-1]).':'.$j;
                   15208:                     } else {
                   15209:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15210:                     }
                   15211:                     push(@{$subcats->{$higher}},$subcat);
                   15212:                 }
                   15213:             }
                   15214:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   15215:                                 $subcats);
1.655     raeburn  15216:             pop(@{$parents});
                   15217:         }
                   15218:     } else {
                   15219:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   15220:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   15221:         if ($allitems->{$item} eq '') {
                   15222:             push(@{$trails},$trailstr);
                   15223:             $allitems->{$item} = scalar(@{$trails})-1;
                   15224:         }
                   15225:     }
                   15226:     return;
                   15227: }
                   15228: 
1.663     raeburn  15229: =pod
                   15230: 
1.1162    raeburn  15231: =item * &assign_categories_table()
1.663     raeburn  15232: 
                   15233: Create a datatable for display of hierarchical categories in a domain,
                   15234: with checkboxes to allow a course to be categorized. 
                   15235: 
                   15236: Inputs:
                   15237: 
                   15238: cathash - reference to hash of categories defined for the domain (from
                   15239:           configuration.db)
                   15240: 
                   15241: currcat - scalar with an & separated list of categories assigned to a course. 
                   15242: 
1.919     raeburn  15243: type    - scalar contains course type (Course or Community).
                   15244: 
1.1260    raeburn  15245: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15246:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15247: 
1.663     raeburn  15248: Returns: $output (markup to be displayed) 
                   15249: 
                   15250: =cut
                   15251: 
                   15252: sub assign_categories_table {
1.1259    raeburn  15253:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15254:     my $output;
                   15255:     if (ref($cathash) eq 'HASH') {
                   15256:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   15257:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   15258:         $maxdepth = scalar(@cats);
                   15259:         if (@cats > 0) {
                   15260:             my $itemcount = 0;
                   15261:             if (ref($cats[0]) eq 'ARRAY') {
                   15262:                 my @currcategories;
                   15263:                 if ($currcat ne '') {
                   15264:                     @currcategories = split('&',$currcat);
                   15265:                 }
1.919     raeburn  15266:                 my $table;
1.663     raeburn  15267:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15268:                     my $parent = $cats[0][$i];
1.919     raeburn  15269:                     next if ($parent eq 'instcode');
                   15270:                     if ($type eq 'Community') {
                   15271:                         next unless ($parent eq 'communities');
1.1239    raeburn  15272:                     } elsif ($type eq 'Placement') {
                   15273:                         next unless ($parent eq 'placement');
1.919     raeburn  15274:                     } else {
1.1239    raeburn  15275:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  15276:                     }
1.663     raeburn  15277:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15278:                     my $item = &escape($parent).'::0';
                   15279:                     my $checked = '';
                   15280:                     if (@currcategories > 0) {
                   15281:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15282:                             $checked = ' checked="checked"';
1.663     raeburn  15283:                         }
                   15284:                     }
1.919     raeburn  15285:                     my $parent_title = $parent;
                   15286:                     if ($parent eq 'communities') {
                   15287:                         $parent_title = &mt('Communities');
1.1239    raeburn  15288:                     } elsif ($parent eq 'placement') {
                   15289:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  15290:                     }
                   15291:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15292:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15293:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15294:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15295:                     my $depth = 1;
                   15296:                     push(@path,$parent);
1.1259    raeburn  15297:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15298:                     pop(@path);
1.919     raeburn  15299:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15300:                     $itemcount ++;
                   15301:                 }
1.919     raeburn  15302:                 if ($itemcount) {
                   15303:                     $output = &Apache::loncommon::start_data_table().
                   15304:                               $table.
                   15305:                               &Apache::loncommon::end_data_table();
                   15306:                 }
1.663     raeburn  15307:             }
                   15308:         }
                   15309:     }
                   15310:     return $output;
                   15311: }
                   15312: 
                   15313: =pod
                   15314: 
1.1162    raeburn  15315: =item * &assign_category_rows()
1.663     raeburn  15316: 
                   15317: Create a datatable row for display of nested categories in a domain,
                   15318: with checkboxes to allow a course to be categorized,called recursively.
                   15319: 
                   15320: Inputs:
                   15321: 
                   15322: itemcount - track row number for alternating colors
                   15323: 
                   15324: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15325:       categories and subcategories.
                   15326: 
                   15327: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15328: 
                   15329: parent - parent of current category item
                   15330: 
                   15331: path - Array containing all categories back up through the hierarchy from the
                   15332:        current category to the top level.
                   15333: 
                   15334: currcategories - reference to array of current categories assigned to the course
                   15335: 
1.1260    raeburn  15336: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15337:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15338: 
1.663     raeburn  15339: Returns: $output (markup to be displayed).
                   15340: 
                   15341: =cut
                   15342: 
                   15343: sub assign_category_rows {
1.1259    raeburn  15344:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15345:     my ($text,$name,$item,$chgstr);
                   15346:     if (ref($cats) eq 'ARRAY') {
                   15347:         my $maxdepth = scalar(@{$cats});
                   15348:         if (ref($cats->[$depth]) eq 'HASH') {
                   15349:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15350:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15351:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  15352:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15353:                 for (my $j=0; $j<$numchildren; $j++) {
                   15354:                     $name = $cats->[$depth]{$parent}[$j];
                   15355:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15356:                     my $deeper = $depth+1;
                   15357:                     my $checked = '';
                   15358:                     if (ref($currcategories) eq 'ARRAY') {
                   15359:                         if (@{$currcategories} > 0) {
                   15360:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15361:                                 $checked = ' checked="checked"';
1.663     raeburn  15362:                             }
                   15363:                         }
                   15364:                     }
1.664     raeburn  15365:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15366:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15367:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15368:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15369:                              '</td><td>';
1.663     raeburn  15370:                     if (ref($path) eq 'ARRAY') {
                   15371:                         push(@{$path},$name);
1.1259    raeburn  15372:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15373:                         pop(@{$path});
                   15374:                     }
                   15375:                     $text .= '</td></tr>';
                   15376:                 }
                   15377:                 $text .= '</table></td>';
                   15378:             }
                   15379:         }
                   15380:     }
                   15381:     return $text;
                   15382: }
                   15383: 
1.1181    raeburn  15384: =pod
                   15385: 
                   15386: =back
                   15387: 
                   15388: =cut
                   15389: 
1.655     raeburn  15390: ############################################################
                   15391: ############################################################
                   15392: 
                   15393: 
1.443     albertel 15394: sub commit_customrole {
1.664     raeburn  15395:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15396:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15397:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15398:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15399:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15400:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15401:                  '</b><br />';
                   15402:     return $output;
                   15403: }
                   15404: 
                   15405: sub commit_standardrole {
1.1116    raeburn  15406:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15407:     my ($output,$logmsg,$linefeed);
                   15408:     if ($context eq 'auto') {
                   15409:         $linefeed = "\n";
                   15410:     } else {
                   15411:         $linefeed = "<br />\n";
                   15412:     }  
1.443     albertel 15413:     if ($three eq 'st') {
1.541     raeburn  15414:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15415:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15416:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15417:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15418:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15419:         } else {
1.541     raeburn  15420:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15421:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15422:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15423:             if ($context eq 'auto') {
                   15424:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15425:             } else {
                   15426:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15427:                &mt('Add to classlist').': <b>ok</b>';
                   15428:             }
                   15429:             $output .= $linefeed;
1.443     albertel 15430:         }
                   15431:     } else {
                   15432:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15433:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15434:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15435:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15436:         if ($context eq 'auto') {
                   15437:             $output .= $result.$linefeed;
                   15438:         } else {
                   15439:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15440:         }
1.443     albertel 15441:     }
                   15442:     return $output;
                   15443: }
                   15444: 
                   15445: sub commit_studentrole {
1.1116    raeburn  15446:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15447:         $credits) = @_;
1.626     raeburn  15448:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15449:     if ($context eq 'auto') {
                   15450:         $linefeed = "\n";
                   15451:     } else {
                   15452:         $linefeed = '<br />'."\n";
                   15453:     }
1.443     albertel 15454:     if (defined($one) && defined($two)) {
                   15455:         my $cid=$one.'_'.$two;
                   15456:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15457:         my $secchange = 0;
                   15458:         my $expire_role_result;
                   15459:         my $modify_section_result;
1.628     raeburn  15460:         if ($oldsec ne '-1') { 
                   15461:             if ($oldsec ne $sec) {
1.443     albertel 15462:                 $secchange = 1;
1.628     raeburn  15463:                 my $now = time;
1.443     albertel 15464:                 my $uurl='/'.$cid;
                   15465:                 $uurl=~s/\_/\//g;
                   15466:                 if ($oldsec) {
                   15467:                     $uurl.='/'.$oldsec;
                   15468:                 }
1.626     raeburn  15469:                 $oldsecurl = $uurl;
1.628     raeburn  15470:                 $expire_role_result = 
1.652     raeburn  15471:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15472:                 if ($env{'request.course.sec'} ne '') { 
                   15473:                     if ($expire_role_result eq 'refused') {
                   15474:                         my @roles = ('st');
                   15475:                         my @statuses = ('previous');
                   15476:                         my @roledoms = ($one);
                   15477:                         my $withsec = 1;
                   15478:                         my %roleshash = 
                   15479:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15480:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15481:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15482:                             my ($oldstart,$oldend) = 
                   15483:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15484:                             if ($oldend > 0 && $oldend <= $now) {
                   15485:                                 $expire_role_result = 'ok';
                   15486:                             }
                   15487:                         }
                   15488:                     }
                   15489:                 }
1.443     albertel 15490:                 $result = $expire_role_result;
                   15491:             }
                   15492:         }
                   15493:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  15494:             $modify_section_result = 
                   15495:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15496:                                                            undef,undef,undef,$sec,
                   15497:                                                            $end,$start,'','',$cid,
                   15498:                                                            '',$context,$credits);
1.443     albertel 15499:             if ($modify_section_result =~ /^ok/) {
                   15500:                 if ($secchange == 1) {
1.628     raeburn  15501:                     if ($sec eq '') {
                   15502:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15503:                     } else {
                   15504:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15505:                     }
1.443     albertel 15506:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15507:                     if ($sec eq '') {
                   15508:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15509:                     } else {
                   15510:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15511:                     }
1.443     albertel 15512:                 } else {
1.628     raeburn  15513:                     if ($sec eq '') {
                   15514:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15515:                     } else {
                   15516:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15517:                     }
1.443     albertel 15518:                 }
                   15519:             } else {
1.1115    raeburn  15520:                 if ($secchange) { 
1.628     raeburn  15521:                     $$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;
                   15522:                 } else {
                   15523:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15524:                 }
1.443     albertel 15525:             }
                   15526:             $result = $modify_section_result;
                   15527:         } elsif ($secchange == 1) {
1.628     raeburn  15528:             if ($oldsec eq '') {
1.1103    raeburn  15529:                 $$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  15530:             } else {
                   15531:                 $$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;
                   15532:             }
1.626     raeburn  15533:             if ($expire_role_result eq 'refused') {
                   15534:                 my $newsecurl = '/'.$cid;
                   15535:                 $newsecurl =~ s/\_/\//g;
                   15536:                 if ($sec ne '') {
                   15537:                     $newsecurl.='/'.$sec;
                   15538:                 }
                   15539:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15540:                     if ($sec eq '') {
                   15541:                         $$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;
                   15542:                     } else {
                   15543:                         $$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;
                   15544:                     }
                   15545:                 }
                   15546:             }
1.443     albertel 15547:         }
                   15548:     } else {
1.626     raeburn  15549:         $$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 15550:         $result = "error: incomplete course id\n";
                   15551:     }
                   15552:     return $result;
                   15553: }
                   15554: 
1.1108    raeburn  15555: sub show_role_extent {
                   15556:     my ($scope,$context,$role) = @_;
                   15557:     $scope =~ s{^/}{};
                   15558:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15559:     push(@courseroles,'co');
                   15560:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15561:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15562:         $scope =~ s{/}{_};
                   15563:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15564:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15565:         my ($audom,$auname) = split(/\//,$scope);
                   15566:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15567:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15568:     } else {
                   15569:         $scope =~ s{/$}{};
                   15570:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15571:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15572:     }
                   15573: }
                   15574: 
1.443     albertel 15575: ############################################################
                   15576: ############################################################
                   15577: 
1.566     albertel 15578: sub check_clone {
1.578     raeburn  15579:     my ($args,$linefeed) = @_;
1.566     albertel 15580:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15581:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15582:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15583:     my $clonemsg;
                   15584:     my $can_clone = 0;
1.944     raeburn  15585:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15586:     if ($lctype ne 'community') {
                   15587:         $lctype = 'course';
                   15588:     }
1.566     albertel 15589:     if ($clonehome eq 'no_host') {
1.944     raeburn  15590:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15591:             $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'});
                   15592:         } else {
                   15593:             $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'});
                   15594:         }     
1.566     albertel 15595:     } else {
                   15596: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15597:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15598:             if ($clonedesc{'type'} ne 'Community') {
1.1262    raeburn  15599:                 $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
1.908     raeburn  15600:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15601:             }
                   15602:         }
1.1262    raeburn  15603: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15604:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15605: 	    $can_clone = 1;
                   15606: 	} else {
1.1221    raeburn  15607: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15608: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  15609:             if ($clonehash{'cloners'} eq '') {
                   15610:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15611:                 if ($domdefs{'canclone'}) {
                   15612:                     unless ($domdefs{'canclone'} eq 'none') {
                   15613:                         if ($domdefs{'canclone'} eq 'domain') {
                   15614:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15615:                                 $can_clone = 1;
                   15616:                             }
                   15617:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15618:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15619:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15620:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15621:                                 $can_clone = 1;
                   15622:                             }
                   15623:                         }
                   15624:                     }
                   15625:                 }
1.578     raeburn  15626:             } else {
1.1221    raeburn  15627: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15628:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15629:                     $can_clone = 1;
1.1221    raeburn  15630:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15631:                     $can_clone = 1;
1.1225    raeburn  15632:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15633:                     $can_clone = 1;
1.1221    raeburn  15634:                 }
                   15635:                 unless ($can_clone) {
1.1225    raeburn  15636:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15637:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  15638:                         my (%gotdomdefaults,%gotcodedefaults);
                   15639:                         foreach my $cloner (@cloners) {
                   15640:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15641:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15642:                                 my (%codedefaults,@code_order);
                   15643:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15644:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15645:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15646:                                     }
                   15647:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15648:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15649:                                     }
                   15650:                                 } else {
                   15651:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15652:                                                                             \%codedefaults,
                   15653:                                                                             \@code_order);
                   15654:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15655:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15656:                                 }
                   15657:                                 if (@code_order > 0) {
                   15658:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15659:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15660:                                                                                 $args->{'crscode'})) {
                   15661:                                         $can_clone = 1;
                   15662:                                         last;
                   15663:                                     }
                   15664:                                 }
                   15665:                             }
                   15666:                         }
                   15667:                     }
1.1225    raeburn  15668:                 }
                   15669:             }
                   15670:             unless ($can_clone) {
                   15671:                 my $ccrole = 'cc';
                   15672:                 if ($args->{'crstype'} eq 'Community') {
                   15673:                     $ccrole = 'co';
                   15674:                 }
                   15675: 	        my %roleshash =
                   15676: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15677: 					          $args->{'ccdomain'},
                   15678:                                                   'userroles',['active'],[$ccrole],
                   15679: 					          [$args->{'clonedomain'}]);
                   15680: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15681:                     $can_clone = 1;
                   15682:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15683:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15684:                     $can_clone = 1;
1.1221    raeburn  15685:                 }
                   15686:             }
                   15687:             unless ($can_clone) {
                   15688:                 if ($args->{'crstype'} eq 'Community') {
                   15689:                     $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  15690:                 } else {
1.1221    raeburn  15691:                     $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'});
                   15692:                 }
1.566     albertel 15693: 	    }
1.578     raeburn  15694:         }
1.566     albertel 15695:     }
                   15696:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15697: }
                   15698: 
1.444     albertel 15699: sub construct_course {
1.1262    raeburn  15700:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15701:         $cnum,$category,$coderef) = @_;
1.444     albertel 15702:     my $outcome;
1.541     raeburn  15703:     my $linefeed =  '<br />'."\n";
                   15704:     if ($context eq 'auto') {
                   15705:         $linefeed = "\n";
                   15706:     }
1.566     albertel 15707: 
                   15708: #
                   15709: # Are we cloning?
                   15710: #
                   15711:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15712:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15713: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15714: 	if ($context ne 'auto') {
1.578     raeburn  15715:             if ($clonemsg ne '') {
                   15716: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15717:             }
1.566     albertel 15718: 	}
                   15719: 	$outcome .= $clonemsg.$linefeed;
                   15720: 
                   15721:         if (!$can_clone) {
                   15722: 	    return (0,$outcome);
                   15723: 	}
                   15724:     }
                   15725: 
1.444     albertel 15726: #
                   15727: # Open course
                   15728: #
1.1239    raeburn  15729:     my $showncrstype;
                   15730:     if ($args->{'crstype'} eq 'Placement') {
                   15731:         $showncrstype = 'placement test'; 
                   15732:     } else {  
                   15733:         $showncrstype = lc($args->{'crstype'});
                   15734:     }
1.444     albertel 15735:     my %cenv=();
                   15736:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15737:                                              $args->{'cdescr'},
                   15738:                                              $args->{'curl'},
                   15739:                                              $args->{'course_home'},
                   15740:                                              $args->{'nonstandard'},
                   15741:                                              $args->{'crscode'},
                   15742:                                              $args->{'ccuname'}.':'.
                   15743:                                              $args->{'ccdomain'},
1.882     raeburn  15744:                                              $args->{'crstype'},
1.885     raeburn  15745:                                              $cnum,$context,$category);
1.444     albertel 15746: 
                   15747:     # Note: The testing routines depend on this being output; see 
                   15748:     # Utils::Course. This needs to at least be output as a comment
                   15749:     # if anyone ever decides to not show this, and Utils::Course::new
                   15750:     # will need to be suitably modified.
1.1239    raeburn  15751:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
1.943     raeburn  15752:     if ($$courseid =~ /^error:/) {
                   15753:         return (0,$outcome);
                   15754:     }
                   15755: 
1.444     albertel 15756: #
                   15757: # Check if created correctly
                   15758: #
1.479     albertel 15759:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15760:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15761:     if ($crsuhome eq 'no_host') {
                   15762:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15763:         return (0,$outcome);
                   15764:     }
1.541     raeburn  15765:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15766: 
1.444     albertel 15767: #
1.566     albertel 15768: # Do the cloning
                   15769: #   
                   15770:     if ($can_clone && $cloneid) {
1.1239    raeburn  15771: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
1.566     albertel 15772: 	if ($context ne 'auto') {
                   15773: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15774: 	}
                   15775: 	$outcome .= $clonemsg.$linefeed;
                   15776: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15777: # Copy all files
1.637     www      15778: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15779: # Restore URL
1.566     albertel 15780: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15781: # Restore title
1.566     albertel 15782: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15783: # Restore creation date, creator and creation context.
                   15784:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15785:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15786:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15787: # Mark as cloned
1.566     albertel 15788: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15789: # Need to clone grading mode
                   15790:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15791:         $cenv{'grading'}=$newenv{'grading'};
                   15792: # Do not clone these environment entries
                   15793:         &Apache::lonnet::del('environment',
                   15794:                   ['default_enrollment_start_date',
                   15795:                    'default_enrollment_end_date',
                   15796:                    'question.email',
                   15797:                    'policy.email',
                   15798:                    'comment.email',
                   15799:                    'pch.users.denied',
1.725     raeburn  15800:                    'plc.users.denied',
                   15801:                    'hidefromcat',
1.1121    raeburn  15802:                    'checkforpriv',
1.1166    raeburn  15803:                    'categories',
                   15804:                    'internal.uniquecode'],
1.638     www      15805:                    $$crsudom,$$crsunum);
1.1170    raeburn  15806:         if ($args->{'textbook'}) {
                   15807:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15808:         }
1.444     albertel 15809:     }
1.566     albertel 15810: 
1.444     albertel 15811: #
                   15812: # Set environment (will override cloned, if existing)
                   15813: #
                   15814:     my @sections = ();
                   15815:     my @xlists = ();
                   15816:     if ($args->{'crstype'}) {
                   15817:         $cenv{'type'}=$args->{'crstype'};
                   15818:     }
                   15819:     if ($args->{'crsid'}) {
                   15820:         $cenv{'courseid'}=$args->{'crsid'};
                   15821:     }
                   15822:     if ($args->{'crscode'}) {
                   15823:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15824:     }
                   15825:     if ($args->{'crsquota'} ne '') {
                   15826:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15827:     } else {
                   15828:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15829:     }
                   15830:     if ($args->{'ccuname'}) {
                   15831:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15832:                                         ':'.$args->{'ccdomain'};
                   15833:     } else {
                   15834:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15835:     }
1.1116    raeburn  15836:     if ($args->{'defaultcredits'}) {
                   15837:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15838:     }
1.444     albertel 15839:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15840:     if ($args->{'crssections'}) {
                   15841:         $cenv{'internal.sectionnums'} = '';
                   15842:         if ($args->{'crssections'} =~ m/,/) {
                   15843:             @sections = split/,/,$args->{'crssections'};
                   15844:         } else {
                   15845:             $sections[0] = $args->{'crssections'};
                   15846:         }
                   15847:         if (@sections > 0) {
                   15848:             foreach my $item (@sections) {
                   15849:                 my ($sec,$gp) = split/:/,$item;
                   15850:                 my $class = $args->{'crscode'}.$sec;
                   15851:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15852:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15853:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15854:                     push(@badclasses,$class);
1.444     albertel 15855:                 }
                   15856:             }
                   15857:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15858:         }
                   15859:     }
                   15860: # do not hide course coordinator from staff listing, 
                   15861: # even if privileged
                   15862:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  15863: # add course coordinator's domain to domains to check for privileged users
                   15864: # if different to course domain
                   15865:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15866:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15867:     }
1.444     albertel 15868: # add crosslistings
                   15869:     if ($args->{'crsxlist'}) {
                   15870:         $cenv{'internal.crosslistings'}='';
                   15871:         if ($args->{'crsxlist'} =~ m/,/) {
                   15872:             @xlists = split/,/,$args->{'crsxlist'};
                   15873:         } else {
                   15874:             $xlists[0] = $args->{'crsxlist'};
                   15875:         }
                   15876:         if (@xlists > 0) {
                   15877:             foreach my $item (@xlists) {
                   15878:                 my ($xl,$gp) = split/:/,$item;
                   15879:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15880:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15881:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15882:                     push(@badclasses,$xl);
1.444     albertel 15883:                 }
                   15884:             }
                   15885:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15886:         }
                   15887:     }
                   15888:     if ($args->{'autoadds'}) {
                   15889:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15890:     }
                   15891:     if ($args->{'autodrops'}) {
                   15892:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15893:     }
                   15894: # check for notification of enrollment changes
                   15895:     my @notified = ();
                   15896:     if ($args->{'notify_owner'}) {
                   15897:         if ($args->{'ccuname'} ne '') {
                   15898:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15899:         }
                   15900:     }
                   15901:     if ($args->{'notify_dc'}) {
                   15902:         if ($uname ne '') { 
1.630     raeburn  15903:             push(@notified,$uname.':'.$udom);
1.444     albertel 15904:         }
                   15905:     }
                   15906:     if (@notified > 0) {
                   15907:         my $notifylist;
                   15908:         if (@notified > 1) {
                   15909:             $notifylist = join(',',@notified);
                   15910:         } else {
                   15911:             $notifylist = $notified[0];
                   15912:         }
                   15913:         $cenv{'internal.notifylist'} = $notifylist;
                   15914:     }
                   15915:     if (@badclasses > 0) {
                   15916:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  15917:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15918:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15919:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15920:         );
1.1264    raeburn  15921:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15922:                            &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
1.541     raeburn  15923:         if ($context eq 'auto') {
                   15924:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  15925:         } else {
1.566     albertel 15926:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  15927:         }
                   15928:         foreach my $item (@badclasses) {
1.541     raeburn  15929:             if ($context eq 'auto') {
1.1261    raeburn  15930:                 $outcome .= " - $item\n";
1.541     raeburn  15931:             } else {
1.1261    raeburn  15932:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15933:             }
1.1261    raeburn  15934:         }
                   15935:         if ($context eq 'auto') {
                   15936:             $outcome .= $linefeed;
                   15937:         } else {
                   15938:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  15939:         } 
1.444     albertel 15940:     }
                   15941:     if ($args->{'no_end_date'}) {
                   15942:         $args->{'endaccess'} = 0;
                   15943:     }
                   15944:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15945:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15946:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15947:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15948:     if ($args->{'showphotos'}) {
                   15949:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15950:     }
                   15951:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15952:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15953:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15954:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15955:             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'); 
                   15956:             if ($context eq 'auto') {
                   15957:                 $outcome .= $krb_msg;
                   15958:             } else {
1.566     albertel 15959:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15960:             }
                   15961:             $outcome .= $linefeed;
1.444     albertel 15962:         }
                   15963:     }
                   15964:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15965:        if ($args->{'setpolicy'}) {
                   15966:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15967:        }
                   15968:        if ($args->{'setcontent'}) {
                   15969:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15970:        }
1.1251    raeburn  15971:        if ($args->{'setcomment'}) {
                   15972:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15973:        }
1.444     albertel 15974:     }
                   15975:     if ($args->{'reshome'}) {
                   15976: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15977: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15978:     }
                   15979: #
                   15980: # course has keyed access
                   15981: #
                   15982:     if ($args->{'setkeys'}) {
                   15983:        $cenv{'keyaccess'}='yes';
                   15984:     }
                   15985: # if specified, key authority is not course, but user
                   15986: # only active if keyaccess is yes
                   15987:     if ($args->{'keyauth'}) {
1.487     albertel 15988: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15989: 	$user = &LONCAPA::clean_username($user);
                   15990: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15991: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15992: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15993: 	}
                   15994:     }
                   15995: 
1.1166    raeburn  15996: #
1.1167    raeburn  15997: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  15998: #
                   15999:     if ($args->{'uniquecode'}) {
                   16000:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16001:         if ($code) {
                   16002:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  16003:             my %crsinfo =
                   16004:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16005:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16006:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16007:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16008:             } 
1.1166    raeburn  16009:             if (ref($coderef)) {
                   16010:                 $$coderef = $code;
                   16011:             }
                   16012:         }
                   16013:     }
                   16014: 
1.444     albertel 16015:     if ($args->{'disresdis'}) {
                   16016:         $cenv{'pch.roles.denied'}='st';
                   16017:     }
                   16018:     if ($args->{'disablechat'}) {
                   16019:         $cenv{'plc.roles.denied'}='st';
                   16020:     }
                   16021: 
                   16022:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16023:     # course
                   16024:     $cenv{'course.helper.not.run'} = 1;
                   16025:     #
                   16026:     # Use new Randomseed
                   16027:     #
                   16028:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16029:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16030:     #
                   16031:     # The encryption code and receipt prefix for this course
                   16032:     #
                   16033:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16034:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16035:     #
                   16036:     # By default, use standard grading
                   16037:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16038: 
1.541     raeburn  16039:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16040:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16041: #
                   16042: # Open all assignments
                   16043: #
                   16044:     if ($args->{'openall'}) {
                   16045:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   16046:        my %storecontent = ($storeunder         => time,
                   16047:                            $storeunder.'.type' => 'date_start');
                   16048:        
                   16049:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  16050:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16051:    }
                   16052: #
                   16053: # Set first page
                   16054: #
                   16055:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16056: 	    || ($cloneid)) {
1.445     albertel 16057: 	use LONCAPA::map;
1.444     albertel 16058: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16059: 
                   16060: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16061:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16062: 
1.444     albertel 16063:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16064:         my $title; my $url;
                   16065:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16066: 	    $title=&mt('Syllabus');
1.444     albertel 16067:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16068:         } else {
1.963     raeburn  16069:             $title=&mt('Table of Contents');
1.444     albertel 16070:             $url='/adm/navmaps';
                   16071:         }
1.445     albertel 16072: 
                   16073:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16074: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16075: 
                   16076: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16077:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16078:     }
1.566     albertel 16079: 
1.1237    raeburn  16080: # 
                   16081: # Set params for Placement Tests
                   16082: #
1.1239    raeburn  16083:     if ($args->{'crstype'} eq 'Placement') {
                   16084:        my %storecontent; 
                   16085:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   16086:        my %defaults = (
                   16087:                         buttonshide   => { value => 'yes',
                   16088:                                            type => 'string_yesno',},
                   16089:                         type          => { value => 'randomizetry',
                   16090:                                            type  => 'string_questiontype',},
                   16091:                         maxtries      => { value => 1,
                   16092:                                            type => 'int_pos',},
                   16093:                         problemstatus => { value => 'no',
                   16094:                                            type  => 'string_problemstatus',},
                   16095:                       );
                   16096:        foreach my $key (keys(%defaults)) {
                   16097:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   16098:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   16099:        }
1.1237    raeburn  16100:        &Apache::lonnet::cput
                   16101:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   16102:     }
                   16103: 
1.566     albertel 16104:     return (1,$outcome);
1.444     albertel 16105: }
                   16106: 
1.1166    raeburn  16107: sub make_unique_code {
                   16108:     my ($cdom,$cnum) = @_;
                   16109:     # get lock on uniquecodes db
                   16110:     my $lockhash = {
                   16111:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16112:                                                   ':'.$env{'user.domain'},
                   16113:                    };
                   16114:     my $tries = 0;
                   16115:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16116:     my ($code,$error);
                   16117:   
                   16118:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16119:         $tries ++;
                   16120:         sleep 1;
                   16121:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16122:     }
                   16123:     if ($gotlock eq 'ok') {
                   16124:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16125:         my $gotcode;
                   16126:         my $attempts = 0;
                   16127:         while ((!$gotcode) && ($attempts < 100)) {
                   16128:             $code = &generate_code();
                   16129:             if (!exists($currcodes{$code})) {
                   16130:                 $gotcode = 1;
                   16131:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16132:                     $error = 'nostore';
                   16133:                 }
                   16134:             }
                   16135:             $attempts ++;
                   16136:         }
                   16137:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16138:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16139:     } else {
                   16140:         $error = 'nolock';
                   16141:     }
                   16142:     return ($code,$error);
                   16143: }
                   16144: 
                   16145: sub generate_code {
                   16146:     my $code;
                   16147:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16148:     for (my $i=0; $i<6; $i++) {
                   16149:         my $lettnum = int (rand 2);
                   16150:         my $item = '';
                   16151:         if ($lettnum) {
                   16152:             $item = $letts[int( rand(18) )];
                   16153:         } else {
                   16154:             $item = 1+int( rand(8) );
                   16155:         }
                   16156:         $code .= $item;
                   16157:     }
                   16158:     return $code;
                   16159: }
                   16160: 
1.444     albertel 16161: ############################################################
                   16162: ############################################################
                   16163: 
1.1237    raeburn  16164: # Community, Course and Placement Test
1.378     raeburn  16165: sub course_type {
                   16166:     my ($cid) = @_;
                   16167:     if (!defined($cid)) {
                   16168:         $cid = $env{'request.course.id'};
                   16169:     }
1.404     albertel 16170:     if (defined($env{'course.'.$cid.'.type'})) {
                   16171:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16172:     } else {
                   16173:         return 'Course';
1.377     raeburn  16174:     }
                   16175: }
1.156     albertel 16176: 
1.406     raeburn  16177: sub group_term {
                   16178:     my $crstype = &course_type();
                   16179:     my %names = (
                   16180:                   'Course' => 'group',
1.865     raeburn  16181:                   'Community' => 'group',
1.1237    raeburn  16182:                   'Placement' => 'group',
1.406     raeburn  16183:                 );
                   16184:     return $names{$crstype};
                   16185: }
                   16186: 
1.902     raeburn  16187: sub course_types {
1.1237    raeburn  16188:     my @types = ('official','unofficial','community','textbook','placement');
1.902     raeburn  16189:     my %typename = (
                   16190:                          official   => 'Official course',
                   16191:                          unofficial => 'Unofficial course',
                   16192:                          community  => 'Community',
1.1165    raeburn  16193:                          textbook   => 'Textbook course',
1.1237    raeburn  16194:                          placement  => 'Placement test',
1.902     raeburn  16195:                    );
                   16196:     return (\@types,\%typename);
                   16197: }
                   16198: 
1.156     albertel 16199: sub icon {
                   16200:     my ($file)=@_;
1.505     albertel 16201:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16202:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16203:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16204:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16205: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16206: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16207: 	            $curfext.".gif") {
                   16208: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16209: 		$curfext.".gif";
                   16210: 	}
                   16211:     }
1.249     albertel 16212:     return &lonhttpdurl($iconname);
1.154     albertel 16213: } 
1.84      albertel 16214: 
1.575     albertel 16215: sub lonhttpdurl {
1.692     www      16216: #
                   16217: # Had been used for "small fry" static images on separate port 8080.
                   16218: # Modify here if lightweight http functionality desired again.
                   16219: # Currently eliminated due to increasing firewall issues.
                   16220: #
1.575     albertel 16221:     my ($url)=@_;
1.692     www      16222:     return $url;
1.215     albertel 16223: }
                   16224: 
1.213     albertel 16225: sub connection_aborted {
                   16226:     my ($r)=@_;
                   16227:     $r->print(" ");$r->rflush();
                   16228:     my $c = $r->connection;
                   16229:     return $c->aborted();
                   16230: }
                   16231: 
1.221     foxr     16232: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16233: #    strings as 'strings'.
                   16234: sub escape_single {
1.221     foxr     16235:     my ($input) = @_;
1.223     albertel 16236:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16237:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16238:     return $input;
                   16239: }
1.223     albertel 16240: 
1.222     foxr     16241: #  Same as escape_single, but escape's "'s  This 
                   16242: #  can be used for  "strings"
                   16243: sub escape_double {
                   16244:     my ($input) = @_;
                   16245:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16246:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16247:     return $input;
                   16248: }
1.223     albertel 16249:  
1.222     foxr     16250: #   Escapes the last element of a full URL.
                   16251: sub escape_url {
                   16252:     my ($url)   = @_;
1.238     raeburn  16253:     my @urlslices = split(/\//, $url,-1);
1.369     www      16254:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  16255:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16256: }
1.462     albertel 16257: 
1.820     raeburn  16258: sub compare_arrays {
                   16259:     my ($arrayref1,$arrayref2) = @_;
                   16260:     my (@difference,%count);
                   16261:     @difference = ();
                   16262:     %count = ();
                   16263:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16264:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16265:         foreach my $element (keys(%count)) {
                   16266:             if ($count{$element} == 1) {
                   16267:                 push(@difference,$element);
                   16268:             }
                   16269:         }
                   16270:     }
                   16271:     return @difference;
                   16272: }
                   16273: 
1.817     bisitz   16274: # -------------------------------------------------------- Initialize user login
1.462     albertel 16275: sub init_user_environment {
1.463     albertel 16276:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16277:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16278: 
                   16279:     my $public=($username eq 'public' && $domain eq 'public');
                   16280: 
1.1062    raeburn  16281:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16282:     my $now=time;
                   16283: 
                   16284:     if ($public) {
                   16285: 	my $max_public=100;
                   16286: 	my $oldest;
                   16287: 	my $oldest_time=0;
                   16288: 	for(my $next=1;$next<=$max_public;$next++) {
                   16289: 	    if (-e $lonids."/publicuser_$next.id") {
                   16290: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16291: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16292: 		    $oldest_time=$mtime;
                   16293: 		    $oldest=$next;
                   16294: 		}
                   16295: 	    } else {
                   16296: 		$cookie="publicuser_$next";
                   16297: 		last;
                   16298: 	    }
                   16299: 	}
                   16300: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16301:     } else {
1.1275    raeburn  16302: 	# See if old ID present, if so, remove if this isn't a robot,
                   16303: 	# killing any existing non-robot sessions
1.463     albertel 16304: 	if (!$args->{'robot'}) {
                   16305: 	    opendir(DIR,$lonids);
                   16306: 	    while ($filename=readdir(DIR)) {
                   16307: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1295    raeburn  16308:                     if ($ENV{'SERVER_PORT'} == 443) {
                   16309:                         my $linkedfile;
                   16310:                         if (tie(my %oldenv,'GDBM_File',"$lonids/$cookie.id",
                   16311:                                 &GDBM_READER(),0640)) {
                   16312:                             if (exists($oldenv{'user.linkedenv'})) {
                   16313:                                 $linkedfile = $oldenv{'user.linkedenv'};
                   16314:                             }
                   16315:                             untie(%oldenv);
                   16316:                         }
                   16317:                         if (unlink($lonids.'/'.$filename)) {
                   16318:                             if ($linkedfile =~ /^[a-f0-9]+_linked\.id$/) {
                   16319:                                 unlink($lonids.'/'.$linkedfile);
                   16320:                             }
                   16321:                         }
                   16322:                     } else {
                   16323:                         unlink($lonids.'/'.$filename);
                   16324:                     }
1.463     albertel 16325: 		}
1.462     albertel 16326: 	    }
1.463     albertel 16327: 	    closedir(DIR);
1.1204    raeburn  16328: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16329:             my $namespace = 'nohist_courseeditor';
                   16330:             my $lockingkey = 'paste'."\0".'locked_num';
                   16331:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16332:                                                 $domain,$username);
                   16333:             if (exists($lockhash{$lockingkey})) {
                   16334:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16335:                 unless ($delresult eq 'ok') {
                   16336:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16337:                 }
                   16338:             }
1.462     albertel 16339: 	}
                   16340: # Give them a new cookie
1.463     albertel 16341: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16342: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16343: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16344:     
                   16345: # Initialize roles
                   16346: 
1.1062    raeburn  16347: 	($userroles,$firstaccenv,$timerintenv) = 
                   16348:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16349:     }
                   16350: # ------------------------------------ Check browser type and MathML capability
                   16351: 
1.1194    raeburn  16352:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16353:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16354: 
                   16355: # ------------------------------------------------------------- Get environment
                   16356: 
                   16357:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16358:     my ($tmp) = keys(%userenv);
1.1275    raeburn  16359:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 16360: 	undef(%userenv);
                   16361:     }
                   16362:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16363: 	$form->{'interface'}=$userenv{'interface'};
                   16364:     }
                   16365:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16366: 
                   16367: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16368:     foreach my $option ('interface','localpath','localres') {
                   16369:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16370:     }
                   16371: # --------------------------------------------------------- Write first profile
                   16372: 
                   16373:     {
                   16374: 	my %initial_env = 
                   16375: 	    ("user.name"          => $username,
                   16376: 	     "user.domain"        => $domain,
                   16377: 	     "user.home"          => $authhost,
                   16378: 	     "browser.type"       => $clientbrowser,
                   16379: 	     "browser.version"    => $clientversion,
                   16380: 	     "browser.mathml"     => $clientmathml,
                   16381: 	     "browser.unicode"    => $clientunicode,
                   16382: 	     "browser.os"         => $clientos,
1.1137    raeburn  16383:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  16384:              "browser.info"       => $clientinfo,
1.1194    raeburn  16385:              "browser.osversion"  => $clientosversion,
1.462     albertel 16386: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16387: 	     "request.course.fn"  => '',
                   16388: 	     "request.course.uri" => '',
                   16389: 	     "request.course.sec" => '',
                   16390: 	     "request.role"       => 'cm',
                   16391: 	     "request.role.adv"   => $env{'user.adv'},
                   16392: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   16393: 
                   16394:         if ($form->{'localpath'}) {
                   16395: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16396: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16397:         }
                   16398: 	
                   16399: 	if ($form->{'interface'}) {
                   16400: 	    $form->{'interface'}=~s/\W//gs;
                   16401: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16402: 	    $env{'browser.interface'}=$form->{'interface'};
                   16403: 	}
                   16404: 
1.1157    raeburn  16405:         if ($form->{'iptoken'}) {
                   16406:             my $lonhost = $r->dir_config('lonHostID');
                   16407:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16408:             $env{'user.noloadbalance'} = $lonhost;
                   16409:         }
                   16410: 
1.1268    raeburn  16411:         if ($form->{'noloadbalance'}) {
                   16412:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16413:             my $hosthere = $form->{'noloadbalance'};
                   16414:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16415:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16416:                 $env{'user.noloadbalance'} = $hosthere;
                   16417:             }
                   16418:         }
                   16419: 
1.1016    raeburn  16420:         unless ($domain eq 'public') {
1.1273    raeburn  16421:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16422:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   16423: 
                   16424:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   16425:                 $userenv{'availabletools.'.$tool} = 
                   16426:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16427:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16428:             }
1.980     raeburn  16429: 
1.1273    raeburn  16430:             foreach my $crstype ('official','unofficial','community','textbook','placement') {
                   16431:                 $userenv{'canrequest.'.$crstype} =
                   16432:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16433:                                                       'reload','requestcourses',
                   16434:                                                       \%userenv,\%domdef,\%is_adv);
                   16435:             }
1.724     raeburn  16436: 
1.1273    raeburn  16437:             $userenv{'canrequest.author'} =
                   16438:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16439:                                                   'reload','requestauthor',
1.980     raeburn  16440:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  16441:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16442:                                                  $domain,$username);
                   16443:             my $reqstatus = $reqauthor{'author_status'};
                   16444:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   16445:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16446:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16447:                                                       $reqauthor{'author'}{'timestamp'};
                   16448:                 }
1.1092    raeburn  16449:             }
1.1287    raeburn  16450:             my ($types,$typename) = &course_types();
                   16451:             if (ref($types) eq 'ARRAY') {
                   16452:                 my @options = ('approval','validate','autolimit');
                   16453:                 my $optregex = join('|',@options);
                   16454:                 my (%willtrust,%trustchecked);
                   16455:                 foreach my $type (@{$types}) {
                   16456:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   16457:                     if ($dom_str ne '') {
                   16458:                         my $updatedstr = '';
                   16459:                         my @possdomains = split(',',$dom_str);
                   16460:                         foreach my $entry (@possdomains) {
                   16461:                             my ($extdom,$extopt) = split(':',$entry);
                   16462:                             unless ($trustchecked{$extdom}) {
                   16463:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   16464:                                 $trustchecked{$extdom} = 1;
                   16465:                             }
                   16466:                             if ($willtrust{$extdom}) {
                   16467:                                 $updatedstr .= $entry.',';
                   16468:                             }
                   16469:                         }
                   16470:                         $updatedstr =~ s/,$//;
                   16471:                         if ($updatedstr) {
                   16472:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   16473:                         } else {
                   16474:                             delete($userenv{'reqcrsotherdom.'.$type});
                   16475:                         }
                   16476:                     }
                   16477:                 }
                   16478:             }
1.1092    raeburn  16479:         }
1.462     albertel 16480: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16481: 
1.462     albertel 16482: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16483: 		 &GDBM_WRCREAT(),0640)) {
                   16484: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16485: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16486: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16487:             if (ref($firstaccenv) eq 'HASH') {
                   16488:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16489:             }
                   16490:             if (ref($timerintenv) eq 'HASH') {
                   16491:                 &_add_to_env(\%disk_env,$timerintenv);
                   16492:             }
1.463     albertel 16493: 	    if (ref($args->{'extra_env'})) {
                   16494: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16495: 	    }
1.462     albertel 16496: 	    untie(%disk_env);
                   16497: 	} else {
1.705     tempelho 16498: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16499: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16500: 	    return 'error: '.$!;
                   16501: 	}
                   16502:     }
                   16503:     $env{'request.role'}='cm';
                   16504:     $env{'request.role.adv'}=$env{'user.adv'};
                   16505:     $env{'browser.type'}=$clientbrowser;
                   16506: 
                   16507:     return $cookie;
                   16508: 
                   16509: }
                   16510: 
                   16511: sub _add_to_env {
                   16512:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16513:     if (ref($env_data) eq 'HASH') {
                   16514:         while (my ($key,$value) = each(%$env_data)) {
                   16515: 	    $idf->{$prefix.$key} = $value;
                   16516: 	    $env{$prefix.$key}   = $value;
                   16517:         }
1.462     albertel 16518:     }
                   16519: }
                   16520: 
1.685     tempelho 16521: # --- Get the symbolic name of a problem and the url
                   16522: sub get_symb {
                   16523:     my ($request,$silent) = @_;
1.726     raeburn  16524:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16525:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16526:     if ($symb eq '') {
                   16527:         if (!$silent) {
1.1071    raeburn  16528:             if (ref($request)) { 
                   16529:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16530:             }
1.685     tempelho 16531:             return ();
                   16532:         }
                   16533:     }
                   16534:     &Apache::lonenc::check_decrypt(\$symb);
                   16535:     return ($symb);
                   16536: }
                   16537: 
                   16538: # --------------------------------------------------------------Get annotation
                   16539: 
                   16540: sub get_annotation {
                   16541:     my ($symb,$enc) = @_;
                   16542: 
                   16543:     my $key = $symb;
                   16544:     if (!$enc) {
                   16545:         $key =
                   16546:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16547:     }
                   16548:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16549:     return $annotation{$key};
                   16550: }
                   16551: 
                   16552: sub clean_symb {
1.731     raeburn  16553:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16554: 
                   16555:     &Apache::lonenc::check_decrypt(\$symb);
                   16556:     my $enc = $env{'request.enc'};
1.731     raeburn  16557:     if ($delete_enc) {
1.730     raeburn  16558:         delete($env{'request.enc'});
                   16559:     }
1.685     tempelho 16560: 
                   16561:     return ($symb,$enc);
                   16562: }
1.462     albertel 16563: 
1.1181    raeburn  16564: ############################################################
                   16565: ############################################################
                   16566: 
                   16567: =pod
                   16568: 
                   16569: =head1 Routines for building display used to search for courses
                   16570: 
                   16571: 
                   16572: =over 4
                   16573: 
                   16574: =item * &build_filters()
                   16575: 
                   16576: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  16577: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16578: and quotacheck.pl
                   16579: 
1.1181    raeburn  16580: 
                   16581: Inputs:
                   16582: 
                   16583: filterlist - anonymous array of fields to include as potential filters 
                   16584: 
                   16585: crstype - course type
                   16586: 
                   16587: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16588:               to pop-open a course selector (will contain "extra element"). 
                   16589: 
                   16590: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16591: 
                   16592: filter - anonymous hash of criteria and their values
                   16593: 
                   16594: action - form action
                   16595: 
                   16596: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16597: 
1.1182    raeburn  16598: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  16599: 
                   16600: cloneruname - username of owner of new course who wants to clone
                   16601: 
                   16602: clonerudom - domain of owner of new course who wants to clone
                   16603: 
                   16604: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   16605: 
                   16606: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16607: 
                   16608: codedom - domain
                   16609: 
                   16610: formname - value of form element named "form". 
                   16611: 
                   16612: fixeddom - domain, if fixed.
                   16613: 
                   16614: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   16615: 
                   16616: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   16617: 
                   16618: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16619: 
                   16620: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16621: 
                   16622: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16623: 
                   16624: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16625: 
                   16626: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16627: 
1.1182    raeburn  16628: 
1.1181    raeburn  16629: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16630: 
1.1182    raeburn  16631: 
1.1181    raeburn  16632: Side Effects: None
                   16633: 
                   16634: =cut
                   16635: 
                   16636: # ---------------------------------------------- search for courses based on last activity etc.
                   16637: 
                   16638: sub build_filters {
                   16639:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16640:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16641:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16642:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16643:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  16644:     my ($list,$jscript);
1.1181    raeburn  16645:     my $onchange = 'javascript:updateFilters(this)';
                   16646:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16647:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16648:         $typeselectform,$instcodetitle);
                   16649:     if ($formname eq '') {
                   16650:         $formname = $caller;
                   16651:     }
                   16652:     foreach my $item (@{$filterlist}) {
                   16653:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16654:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16655:             if ($item eq 'domainfilter') {
                   16656:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16657:             } elsif ($item eq 'coursefilter') {
                   16658:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16659:             } elsif ($item eq 'ownerfilter') {
                   16660:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16661:             } elsif ($item eq 'ownerdomfilter') {
                   16662:                 $filter->{'ownerdomfilter'} =
                   16663:                     &LONCAPA::clean_domain($filter->{$item});
                   16664:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16665:                                                        'ownerdomfilter',1);
                   16666:             } elsif ($item eq 'personfilter') {
                   16667:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16668:             } elsif ($item eq 'persondomfilter') {
                   16669:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16670:                                                         'persondomfilter',1);
                   16671:             } else {
                   16672:                 $filter->{$item} =~ s/\W//g;
                   16673:             }
                   16674:             if (!$filter->{$item}) {
                   16675:                 $filter->{$item} = '';
                   16676:             }
                   16677:         }
                   16678:         if ($item eq 'domainfilter') {
                   16679:             my $allow_blank = 1;
                   16680:             if ($formname eq 'portform') {
                   16681:                 $allow_blank=0;
                   16682:             } elsif ($formname eq 'studentform') {
                   16683:                 $allow_blank=0;
                   16684:             }
                   16685:             if ($fixeddom) {
                   16686:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16687:                                     ' value="'.$codedom.'" />'.
                   16688:                                     &Apache::lonnet::domain($codedom,'description');
                   16689:             } else {
                   16690:                 $domainselectform = &select_dom_form($filter->{$item},
                   16691:                                                      'domainfilter',
                   16692:                                                       $allow_blank,'',$onchange);
                   16693:             }
                   16694:         } else {
                   16695:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16696:         }
                   16697:     }
                   16698: 
                   16699:     # last course activity filter and selection
                   16700:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16701: 
                   16702:     # course created filter and selection
                   16703:     if (exists($filter->{'createdfilter'})) {
                   16704:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16705:     }
                   16706: 
1.1239    raeburn  16707:     my $prefix = $crstype;
                   16708:     if ($crstype eq 'Placement') {
                   16709:         $prefix = 'Placement Test'
                   16710:     }
1.1181    raeburn  16711:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  16712:                 'cac' => "$prefix Activity",
                   16713:                 'ccr' => "$prefix Created",
                   16714:                 'cde' => "$prefix Title",
                   16715:                 'cdo' => "$prefix Domain",
1.1181    raeburn  16716:                 'ins' => 'Institutional Code',
                   16717:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  16718:                 'cow' => "$prefix Owner/Co-owner",
                   16719:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  16720:                 'cog' => 'Type',
                   16721:              );
                   16722: 
                   16723:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16724:         my $typeval = 'Course';
                   16725:         if ($crstype eq 'Community') {
                   16726:             $typeval = 'Community';
1.1239    raeburn  16727:         } elsif ($crstype eq 'Placement') {
                   16728:             $typeval = 'Placement';
1.1181    raeburn  16729:         }
                   16730:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16731:     } else {
                   16732:         $typeselectform =  '<select name="type" size="1"';
                   16733:         if ($onchange) {
                   16734:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16735:         }
                   16736:         $typeselectform .= '>'."\n";
1.1237    raeburn  16737:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  16738:             my $shown;
                   16739:             if ($posstype eq 'Placement') {
                   16740:                 $shown = &mt('Placement Test');
                   16741:             } else {
                   16742:                 $shown = &mt($posstype);
                   16743:             }
1.1181    raeburn  16744:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  16745:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  16746:         }
                   16747:         $typeselectform.="</select>";
                   16748:     }
                   16749: 
                   16750:     my ($cloneableonlyform,$cloneabletitle);
                   16751:     if (exists($filter->{'cloneableonly'})) {
                   16752:         my $cloneableon = '';
                   16753:         my $cloneableoff = ' checked="checked"';
                   16754:         if ($filter->{'cloneableonly'}) {
                   16755:             $cloneableon = $cloneableoff;
                   16756:             $cloneableoff = '';
                   16757:         }
                   16758:         $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>';
                   16759:         if ($formname eq 'ccrs') {
1.1187    bisitz   16760:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  16761:         } else {
                   16762:             $cloneabletitle = &mt('Cloneable by you');
                   16763:         }
                   16764:     }
                   16765:     my $officialjs;
                   16766:     if ($crstype eq 'Course') {
                   16767:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  16768: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16769: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16770:             if ($codedom) { 
1.1181    raeburn  16771:                 $officialjs = 1;
                   16772:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16773:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16774:                                                                   $officialjs,$codetitlesref);
                   16775:                 if ($jscript) {
1.1182    raeburn  16776:                     $jscript = '<script type="text/javascript">'."\n".
                   16777:                                '// <![CDATA['."\n".
                   16778:                                $jscript."\n".
                   16779:                                '// ]]>'."\n".
                   16780:                                '</script>'."\n";
1.1181    raeburn  16781:                 }
                   16782:             }
                   16783:             if ($instcodeform eq '') {
                   16784:                 $instcodeform =
                   16785:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16786:                     $list->{'instcodefilter'}.'" />';
                   16787:                 $instcodetitle = $lt{'ins'};
                   16788:             } else {
                   16789:                 $instcodetitle = $lt{'inc'};
                   16790:             }
                   16791:             if ($fixeddom) {
                   16792:                 $instcodetitle .= '<br />('.$codedom.')';
                   16793:             }
                   16794:         }
                   16795:     }
                   16796:     my $output = qq|
                   16797: <form method="post" name="filterpicker" action="$action">
                   16798: <input type="hidden" name="form" value="$formname" />
                   16799: |;
                   16800:     if ($formname eq 'modifycourse') {
                   16801:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16802:                    '<input type="hidden" name="prevphase" value="'.
                   16803:                    $prevphase.'" />'."\n";
1.1198    musolffc 16804:     } elsif ($formname eq 'quotacheck') {
                   16805:         $output .= qq|
                   16806: <input type="hidden" name="sortby" value="" />
                   16807: <input type="hidden" name="sortorder" value="" />
                   16808: |;
                   16809:     } else {
1.1181    raeburn  16810:         my $name_input;
                   16811:         if ($cnameelement ne '') {
                   16812:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16813:                           $cnameelement.'" />';
                   16814:         }
                   16815:         $output .= qq|
1.1182    raeburn  16816: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16817: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  16818: $name_input
                   16819: $roleelement
                   16820: $multelement
                   16821: $typeelement
                   16822: |;
                   16823:         if ($formname eq 'portform') {
                   16824:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16825:         }
                   16826:     }
                   16827:     if ($fixeddom) {
                   16828:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16829:     }
                   16830:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16831:     if ($sincefilterform) {
                   16832:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16833:                   .$sincefilterform
                   16834:                   .&Apache::lonhtmlcommon::row_closure();
                   16835:     }
                   16836:     if ($createdfilterform) {
                   16837:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16838:                   .$createdfilterform
                   16839:                   .&Apache::lonhtmlcommon::row_closure();
                   16840:     }
                   16841:     if ($domainselectform) {
                   16842:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16843:                   .$domainselectform
                   16844:                   .&Apache::lonhtmlcommon::row_closure();
                   16845:     }
                   16846:     if ($typeselectform) {
                   16847:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16848:             $output .= $typeselectform;
                   16849:         } else {
                   16850:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16851:                       .$typeselectform
                   16852:                       .&Apache::lonhtmlcommon::row_closure();
                   16853:         }
                   16854:     }
                   16855:     if ($instcodeform) {
                   16856:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16857:                   .$instcodeform
                   16858:                   .&Apache::lonhtmlcommon::row_closure();
                   16859:     }
                   16860:     if (exists($filter->{'ownerfilter'})) {
                   16861:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16862:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16863:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16864:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16865:                    $ownerdomselectform.'</td></tr></table>'.
                   16866:                    &Apache::lonhtmlcommon::row_closure();
                   16867:     }
                   16868:     if (exists($filter->{'personfilter'})) {
                   16869:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16870:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16871:                    '<input type="text" name="personfilter" size="20" value="'.
                   16872:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16873:                    $persondomselectform.'</td></tr></table>'.
                   16874:                    &Apache::lonhtmlcommon::row_closure();
                   16875:     }
                   16876:     if (exists($filter->{'coursefilter'})) {
                   16877:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16878:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16879:                   .$list->{'coursefilter'}.'" />'
                   16880:                   .&Apache::lonhtmlcommon::row_closure();
                   16881:     }
                   16882:     if ($cloneableonlyform) {
                   16883:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16884:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16885:     }
                   16886:     if (exists($filter->{'descriptfilter'})) {
                   16887:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16888:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16889:                   .$list->{'descriptfilter'}.'" />'
                   16890:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16891:     }
                   16892:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16893:                '<input type="hidden" name="updater" value="" />'."\n".
                   16894:                '<input type="submit" name="gosearch" value="'.
                   16895:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16896:     return $jscript.$clonewarning.$output;
                   16897: }
                   16898: 
                   16899: =pod 
                   16900: 
                   16901: =item * &timebased_select_form()
                   16902: 
1.1182    raeburn  16903: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  16904: filter e.g., Course Activity, Course Created, when searching for courses
                   16905: or communities
                   16906: 
                   16907: Inputs:
                   16908: 
                   16909: item - name of form element (sincefilter or createdfilter)
                   16910: 
                   16911: filter - anonymous hash of criteria and their values
                   16912: 
                   16913: Returns: HTML for a select box contained a blank, then six time selections,
                   16914:          with value set in incoming form variables currently selected. 
                   16915: 
                   16916: Side Effects: None
                   16917: 
                   16918: =cut
                   16919: 
                   16920: sub timebased_select_form {
                   16921:     my ($item,$filter) = @_;
                   16922:     if (ref($filter) eq 'HASH') {
                   16923:         $filter->{$item} =~ s/[^\d-]//g;
                   16924:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16925:         return &select_form(
                   16926:                             $filter->{$item},
                   16927:                             $item,
                   16928:                             {      '-1' => '',
                   16929:                                 '86400' => &mt('today'),
                   16930:                                '604800' => &mt('last week'),
                   16931:                               '2592000' => &mt('last month'),
                   16932:                               '7776000' => &mt('last three months'),
                   16933:                              '15552000' => &mt('last six months'),
                   16934:                              '31104000' => &mt('last year'),
                   16935:                     'select_form_order' =>
                   16936:                            ['-1','86400','604800','2592000','7776000',
                   16937:                             '15552000','31104000']});
                   16938:     }
                   16939: }
                   16940: 
                   16941: =pod
                   16942: 
                   16943: =item * &js_changer()
                   16944: 
                   16945: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  16946: when course type or domain is changed, and also to hide 'Searching ...' on
                   16947: page load completion for page showing search result.
1.1181    raeburn  16948: 
                   16949: Inputs: None
                   16950: 
1.1183    raeburn  16951: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  16952: 
                   16953: Side Effects: None
                   16954: 
                   16955: =cut
                   16956: 
                   16957: sub js_changer {
                   16958:     return <<ENDJS;
                   16959: <script type="text/javascript">
                   16960: // <![CDATA[
                   16961: function updateFilters(caller) {
                   16962:     if (typeof(caller) != "undefined") {
                   16963:         document.filterpicker.updater.value = caller.name;
                   16964:     }
                   16965:     document.filterpicker.submit();
                   16966: }
1.1183    raeburn  16967: 
                   16968: function hideSearching() {
                   16969:     if (document.getElementById('searching')) {
                   16970:         document.getElementById('searching').style.display = 'none';
                   16971:     }
                   16972:     return;
                   16973: }
                   16974: 
1.1181    raeburn  16975: // ]]>
                   16976: </script>
                   16977: 
                   16978: ENDJS
                   16979: }
                   16980: 
                   16981: =pod
                   16982: 
1.1182    raeburn  16983: =item * &search_courses()
                   16984: 
                   16985: Process selected filters form course search form and pass to lonnet::courseiddump
                   16986: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16987: 
                   16988: Inputs:
                   16989: 
                   16990: dom - domain being searched 
                   16991: 
                   16992: type - course type ('Course' or 'Community' or '.' if any).
                   16993: 
                   16994: filter - anonymous hash of criteria and their values
                   16995: 
                   16996: numtitles - for institutional codes - number of categories
                   16997: 
                   16998: cloneruname - optional username of new course owner
                   16999: 
                   17000: clonerudom - optional domain of new course owner
                   17001: 
1.1221    raeburn  17002: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  17003:             (used when DC is using course creation form)
                   17004: 
                   17005: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17006: 
1.1221    raeburn  17007: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17008:            (and so can clone automatically)
                   17009: 
                   17010: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17011: 
                   17012: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17013:               courses to clone 
1.1182    raeburn  17014: 
                   17015: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17016: 
                   17017: 
                   17018: Side Effects: None
                   17019: 
                   17020: =cut
                   17021: 
                   17022: 
                   17023: sub search_courses {
1.1221    raeburn  17024:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17025:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17026:     my (%courses,%showcourses,$cloner);
                   17027:     if (($filter->{'ownerfilter'} ne '') ||
                   17028:         ($filter->{'ownerdomfilter'} ne '')) {
                   17029:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17030:                                        $filter->{'ownerdomfilter'};
                   17031:     }
                   17032:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17033:         if (!$filter->{$item}) {
                   17034:             $filter->{$item}='.';
                   17035:         }
                   17036:     }
                   17037:     my $now = time;
                   17038:     my $timefilter =
                   17039:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17040:     my ($createdbefore,$createdafter);
                   17041:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17042:         $createdbefore = $now;
                   17043:         $createdafter = $now-$filter->{'createdfilter'};
                   17044:     }
                   17045:     my ($instcodefilter,$regexpok);
                   17046:     if ($numtitles) {
                   17047:         if ($env{'form.official'} eq 'on') {
                   17048:             $instcodefilter =
                   17049:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17050:             $regexpok = 1;
                   17051:         } elsif ($env{'form.official'} eq 'off') {
                   17052:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17053:             unless ($instcodefilter eq '') {
                   17054:                 $regexpok = -1;
                   17055:             }
                   17056:         }
                   17057:     } else {
                   17058:         $instcodefilter = $filter->{'instcodefilter'};
                   17059:     }
                   17060:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17061:     if ($type eq '') { $type = '.'; }
                   17062: 
                   17063:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17064:         $cloner = $cloneruname.':'.$clonerudom;
                   17065:     }
                   17066:     %courses = &Apache::lonnet::courseiddump($dom,
                   17067:                                              $filter->{'descriptfilter'},
                   17068:                                              $timefilter,
                   17069:                                              $instcodefilter,
                   17070:                                              $filter->{'combownerfilter'},
                   17071:                                              $filter->{'coursefilter'},
                   17072:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  17073:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  17074:                                              $filter->{'cloneableonly'},
                   17075:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  17076:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  17077:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17078:         my $ccrole;
                   17079:         if ($type eq 'Community') {
                   17080:             $ccrole = 'co';
                   17081:         } else {
                   17082:             $ccrole = 'cc';
                   17083:         }
                   17084:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17085:                                                      $filter->{'persondomfilter'},
                   17086:                                                      'userroles',undef,
                   17087:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17088:                                                      $dom);
                   17089:         foreach my $role (keys(%rolehash)) {
                   17090:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17091:             my $cid = $cdom.'_'.$cnum;
                   17092:             if (exists($courses{$cid})) {
                   17093:                 if (ref($courses{$cid}) eq 'HASH') {
                   17094:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17095:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  17096:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  17097:                         }
                   17098:                     } else {
                   17099:                         $courses{$cid}{roles} = [$courserole];
                   17100:                     }
                   17101:                     $showcourses{$cid} = $courses{$cid};
                   17102:                 }
                   17103:             }
                   17104:         }
                   17105:         %courses = %showcourses;
                   17106:     }
                   17107:     return %courses;
                   17108: }
                   17109: 
                   17110: =pod
                   17111: 
1.1181    raeburn  17112: =back
                   17113: 
1.1207    raeburn  17114: =head1 Routines for version requirements for current course.
                   17115: 
                   17116: =over 4
                   17117: 
                   17118: =item * &check_release_required()
                   17119: 
                   17120: Compares required LON-CAPA version with version on server, and
                   17121: if required version is newer looks for a server with the required version.
                   17122: 
                   17123: Looks first at servers in user's owen domain; if none suitable, looks at
                   17124: servers in course's domain are permitted to host sessions for user's domain.
                   17125: 
                   17126: Inputs:
                   17127: 
                   17128: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17129: 
                   17130: $courseid - Course ID of current course
                   17131: 
                   17132: $rolecode - User's current role in course (for switchserver query string).
                   17133: 
                   17134: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17135: 
                   17136: 
                   17137: Returns:
                   17138: 
                   17139: $switchserver - query string tp append to /adm/switchserver call (if 
                   17140:                 current server's LON-CAPA version is too old. 
                   17141: 
                   17142: $warning - Message is displayed if no suitable server could be found.
                   17143: 
                   17144: =cut
                   17145: 
                   17146: sub check_release_required {
                   17147:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17148:     my ($switchserver,$warning);
                   17149:     if ($required ne '') {
                   17150:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17151:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17152:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17153:             my $otherserver;
                   17154:             if (($major eq '' && $minor eq '') ||
                   17155:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17156:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17157:                 my $switchlcrev =
                   17158:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17159:                                                            $userdomserver);
                   17160:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17161:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17162:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17163:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17164:                     if ($cdom ne $env{'user.domain'}) {
                   17165:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17166:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17167:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17168:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17169:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17170:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17171:                         my $canhost =
                   17172:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17173:                                                               $coursedomserver,
                   17174:                                                               $remoterev,
                   17175:                                                               $udomdefaults{'remotesessions'},
                   17176:                                                               $defdomdefaults{'hostedsessions'});
                   17177: 
                   17178:                         if ($canhost) {
                   17179:                             $otherserver = $coursedomserver;
                   17180:                         } else {
                   17181:                             $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.");
                   17182:                         }
                   17183:                     } else {
                   17184:                         $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).");
                   17185:                     }
                   17186:                 } else {
                   17187:                     $otherserver = $userdomserver;
                   17188:                 }
                   17189:             }
                   17190:             if ($otherserver ne '') {
                   17191:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17192:             }
                   17193:         }
                   17194:     }
                   17195:     return ($switchserver,$warning);
                   17196: }
                   17197: 
                   17198: =pod
                   17199: 
                   17200: =item * &check_release_result()
                   17201: 
                   17202: Inputs:
                   17203: 
                   17204: $switchwarning - Warning message if no suitable server found to host session.
                   17205: 
                   17206: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17207:                 and current role.
                   17208: 
                   17209: Returns: HTML to display with information about requirement to switch server.
                   17210:          Either displaying warning with link to Roles/Courses screen or
                   17211:          display link to switchserver.
                   17212: 
1.1181    raeburn  17213: =cut
                   17214: 
1.1207    raeburn  17215: sub check_release_result {
                   17216:     my ($switchwarning,$switchserver) = @_;
                   17217:     my $output = &start_page('Selected course unavailable on this server').
                   17218:                  '<p class="LC_warning">';
                   17219:     if ($switchwarning) {
                   17220:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17221:         if (&show_course()) {
                   17222:             $output .= &mt('Display courses');
                   17223:         } else {
                   17224:             $output .= &mt('Display roles');
                   17225:         }
                   17226:         $output .= '</a>';
                   17227:     } elsif ($switchserver) {
                   17228:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17229:                    '<br />'.
                   17230:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17231:                    &mt('Switch Server').
                   17232:                    '</a>';
                   17233:     }
                   17234:     $output .= '</p>'.&end_page();
                   17235:     return $output;
                   17236: }
                   17237: 
                   17238: =pod
                   17239: 
                   17240: =item * &needs_coursereinit()
                   17241: 
                   17242: Determine if course contents stored for user's session needs to be
                   17243: refreshed, because content has changed since "Big Hash" last tied.
                   17244: 
                   17245: Check for change is made if time last checked is more than 10 minutes ago
                   17246: (by default).
                   17247: 
                   17248: Inputs:
                   17249: 
                   17250: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17251: 
                   17252: $interval (optional) - Time which may elapse (in s) between last check for content
                   17253:                        change in current course. (default: 600 s).  
                   17254: 
                   17255: Returns: an array; first element is:
                   17256: 
                   17257: =over 4
                   17258: 
                   17259: 'switch' - if content updates mean user's session
                   17260:            needs to be switched to a server running a newer LON-CAPA version
                   17261:  
                   17262: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17263:            on current server hosting user's session                
                   17264: 
                   17265: ''       - if no action required.
                   17266: 
                   17267: =back
                   17268: 
                   17269: If first item element is 'switch':
                   17270: 
                   17271: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   17272: 
                   17273: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17274:                               and current role. 
                   17275: 
                   17276: otherwise: no other elements returned.
                   17277: 
                   17278: =back
                   17279: 
                   17280: =cut
                   17281: 
                   17282: sub needs_coursereinit {
                   17283:     my ($loncaparev,$interval) = @_;
                   17284:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17285:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17286:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17287:     my $now = time;
                   17288:     if ($interval eq '') {
                   17289:         $interval = 600;
                   17290:     }
                   17291:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  17292:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1283    raeburn  17293:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
1.1282    raeburn  17294:         if ($blocked) {
                   17295:             return ();
                   17296:         }
1.1207    raeburn  17297:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17298:         if ($lastchange > $env{'request.course.tied'}) {
                   17299:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17300:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17301:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17302:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17303:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17304:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   17305:                     my ($switchserver,$switchwarning) =
                   17306:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17307:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17308:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17309:                         return ('switch',$switchwarning,$switchserver);
                   17310:                     }
                   17311:                 }
                   17312:             }
                   17313:             return ('update');
                   17314:         }
                   17315:     }
                   17316:     return ();
                   17317: }
1.1181    raeburn  17318: 
1.1083    raeburn  17319: sub update_content_constraints {
                   17320:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17321:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17322:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   17323:     my %checkresponsetypes;
                   17324:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  17325:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  17326:         if ($item eq 'resourcetag') {
                   17327:             if ($name eq 'responsetype') {
                   17328:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17329:             }
                   17330:         }
                   17331:     }
                   17332:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17333:     if (defined($navmap)) {
                   17334:         my %allresponses;
                   17335:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   17336:             my %responses = $res->responseTypes();
                   17337:             foreach my $key (keys(%responses)) {
                   17338:                 next unless(exists($checkresponsetypes{$key}));
                   17339:                 $allresponses{$key} += $responses{$key};
                   17340:             }
                   17341:         }
                   17342:         foreach my $key (keys(%allresponses)) {
                   17343:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17344:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17345:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17346:             }
                   17347:         }
                   17348:         undef($navmap);
                   17349:     }
                   17350:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17351:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17352:     }
                   17353:     return;
                   17354: }
                   17355: 
1.1110    raeburn  17356: sub allmaps_incourse {
                   17357:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17358:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17359:         $cid = $env{'request.course.id'};
                   17360:         $cdom = $env{'course.'.$cid.'.domain'};
                   17361:         $cnum = $env{'course.'.$cid.'.num'};
                   17362:         $chome = $env{'course.'.$cid.'.home'};
                   17363:     }
                   17364:     my %allmaps = ();
                   17365:     my $lastchange =
                   17366:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17367:     if ($lastchange > $env{'request.course.tied'}) {
                   17368:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17369:         unless ($ferr) {
                   17370:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   17371:         }
                   17372:     }
                   17373:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17374:     if (defined($navmap)) {
                   17375:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17376:             $allmaps{$res->src()} = 1;
                   17377:         }
                   17378:     }
                   17379:     return \%allmaps;
                   17380: }
                   17381: 
1.1083    raeburn  17382: sub parse_supplemental_title {
                   17383:     my ($title) = @_;
                   17384: 
                   17385:     my ($foldertitle,$renametitle);
                   17386:     if ($title =~ /&amp;&amp;&amp;/) {
                   17387:         $title = &HTML::Entites::decode($title);
                   17388:     }
                   17389:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17390:         $renametitle=$4;
                   17391:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17392:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17393:         my $name =  &plainname($uname,$udom);
                   17394:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17395:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17396:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17397:             $name.': <br />'.$foldertitle;
                   17398:     }
                   17399:     if (wantarray) {
                   17400:         return ($title,$foldertitle,$renametitle);
                   17401:     }
                   17402:     return $title;
                   17403: }
                   17404: 
1.1143    raeburn  17405: sub recurse_supplemental {
                   17406:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   17407:     if ($suppmap) {
                   17408:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17409:         if ($fatal) {
                   17410:             $errors ++;
                   17411:         } else {
                   17412:             if ($#LONCAPA::map::resources > 0) {
                   17413:                 foreach my $res (@LONCAPA::map::resources) {
                   17414:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   17415:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  17416:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   17417:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  17418:                         } else {
                   17419:                             $numfiles ++;
                   17420:                         }
                   17421:                     }
                   17422:                 }
                   17423:             }
                   17424:         }
                   17425:     }
                   17426:     return ($numfiles,$errors);
                   17427: }
                   17428: 
1.1101    raeburn  17429: sub symb_to_docspath {
1.1267    raeburn  17430:     my ($symb,$navmapref) = @_;
                   17431:     return unless ($symb && ref($navmapref));
1.1101    raeburn  17432:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17433:     if ($resurl=~/\.(sequence|page)$/) {
                   17434:         $mapurl=$resurl;
                   17435:     } elsif ($resurl eq 'adm/navmaps') {
                   17436:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17437:     }
                   17438:     my $mapresobj;
1.1267    raeburn  17439:     unless (ref($$navmapref)) {
                   17440:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17441:     }
                   17442:     if (ref($$navmapref)) {
                   17443:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  17444:     }
                   17445:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17446:     my $type=$2;
                   17447:     my $path;
                   17448:     if (ref($mapresobj)) {
                   17449:         my $pcslist = $mapresobj->map_hierarchy();
                   17450:         if ($pcslist ne '') {
                   17451:             foreach my $pc (split(/,/,$pcslist)) {
                   17452:                 next if ($pc <= 1);
1.1267    raeburn  17453:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  17454:                 if (ref($res)) {
                   17455:                     my $thisurl = $res->src();
                   17456:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17457:                     my $thistitle = $res->title();
                   17458:                     $path .= '&'.
                   17459:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  17460:                              &escape($thistitle).
1.1101    raeburn  17461:                              ':'.$res->randompick().
                   17462:                              ':'.$res->randomout().
                   17463:                              ':'.$res->encrypted().
                   17464:                              ':'.$res->randomorder().
                   17465:                              ':'.$res->is_page();
                   17466:                 }
                   17467:             }
                   17468:         }
                   17469:         $path =~ s/^\&//;
                   17470:         my $maptitle = $mapresobj->title();
                   17471:         if ($mapurl eq 'default') {
1.1129    raeburn  17472:             $maptitle = 'Main Content';
1.1101    raeburn  17473:         }
                   17474:         $path .= (($path ne '')? '&' : '').
                   17475:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17476:                  &escape($maptitle).
1.1101    raeburn  17477:                  ':'.$mapresobj->randompick().
                   17478:                  ':'.$mapresobj->randomout().
                   17479:                  ':'.$mapresobj->encrypted().
                   17480:                  ':'.$mapresobj->randomorder().
                   17481:                  ':'.$mapresobj->is_page();
                   17482:     } else {
                   17483:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17484:         my $ispage = (($type eq 'page')? 1 : '');
                   17485:         if ($mapurl eq 'default') {
1.1129    raeburn  17486:             $maptitle = 'Main Content';
1.1101    raeburn  17487:         }
                   17488:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17489:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  17490:     }
                   17491:     unless ($mapurl eq 'default') {
                   17492:         $path = 'default&'.
1.1146    raeburn  17493:                 &escape('Main Content').
1.1101    raeburn  17494:                 ':::::&'.$path;
                   17495:     }
                   17496:     return $path;
                   17497: }
                   17498: 
1.1094    raeburn  17499: sub captcha_display {
                   17500:     my ($context,$lonhost) = @_;
                   17501:     my ($output,$error);
1.1234    raeburn  17502:     my ($captcha,$pubkey,$privkey,$version) = 
                   17503:         &get_captcha_config($context,$lonhost);
1.1095    raeburn  17504:     if ($captcha eq 'original') {
1.1094    raeburn  17505:         $output = &create_captcha();
                   17506:         unless ($output) {
1.1172    raeburn  17507:             $error = 'captcha';
1.1094    raeburn  17508:         }
                   17509:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17510:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  17511:         unless ($output) {
1.1172    raeburn  17512:             $error = 'recaptcha';
1.1094    raeburn  17513:         }
                   17514:     }
1.1234    raeburn  17515:     return ($output,$error,$captcha,$version);
1.1094    raeburn  17516: }
                   17517: 
                   17518: sub captcha_response {
                   17519:     my ($context,$lonhost) = @_;
                   17520:     my ($captcha_chk,$captcha_error);
1.1234    raeburn  17521:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  17522:     if ($captcha eq 'original') {
1.1094    raeburn  17523:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17524:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17525:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  17526:     } else {
                   17527:         $captcha_chk = 1;
                   17528:     }
                   17529:     return ($captcha_chk,$captcha_error);
                   17530: }
                   17531: 
                   17532: sub get_captcha_config {
                   17533:     my ($context,$lonhost) = @_;
1.1234    raeburn  17534:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  17535:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17536:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17537:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  17538:     if ($context eq 'usercreation') {
                   17539:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17540:         if (ref($domconfig{$context}) eq 'HASH') {
                   17541:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17542:             if (ref($hashtocheck) eq 'HASH') {
                   17543:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17544:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17545:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17546:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17547:                     }
                   17548:                     if ($privkey && $pubkey) {
                   17549:                         $captcha = 'recaptcha';
1.1234    raeburn  17550:                         $version = $hashtocheck->{'recaptchaversion'};
                   17551:                         if ($version ne '2') {
                   17552:                             $version = 1;
                   17553:                         }
1.1095    raeburn  17554:                     } else {
                   17555:                         $captcha = 'original';
                   17556:                     }
                   17557:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17558:                     $captcha = 'original';
                   17559:                 }
1.1094    raeburn  17560:             }
1.1095    raeburn  17561:         } else {
                   17562:             $captcha = 'captcha';
                   17563:         }
                   17564:     } elsif ($context eq 'login') {
                   17565:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17566:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17567:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17568:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  17569:             if ($privkey && $pubkey) {
                   17570:                 $captcha = 'recaptcha';
1.1234    raeburn  17571:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17572:                 if ($version ne '2') {
                   17573:                     $version = 1; 
                   17574:                 }
1.1095    raeburn  17575:             } else {
                   17576:                 $captcha = 'original';
1.1094    raeburn  17577:             }
1.1095    raeburn  17578:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17579:             $captcha = 'original';
1.1094    raeburn  17580:         }
                   17581:     }
1.1234    raeburn  17582:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  17583: }
                   17584: 
                   17585: sub create_captcha {
                   17586:     my %captcha_params = &captcha_settings();
                   17587:     my ($output,$maxtries,$tries) = ('',10,0);
                   17588:     while ($tries < $maxtries) {
                   17589:         $tries ++;
                   17590:         my $captcha = Authen::Captcha->new (
                   17591:                                            output_folder => $captcha_params{'output_dir'},
                   17592:                                            data_folder   => $captcha_params{'db_dir'},
                   17593:                                           );
                   17594:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17595: 
                   17596:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17597:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17598:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  17599:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17600:                       '<br />'.
                   17601:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  17602:             last;
                   17603:         }
                   17604:     }
                   17605:     return $output;
                   17606: }
                   17607: 
                   17608: sub captcha_settings {
                   17609:     my %captcha_params = (
                   17610:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17611:                            www_output_dir => "/captchaspool",
                   17612:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17613:                            numchars       => '5',
                   17614:                          );
                   17615:     return %captcha_params;
                   17616: }
                   17617: 
                   17618: sub check_captcha {
                   17619:     my ($captcha_chk,$captcha_error);
                   17620:     my $code = $env{'form.code'};
                   17621:     my $md5sum = $env{'form.crypt'};
                   17622:     my %captcha_params = &captcha_settings();
                   17623:     my $captcha = Authen::Captcha->new(
                   17624:                       output_folder => $captcha_params{'output_dir'},
                   17625:                       data_folder   => $captcha_params{'db_dir'},
                   17626:                   );
1.1109    raeburn  17627:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  17628:     my %captcha_hash = (
                   17629:                         0       => 'Code not checked (file error)',
                   17630:                        -1      => 'Failed: code expired',
                   17631:                        -2      => 'Failed: invalid code (not in database)',
                   17632:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17633:     );
                   17634:     if ($captcha_chk != 1) {
                   17635:         $captcha_error = $captcha_hash{$captcha_chk}
                   17636:     }
                   17637:     return ($captcha_chk,$captcha_error);
                   17638: }
                   17639: 
                   17640: sub create_recaptcha {
1.1234    raeburn  17641:     my ($pubkey,$version) = @_;
                   17642:     if ($version >= 2) {
                   17643:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17644:     } else {
                   17645:         my $use_ssl;
                   17646:         if ($ENV{'SERVER_PORT'} == 443) {
                   17647:             $use_ssl = 1;
                   17648:         }
                   17649:         my $captcha = Captcha::reCAPTCHA->new;
                   17650:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17651:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17652:                &mt('If the text is hard to read, [_1] will replace them.',
                   17653:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17654:                '<br /><br />';
                   17655:     }
1.1094    raeburn  17656: }
                   17657: 
                   17658: sub check_recaptcha {
1.1234    raeburn  17659:     my ($privkey,$version) = @_;
1.1094    raeburn  17660:     my $captcha_chk;
1.1234    raeburn  17661:     if ($version >= 2) {
                   17662:         my %info = (
                   17663:                      secret   => $privkey, 
                   17664:                      response => $env{'form.g-recaptcha-response'},
                   17665:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17666:                    );
1.1280    raeburn  17667:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   17668:         $request->content(join('&',map {
                   17669:                          my $name = escape($_);
                   17670:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   17671:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   17672:                          : &escape($info{$_}) );
                   17673:         } keys(%info)));
                   17674:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  17675:         if ($response->is_success)  {
                   17676:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17677:             if (ref($data) eq 'HASH') {
                   17678:                 if ($data->{'success'}) {
                   17679:                     $captcha_chk = 1;
                   17680:                 }
                   17681:             }
                   17682:         }
                   17683:     } else {
                   17684:         my $captcha = Captcha::reCAPTCHA->new;
                   17685:         my $captcha_result =
                   17686:             $captcha->check_answer(
                   17687:                                     $privkey,
                   17688:                                     $ENV{'REMOTE_ADDR'},
                   17689:                                     $env{'form.recaptcha_challenge_field'},
                   17690:                                     $env{'form.recaptcha_response_field'},
                   17691:                                   );
                   17692:         if ($captcha_result->{is_valid}) {
                   17693:             $captcha_chk = 1;
                   17694:         }
1.1094    raeburn  17695:     }
                   17696:     return $captcha_chk;
                   17697: }
                   17698: 
1.1174    raeburn  17699: sub emailusername_info {
1.1244    raeburn  17700:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  17701:     my %titles = &Apache::lonlocal::texthash (
                   17702:                      lastname      => 'Last Name',
                   17703:                      firstname     => 'First Name',
                   17704:                      institution   => 'School/college/university',
                   17705:                      location      => "School's city, state/province, country",
                   17706:                      web           => "School's web address",
                   17707:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  17708:                      id            => 'Student/Employee ID',
1.1174    raeburn  17709:                  );
                   17710:     return (\@fields,\%titles);
                   17711: }
                   17712: 
1.1161    raeburn  17713: sub cleanup_html {
                   17714:     my ($incoming) = @_;
                   17715:     my $outgoing;
                   17716:     if ($incoming ne '') {
                   17717:         $outgoing = $incoming;
                   17718:         $outgoing =~ s/;/&#059;/g;
                   17719:         $outgoing =~ s/\#/&#035;/g;
                   17720:         $outgoing =~ s/\&/&#038;/g;
                   17721:         $outgoing =~ s/</&#060;/g;
                   17722:         $outgoing =~ s/>/&#062;/g;
                   17723:         $outgoing =~ s/\(/&#040/g;
                   17724:         $outgoing =~ s/\)/&#041;/g;
                   17725:         $outgoing =~ s/"/&#034;/g;
                   17726:         $outgoing =~ s/'/&#039;/g;
                   17727:         $outgoing =~ s/\$/&#036;/g;
                   17728:         $outgoing =~ s{/}{&#047;}g;
                   17729:         $outgoing =~ s/=/&#061;/g;
                   17730:         $outgoing =~ s/\\/&#092;/g
                   17731:     }
                   17732:     return $outgoing;
                   17733: }
                   17734: 
1.1190    musolffc 17735: # Checks for critical messages and returns a redirect url if one exists.
                   17736: # $interval indicates how often to check for messages.
1.1282    raeburn  17737: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 17738: sub critical_redirect {
1.1282    raeburn  17739:     my ($interval,$context) = @_;
1.1190    musolffc 17740:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  17741:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   17742:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17743:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17744:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   17745:             if ($blocked) {
                   17746:                 my $checkrole = "cm./$cdom/$cnum";
                   17747:                 if ($env{'request.course.sec'} ne '') {
                   17748:                     $checkrole .= "/$env{'request.course.sec'}";
                   17749:                 }
                   17750:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   17751:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   17752:                     return;
                   17753:                 }
                   17754:             }
                   17755:         }
1.1190    musolffc 17756:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   17757:                                         $env{'user.name'});
                   17758:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  17759:         my $redirecturl;
1.1190    musolffc 17760:         if ($what[0]) {
                   17761: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17762: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  17763: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17764:                 return (1, $url);
1.1190    musolffc 17765:             }
1.1191    raeburn  17766:         }
                   17767:     } 
                   17768:     return ();
1.1190    musolffc 17769: }
                   17770: 
1.1174    raeburn  17771: # Use:
                   17772: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17773: #
                   17774: ##################################################
                   17775: #          password associated functions         #
                   17776: ##################################################
                   17777: sub des_keys {
                   17778:     # Make a new key for DES encryption.
                   17779:     # Each key has two parts which are returned separately.
                   17780:     # Please note:  Each key must be passed through the &hex function
                   17781:     # before it is output to the web browser.  The hex versions cannot
                   17782:     # be used to decrypt.
                   17783:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17784:                 '8','9','a','b','c','d','e','f');
                   17785:     my $lkey='';
                   17786:     for (0..7) {
                   17787:         $lkey.=$hexstr[rand(15)];
                   17788:     }
                   17789:     my $ukey='';
                   17790:     for (0..7) {
                   17791:         $ukey.=$hexstr[rand(15)];
                   17792:     }
                   17793:     return ($lkey,$ukey);
                   17794: }
                   17795: 
                   17796: sub des_decrypt {
                   17797:     my ($key,$cyphertext) = @_;
                   17798:     my $keybin=pack("H16",$key);
                   17799:     my $cypher;
                   17800:     if ($Crypt::DES::VERSION>=2.03) {
                   17801:         $cypher=new Crypt::DES $keybin;
                   17802:     } else {
                   17803:         $cypher=new DES $keybin;
                   17804:     }
1.1233    raeburn  17805:     my $plaintext='';
                   17806:     my $cypherlength = length($cyphertext);
                   17807:     my $numchunks = int($cypherlength/32);
                   17808:     for (my $j=0; $j<$numchunks; $j++) {
                   17809:         my $start = $j*32;
                   17810:         my $cypherblock = substr($cyphertext,$start,32);
                   17811:         my $chunk =
                   17812:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17813:         $chunk .=
                   17814:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17815:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17816:         $plaintext .= $chunk;
                   17817:     }
1.1174    raeburn  17818:     return $plaintext;
                   17819: }
                   17820: 
1.112     bowersj2 17821: 1;
                   17822: __END__;
1.41      ng       17823: 

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