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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1304  ! raeburn     4: # $Id: loncommon.pm,v 1.1303 2017/12/18 15:49:11 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.596     albertel 4582:       $prevattempts=
                   4583: 	  &start_data_table().&start_data_table_row().
                   4584: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4585: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4586:     }
                   4587:   } else {
1.596     albertel 4588:     $prevattempts=
                   4589: 	  &start_data_table().&start_data_table_row().
                   4590: 	  '<td>'.&mt('No data.').'</td>'.
                   4591: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4592:   }
1.10      albertel 4593: }
                   4594: 
1.581     albertel 4595: sub format_previous_attempt_value {
                   4596:     my ($key,$value) = @_;
1.1011    www      4597:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4598:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4599:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4600:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4601:     } elsif ($key =~ /answerstring$/) {
                   4602:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4603:         my @answer = %answers;
                   4604:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4605:         my @anskeys = sort(keys(%answers));
                   4606:         if (@anskeys == 1) {
                   4607:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4608:             if ($answer =~ m{\0}) {
                   4609:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4610:             }
                   4611:             my $tag_internal_answer_name = 'INTERNAL';
                   4612:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4613:                 $value = $answer; 
                   4614:             } else {
                   4615:                 $value = $anskeys[0].'='.$answer;
                   4616:             }
                   4617:         } else {
                   4618:             foreach my $ans (@anskeys) {
                   4619:                 my $answer = $answers{$ans};
1.1001    raeburn  4620:                 if ($answer =~ m{\0}) {
                   4621:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4622:                 }
                   4623:                 $value .=  $ans.'='.$answer.'<br />';;
                   4624:             } 
                   4625:         }
1.581     albertel 4626:     } else {
1.1173    kruse    4627:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4628:     }
                   4629:     return $value;
                   4630: }
                   4631: 
                   4632: 
1.107     albertel 4633: sub relative_to_absolute {
                   4634:     my ($url,$output)=@_;
                   4635:     my $parser=HTML::TokeParser->new(\$output);
                   4636:     my $token;
                   4637:     my $thisdir=$url;
                   4638:     my @rlinks=();
                   4639:     while ($token=$parser->get_token) {
                   4640: 	if ($token->[0] eq 'S') {
                   4641: 	    if ($token->[1] eq 'a') {
                   4642: 		if ($token->[2]->{'href'}) {
                   4643: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4644: 		}
                   4645: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4646: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4647: 	    } elsif ($token->[1] eq 'base') {
                   4648: 		$thisdir=$token->[2]->{'href'};
                   4649: 	    }
                   4650: 	}
                   4651:     }
                   4652:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4653:     foreach my $link (@rlinks) {
1.726     raeburn  4654: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4655: 		($link=~/^\//) ||
                   4656: 		($link=~/^javascript:/i) ||
                   4657: 		($link=~/^mailto:/i) ||
                   4658: 		($link=~/^\#/)) {
                   4659: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4660: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4661: 	}
                   4662:     }
                   4663: # -------------------------------------------------- Deal with Applet codebases
                   4664:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4665:     return $output;
                   4666: }
                   4667: 
1.112     bowersj2 4668: =pod
                   4669: 
1.648     raeburn  4670: =item * &get_student_view()
1.112     bowersj2 4671: 
                   4672: show a snapshot of what student was looking at
                   4673: 
                   4674: =cut
                   4675: 
1.10      albertel 4676: sub get_student_view {
1.186     albertel 4677:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4678:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4679:   my (%form);
1.10      albertel 4680:   my @elements=('symb','courseid','domain','username');
                   4681:   foreach my $element (@elements) {
1.186     albertel 4682:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4683:   }
1.186     albertel 4684:   if (defined($moreenv)) {
                   4685:       %form=(%form,%{$moreenv});
                   4686:   }
1.236     albertel 4687:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4688:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4689:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4690:   $userview=~s/\<body[^\>]*\>//gi;
                   4691:   $userview=~s/\<\/body\>//gi;
                   4692:   $userview=~s/\<html\>//gi;
                   4693:   $userview=~s/\<\/html\>//gi;
                   4694:   $userview=~s/\<head\>//gi;
                   4695:   $userview=~s/\<\/head\>//gi;
                   4696:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4697:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4698:   if (wantarray) {
                   4699:      return ($userview,$response);
                   4700:   } else {
                   4701:      return $userview;
                   4702:   }
                   4703: }
                   4704: 
                   4705: sub get_student_view_with_retries {
                   4706:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4707: 
                   4708:     my $ok = 0;                 # True if we got a good response.
                   4709:     my $content;
                   4710:     my $response;
                   4711: 
                   4712:     # Try to get the student_view done. within the retries count:
                   4713:     
                   4714:     do {
                   4715:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4716:          $ok      = $response->is_success;
                   4717:          if (!$ok) {
                   4718:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4719:          }
                   4720:          $retries--;
                   4721:     } while (!$ok && ($retries > 0));
                   4722:     
                   4723:     if (!$ok) {
                   4724:        $content = '';          # On error return an empty content.
                   4725:     }
1.651     www      4726:     if (wantarray) {
                   4727:        return ($content, $response);
                   4728:     } else {
                   4729:        return $content;
                   4730:     }
1.11      albertel 4731: }
                   4732: 
1.112     bowersj2 4733: =pod
                   4734: 
1.648     raeburn  4735: =item * &get_student_answers() 
1.112     bowersj2 4736: 
                   4737: show a snapshot of how student was answering problem
                   4738: 
                   4739: =cut
                   4740: 
1.11      albertel 4741: sub get_student_answers {
1.100     sakharuk 4742:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4743:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4744:   my (%moreenv);
1.11      albertel 4745:   my @elements=('symb','courseid','domain','username');
                   4746:   foreach my $element (@elements) {
1.186     albertel 4747:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4748:   }
1.186     albertel 4749:   $moreenv{'grade_target'}='answer';
                   4750:   %moreenv=(%form,%moreenv);
1.497     raeburn  4751:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4752:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4753:   return $userview;
1.1       albertel 4754: }
1.116     albertel 4755: 
                   4756: =pod
                   4757: 
                   4758: =item * &submlink()
                   4759: 
1.242     albertel 4760: Inputs: $text $uname $udom $symb $target
1.116     albertel 4761: 
                   4762: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4763: 
                   4764: =cut
                   4765: 
                   4766: ###############################################
                   4767: sub submlink {
1.242     albertel 4768:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4769:     if (!($uname && $udom)) {
                   4770: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4771: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4772: 	if (!$symb) { $symb=$cursymb; }
                   4773:     }
1.254     matthew  4774:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4775:     $symb=&escape($symb);
1.960     bisitz   4776:     if ($target) { $target=" target=\"$target\""; }
                   4777:     return
                   4778:         '<a href="/adm/grades?command=submission'.
                   4779:         '&amp;symb='.$symb.
                   4780:         '&amp;student='.$uname.
                   4781:         '&amp;userdom='.$udom.'"'.
                   4782:         $target.'>'.$text.'</a>';
1.242     albertel 4783: }
                   4784: ##############################################
                   4785: 
                   4786: =pod
                   4787: 
                   4788: =item * &pgrdlink()
                   4789: 
                   4790: Inputs: $text $uname $udom $symb $target
                   4791: 
                   4792: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4793: 
                   4794: =cut
                   4795: 
                   4796: ###############################################
                   4797: sub pgrdlink {
                   4798:     my $link=&submlink(@_);
                   4799:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4800:     return $link;
                   4801: }
                   4802: ##############################################
                   4803: 
                   4804: =pod
                   4805: 
                   4806: =item * &pprmlink()
                   4807: 
                   4808: Inputs: $text $uname $udom $symb $target
                   4809: 
                   4810: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4811: student and a specific resource
1.242     albertel 4812: 
                   4813: =cut
                   4814: 
                   4815: ###############################################
                   4816: sub pprmlink {
                   4817:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4818:     if (!($uname && $udom)) {
                   4819: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4820: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4821: 	if (!$symb) { $symb=$cursymb; }
                   4822:     }
1.254     matthew  4823:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4824:     $symb=&escape($symb);
1.242     albertel 4825:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4826:     return '<a href="/adm/parmset?command=set&amp;'.
                   4827: 	'symb='.$symb.'&amp;uname='.$uname.
                   4828: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4829: }
                   4830: ##############################################
1.37      matthew  4831: 
1.112     bowersj2 4832: =pod
                   4833: 
                   4834: =back
                   4835: 
                   4836: =cut
                   4837: 
1.37      matthew  4838: ###############################################
1.51      www      4839: 
                   4840: 
                   4841: sub timehash {
1.687     raeburn  4842:     my ($thistime) = @_;
                   4843:     my $timezone = &Apache::lonlocal::gettimezone();
                   4844:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4845:                      ->set_time_zone($timezone);
                   4846:     my $wday = $dt->day_of_week();
                   4847:     if ($wday == 7) { $wday = 0; }
                   4848:     return ( 'second' => $dt->second(),
                   4849:              'minute' => $dt->minute(),
                   4850:              'hour'   => $dt->hour(),
                   4851:              'day'     => $dt->day_of_month(),
                   4852:              'month'   => $dt->month(),
                   4853:              'year'    => $dt->year(),
                   4854:              'weekday' => $wday,
                   4855:              'dayyear' => $dt->day_of_year(),
                   4856:              'dlsav'   => $dt->is_dst() );
1.51      www      4857: }
                   4858: 
1.370     www      4859: sub utc_string {
                   4860:     my ($date)=@_;
1.371     www      4861:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4862: }
                   4863: 
1.51      www      4864: sub maketime {
                   4865:     my %th=@_;
1.687     raeburn  4866:     my ($epoch_time,$timezone,$dt);
                   4867:     $timezone = &Apache::lonlocal::gettimezone();
                   4868:     eval {
                   4869:         $dt = DateTime->new( year   => $th{'year'},
                   4870:                              month  => $th{'month'},
                   4871:                              day    => $th{'day'},
                   4872:                              hour   => $th{'hour'},
                   4873:                              minute => $th{'minute'},
                   4874:                              second => $th{'second'},
                   4875:                              time_zone => $timezone,
                   4876:                          );
                   4877:     };
                   4878:     if (!$@) {
                   4879:         $epoch_time = $dt->epoch;
                   4880:         if ($epoch_time) {
                   4881:             return $epoch_time;
                   4882:         }
                   4883:     }
1.51      www      4884:     return POSIX::mktime(
                   4885:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4886:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4887: }
                   4888: 
                   4889: #########################################
1.51      www      4890: 
                   4891: sub findallcourses {
1.482     raeburn  4892:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4893:     my %roles;
                   4894:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4895:     my %courses;
1.51      www      4896:     my $now=time;
1.482     raeburn  4897:     if (!defined($uname)) {
                   4898:         $uname = $env{'user.name'};
                   4899:     }
                   4900:     if (!defined($udom)) {
                   4901:         $udom = $env{'user.domain'};
                   4902:     }
                   4903:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4904:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4905:         if (!%roles) {
                   4906:             %roles = (
                   4907:                        cc => 1,
1.907     raeburn  4908:                        co => 1,
1.482     raeburn  4909:                        in => 1,
                   4910:                        ep => 1,
                   4911:                        ta => 1,
                   4912:                        cr => 1,
                   4913:                        st => 1,
                   4914:              );
                   4915:         }
                   4916:         foreach my $entry (keys(%roleshash)) {
                   4917:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4918:             if ($trole =~ /^cr/) { 
                   4919:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4920:             } else {
                   4921:                 next if (!exists($roles{$trole}));
                   4922:             }
                   4923:             if ($tend) {
                   4924:                 next if ($tend < $now);
                   4925:             }
                   4926:             if ($tstart) {
                   4927:                 next if ($tstart > $now);
                   4928:             }
1.1058    raeburn  4929:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4930:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4931:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4932:             if ($secpart eq '') {
                   4933:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4934:                 $sec = 'none';
1.1058    raeburn  4935:                 $value .= $cnum.'/';
1.482     raeburn  4936:             } else {
                   4937:                 $cnum = $cnumpart;
                   4938:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4939:                 $value .= $cnum.'/'.$sec;
                   4940:             }
                   4941:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4942:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4943:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4944:                 }
                   4945:             } else {
                   4946:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4947:             }
1.482     raeburn  4948:         }
                   4949:     } else {
                   4950:         foreach my $key (keys(%env)) {
1.483     albertel 4951: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4952:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4953: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4954: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4955: 	        next if (%roles && !exists($roles{$role}));
                   4956: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4957:                 my $active=1;
                   4958:                 if ($starttime) {
                   4959: 		    if ($now<$starttime) { $active=0; }
                   4960:                 }
                   4961:                 if ($endtime) {
                   4962:                     if ($now>$endtime) { $active=0; }
                   4963:                 }
                   4964:                 if ($active) {
1.1058    raeburn  4965:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4966:                     if ($sec eq '') {
                   4967:                         $sec = 'none';
1.1058    raeburn  4968:                     } else {
                   4969:                         $value .= $sec;
                   4970:                     }
                   4971:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4972:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4973:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4974:                         }
                   4975:                     } else {
                   4976:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4977:                     }
1.474     raeburn  4978:                 }
                   4979:             }
1.51      www      4980:         }
                   4981:     }
1.474     raeburn  4982:     return %courses;
1.51      www      4983: }
1.37      matthew  4984: 
1.54      www      4985: ###############################################
1.474     raeburn  4986: 
                   4987: sub blockcheck {
1.1189    raeburn  4988:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4989: 
1.1189    raeburn  4990:     if (defined($udom) && defined($uname)) {
                   4991:         # If uname and udom are for a course, check for blocks in the course.
                   4992:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4993:             my ($startblock,$endblock,$triggerblock) =
                   4994:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4995:             return ($startblock,$endblock,$triggerblock);
                   4996:         }
                   4997:     } else {
1.490     raeburn  4998:         $udom = $env{'user.domain'};
                   4999:         $uname = $env{'user.name'};
                   5000:     }
                   5001: 
1.502     raeburn  5002:     my $startblock = 0;
                   5003:     my $endblock = 0;
1.1062    raeburn  5004:     my $triggerblock = '';
1.482     raeburn  5005:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  5006: 
1.490     raeburn  5007:     # If uname is for a user, and activity is course-specific, i.e.,
                   5008:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5009: 
1.490     raeburn  5010:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5011:          $activity eq 'groups' || $activity eq 'printout' ||
                   5012:          $activity eq 'reinit' || $activity eq 'alert') &&
1.1189    raeburn  5013:         ($env{'request.course.id'})) {
1.490     raeburn  5014:         foreach my $key (keys(%live_courses)) {
                   5015:             if ($key ne $env{'request.course.id'}) {
                   5016:                 delete($live_courses{$key});
                   5017:             }
                   5018:         }
                   5019:     }
                   5020: 
                   5021:     my $otheruser = 0;
                   5022:     my %own_courses;
                   5023:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5024:         # Resource belongs to user other than current user.
                   5025:         $otheruser = 1;
                   5026:         # Gather courses for current user
                   5027:         %own_courses = 
                   5028:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5029:     }
                   5030: 
                   5031:     # Gather active course roles - course coordinator, instructor, 
                   5032:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5033: 
                   5034:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5035:         my ($cdom,$cnum);
                   5036:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5037:             $cdom = $env{'course.'.$course.'.domain'};
                   5038:             $cnum = $env{'course.'.$course.'.num'};
                   5039:         } else {
1.490     raeburn  5040:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5041:         }
                   5042:         my $no_ownblock = 0;
                   5043:         my $no_userblock = 0;
1.533     raeburn  5044:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5045:             # Check if current user has 'evb' priv for this
                   5046:             if (defined($own_courses{$course})) {
                   5047:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5048:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5049:                     if ($sec ne 'none') {
                   5050:                         $checkrole .= '/'.$sec;
                   5051:                     }
                   5052:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5053:                         $no_ownblock = 1;
                   5054:                         last;
                   5055:                     }
                   5056:                 }
                   5057:             }
                   5058:             # if they have 'evb' priv and are currently not playing student
                   5059:             next if (($no_ownblock) &&
                   5060:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5061:         }
1.474     raeburn  5062:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5063:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5064:             if ($sec ne 'none') {
1.482     raeburn  5065:                 $checkrole .= '/'.$sec;
1.474     raeburn  5066:             }
1.490     raeburn  5067:             if ($otheruser) {
                   5068:                 # Resource belongs to user other than current user.
                   5069:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5070:                 my (%allroles,%userroles);
                   5071:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5072:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5073:                         my ($trole,$tdom,$tnum,$tsec);
                   5074:                         if ($entry =~ /^cr/) {
                   5075:                             ($trole,$tdom,$tnum,$tsec) = 
                   5076:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5077:                         } else {
                   5078:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5079:                         }
                   5080:                         my ($spec,$area,$trest);
                   5081:                         $area = '/'.$tdom.'/'.$tnum;
                   5082:                         $trest = $tnum;
                   5083:                         if ($tsec ne '') {
                   5084:                             $area .= '/'.$tsec;
                   5085:                             $trest .= '/'.$tsec;
                   5086:                         }
                   5087:                         $spec = $trole.'.'.$area;
                   5088:                         if ($trole =~ /^cr/) {
                   5089:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5090:                                                               $tdom,$spec,$trest,$area);
                   5091:                         } else {
                   5092:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5093:                                                                 $tdom,$spec,$trest,$area);
                   5094:                         }
                   5095:                     }
1.1276    raeburn  5096:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5097:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5098:                         if ($1) {
                   5099:                             $no_userblock = 1;
                   5100:                             last;
                   5101:                         }
1.486     raeburn  5102:                     }
                   5103:                 }
1.490     raeburn  5104:             } else {
                   5105:                 # Resource belongs to current user
                   5106:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5107:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5108:                     $no_ownblock = 1;
                   5109:                     last;
                   5110:                 }
1.474     raeburn  5111:             }
                   5112:         }
                   5113:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5114:         next if (($no_ownblock) &&
1.491     albertel 5115:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5116:         next if ($no_userblock);
1.474     raeburn  5117: 
1.1303    raeburn  5118:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5119:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5120: 
1.1062    raeburn  5121:         my ($start,$end,$trigger) = 
                   5122:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  5123:         if (($start != 0) && 
                   5124:             (($startblock == 0) || ($startblock > $start))) {
                   5125:             $startblock = $start;
1.1062    raeburn  5126:             if ($trigger ne '') {
                   5127:                 $triggerblock = $trigger;
                   5128:             }
1.502     raeburn  5129:         }
                   5130:         if (($end != 0)  &&
                   5131:             (($endblock == 0) || ($endblock < $end))) {
                   5132:             $endblock = $end;
1.1062    raeburn  5133:             if ($trigger ne '') {
                   5134:                 $triggerblock = $trigger;
                   5135:             }
1.502     raeburn  5136:         }
1.490     raeburn  5137:     }
1.1062    raeburn  5138:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5139: }
                   5140: 
                   5141: sub get_blocks {
1.1062    raeburn  5142:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  5143:     my $startblock = 0;
                   5144:     my $endblock = 0;
1.1062    raeburn  5145:     my $triggerblock = '';
1.490     raeburn  5146:     my $course = $cdom.'_'.$cnum;
                   5147:     $setters->{$course} = {};
                   5148:     $setters->{$course}{'staff'} = [];
                   5149:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5150:     $setters->{$course}{'triggers'} = [];
                   5151:     my (@blockers,%triggered);
                   5152:     my $now = time;
                   5153:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5154:     if ($activity eq 'docs') {
                   5155:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   5156:         foreach my $block (@blockers) {
                   5157:             if ($block =~ /^firstaccess____(.+)$/) {
                   5158:                 my $item = $1;
                   5159:                 my $type = 'map';
                   5160:                 my $timersymb = $item;
                   5161:                 if ($item eq 'course') {
                   5162:                     $type = 'course';
                   5163:                 } elsif ($item =~ /___\d+___/) {
                   5164:                     $type = 'resource';
                   5165:                 } else {
                   5166:                     $timersymb = &Apache::lonnet::symbread($item);
                   5167:                 }
                   5168:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5169:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5170:                 $triggered{$block} = {
                   5171:                                        start => $start,
                   5172:                                        end   => $end,
                   5173:                                        type  => $type,
                   5174:                                      };
                   5175:             }
                   5176:         }
                   5177:     } else {
                   5178:         foreach my $block (keys(%commblocks)) {
                   5179:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5180:                 my ($start,$end) = ($1,$2);
                   5181:                 if ($start <= time && $end >= time) {
                   5182:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5183:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5184:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5185:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5186:                                     push(@blockers,$block);
                   5187:                                 }
                   5188:                             }
                   5189:                         }
                   5190:                     }
                   5191:                 }
                   5192:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5193:                 my $item = $1;
                   5194:                 my $timersymb = $item; 
                   5195:                 my $type = 'map';
                   5196:                 if ($item eq 'course') {
                   5197:                     $type = 'course';
                   5198:                 } elsif ($item =~ /___\d+___/) {
                   5199:                     $type = 'resource';
                   5200:                 } else {
                   5201:                     $timersymb = &Apache::lonnet::symbread($item);
                   5202:                 }
                   5203:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5204:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5205:                 if ($start && $end) {
                   5206:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5207:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5208:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5209:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5210:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5211:                                         push(@blockers,$block);
                   5212:                                         $triggered{$block} = {
                   5213:                                                                start => $start,
                   5214:                                                                end   => $end,
                   5215:                                                                type  => $type,
                   5216:                                                              };
                   5217:                                     }
                   5218:                                 }
                   5219:                             }
1.1062    raeburn  5220:                         }
                   5221:                     }
1.490     raeburn  5222:                 }
1.1062    raeburn  5223:             }
                   5224:         }
                   5225:     }
                   5226:     foreach my $blocker (@blockers) {
                   5227:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5228:             &parse_block_record($commblocks{$blocker});
                   5229:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5230:         my ($start,$end,$triggertype);
                   5231:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5232:             ($start,$end) = ($1,$2);
                   5233:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5234:             $start = $triggered{$blocker}{'start'};
                   5235:             $end = $triggered{$blocker}{'end'};
                   5236:             $triggertype = $triggered{$blocker}{'type'};
                   5237:         }
                   5238:         if ($start) {
                   5239:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5240:             if ($triggertype) {
                   5241:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5242:             } else {
                   5243:                 push(@{$$setters{$course}{'triggers'}},0);
                   5244:             }
                   5245:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5246:                 $startblock = $start;
                   5247:                 if ($triggertype) {
                   5248:                     $triggerblock = $blocker;
1.474     raeburn  5249:                 }
                   5250:             }
1.1062    raeburn  5251:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5252:                $endblock = $end;
                   5253:                if ($triggertype) {
                   5254:                    $triggerblock = $blocker;
                   5255:                }
                   5256:             }
1.474     raeburn  5257:         }
                   5258:     }
1.1062    raeburn  5259:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5260: }
                   5261: 
                   5262: sub parse_block_record {
                   5263:     my ($record) = @_;
                   5264:     my ($setuname,$setudom,$title,$blocks);
                   5265:     if (ref($record) eq 'HASH') {
                   5266:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5267:         $title = &unescape($record->{'event'});
                   5268:         $blocks = $record->{'blocks'};
                   5269:     } else {
                   5270:         my @data = split(/:/,$record,3);
                   5271:         if (scalar(@data) eq 2) {
                   5272:             $title = $data[1];
                   5273:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5274:         } else {
                   5275:             ($setuname,$setudom,$title) = @data;
                   5276:         }
                   5277:         $blocks = { 'com' => 'on' };
                   5278:     }
                   5279:     return ($setuname,$setudom,$title,$blocks);
                   5280: }
                   5281: 
1.854     kalberla 5282: sub blocking_status {
1.1189    raeburn  5283:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  5284:     my %setters;
1.890     droeschl 5285: 
1.1061    raeburn  5286: # check for active blocking
1.1062    raeburn  5287:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  5288:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  5289:     my $blocked = 0;
                   5290:     if ($startblock && $endblock) {
                   5291:         $blocked = 1;
                   5292:     }
1.890     droeschl 5293: 
1.1061    raeburn  5294: # caller just wants to know whether a block is active
                   5295:     if (!wantarray) { return $blocked; }
                   5296: 
                   5297: # build a link to a popup window containing the details
                   5298:     my $querystring  = "?activity=$activity";
                   5299: # $uname and $udom decide whose portfolio the user is trying to look at
1.1232    raeburn  5300:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5301:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5302:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5303:     } elsif ($activity eq 'docs') {
                   5304:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   5305:     }
1.1061    raeburn  5306: 
                   5307:     my $output .= <<'END_MYBLOCK';
                   5308: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5309:     var options = "width=" + w + ",height=" + h + ",";
                   5310:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5311:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5312:     var newWin = window.open(url, wdwName, options);
                   5313:     newWin.focus();
                   5314: }
1.890     droeschl 5315: END_MYBLOCK
1.854     kalberla 5316: 
1.1061    raeburn  5317:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5318:   
1.1061    raeburn  5319:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5320:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5321:     my $class = 'LC_comblock';
1.1062    raeburn  5322:     if ($activity eq 'docs') {
                   5323:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5324:         $class = '';
1.1063    raeburn  5325:     } elsif ($activity eq 'printout') {
                   5326:         $text = &mt('Printing Blocked');
1.1232    raeburn  5327:     } elsif ($activity eq 'passwd') {
                   5328:         $text = &mt('Password Changing Blocked');
1.1282    raeburn  5329:     } elsif ($activity eq 'alert') {
                   5330:         $text = &mt('Checking Critical Messages Blocked');
                   5331:     } elsif ($activity eq 'reinit') {
                   5332:         $text = &mt('Checking Course Update Blocked');
1.1062    raeburn  5333:     }
1.1061    raeburn  5334:     $output .= <<"END_BLOCK";
1.1217    raeburn  5335: <div class='$class'>
1.869     kalberla 5336:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5337:   title='$text'>
                   5338:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5339:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5340:   title='$text'>$text</a>
1.867     kalberla 5341: </div>
                   5342: 
                   5343: END_BLOCK
1.474     raeburn  5344: 
1.1061    raeburn  5345:     return ($blocked, $output);
1.854     kalberla 5346: }
1.490     raeburn  5347: 
1.60      matthew  5348: ###############################################
                   5349: 
1.682     raeburn  5350: sub check_ip_acc {
1.1201    raeburn  5351:     my ($acc,$clientip)=@_;
1.682     raeburn  5352:     &Apache::lonxml::debug("acc is $acc");
                   5353:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5354:         return 1;
                   5355:     }
1.1219    raeburn  5356:     my $allowed;
1.1252    raeburn  5357:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  5358: 
                   5359:     my $name;
1.1219    raeburn  5360:     my %access = (
                   5361:                      allowfrom => 1,
                   5362:                      denyfrom  => 0,
                   5363:                  );
                   5364:     my @allows;
                   5365:     my @denies;
                   5366:     foreach my $item (split(',',$acc)) {
                   5367:         $item =~ s/^\s*//;
                   5368:         $item =~ s/\s*$//;
                   5369:         my $pattern;
                   5370:         if ($item =~ /^\!(.+)$/) {
                   5371:             push(@denies,$1);
                   5372:         } else {
                   5373:             push(@allows,$item);
                   5374:         }
                   5375:    }
                   5376:    my $numdenies = scalar(@denies);
                   5377:    my $numallows = scalar(@allows);
                   5378:    my $count = 0;
                   5379:    foreach my $pattern (@denies,@allows) {
                   5380:         $count ++; 
                   5381:         my $acctype = 'allowfrom';
                   5382:         if ($count <= $numdenies) {
                   5383:             $acctype = 'denyfrom';
                   5384:         }
1.682     raeburn  5385:         if ($pattern =~ /\*$/) {
                   5386:             #35.8.*
                   5387:             $pattern=~s/\*//;
1.1219    raeburn  5388:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5389:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5390:             #35.8.3.[34-56]
                   5391:             my $low=$2;
                   5392:             my $high=$3;
                   5393:             $pattern=$1;
                   5394:             if ($ip =~ /^\Q$pattern\E/) {
                   5395:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5396:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5397:             }
                   5398:         } elsif ($pattern =~ /^\*/) {
                   5399:             #*.msu.edu
                   5400:             $pattern=~s/\*//;
                   5401:             if (!defined($name)) {
                   5402:                 use Socket;
                   5403:                 my $netaddr=inet_aton($ip);
                   5404:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5405:             }
1.1219    raeburn  5406:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5407:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5408:             #127.0.0.1
1.1219    raeburn  5409:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5410:         } else {
                   5411:             #some.name.com
                   5412:             if (!defined($name)) {
                   5413:                 use Socket;
                   5414:                 my $netaddr=inet_aton($ip);
                   5415:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5416:             }
1.1219    raeburn  5417:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5418:         }
                   5419:         if ($allowed =~ /^(0|1)$/) { last; }
                   5420:     }
                   5421:     if ($allowed eq '') {
                   5422:         if ($numdenies && !$numallows) {
                   5423:             $allowed = 1;
                   5424:         } else {
                   5425:             $allowed = 0;
1.682     raeburn  5426:         }
                   5427:     }
                   5428:     return $allowed;
                   5429: }
                   5430: 
                   5431: ###############################################
                   5432: 
1.60      matthew  5433: =pod
                   5434: 
1.112     bowersj2 5435: =head1 Domain Template Functions
                   5436: 
                   5437: =over 4
                   5438: 
                   5439: =item * &determinedomain()
1.60      matthew  5440: 
                   5441: Inputs: $domain (usually will be undef)
                   5442: 
1.63      www      5443: Returns: Determines which domain should be used for designs
1.60      matthew  5444: 
                   5445: =cut
1.54      www      5446: 
1.60      matthew  5447: ###############################################
1.63      www      5448: sub determinedomain {
                   5449:     my $domain=shift;
1.531     albertel 5450:     if (! $domain) {
1.60      matthew  5451:         # Determine domain if we have not been given one
1.893     raeburn  5452:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5453:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5454:         if ($env{'request.role.domain'}) { 
                   5455:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5456:         }
                   5457:     }
1.63      www      5458:     return $domain;
                   5459: }
                   5460: ###############################################
1.517     raeburn  5461: 
1.518     albertel 5462: sub devalidate_domconfig_cache {
                   5463:     my ($udom)=@_;
                   5464:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5465: }
                   5466: 
                   5467: # ---------------------- Get domain configuration for a domain
                   5468: sub get_domainconf {
                   5469:     my ($udom) = @_;
                   5470:     my $cachetime=1800;
                   5471:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5472:     if (defined($cached)) { return %{$result}; }
                   5473: 
                   5474:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5475: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5476:     my (%designhash,%legacy);
1.518     albertel 5477:     if (keys(%domconfig) > 0) {
                   5478:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5479:             if (keys(%{$domconfig{'login'}})) {
                   5480:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5481:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5482:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5483:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5484:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5485:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5486:                                         if ($key eq 'loginvia') {
                   5487:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5488:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5489:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5490:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5491: 
                   5492:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5493:                                                 } else {
                   5494:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5495:                                                 }
1.948     raeburn  5496:                                             }
1.1208    raeburn  5497:                                         } elsif ($key eq 'headtag') {
                   5498:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5499:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5500:                                             }
1.946     raeburn  5501:                                         }
1.1208    raeburn  5502:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5503:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5504:                                         }
1.946     raeburn  5505:                                     }
                   5506:                                 }
                   5507:                             }
                   5508:                         } else {
                   5509:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5510:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5511:                                     $domconfig{'login'}{$key}{$img};
                   5512:                             }
1.699     raeburn  5513:                         }
                   5514:                     } else {
                   5515:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5516:                     }
1.632     raeburn  5517:                 }
                   5518:             } else {
                   5519:                 $legacy{'login'} = 1;
1.518     albertel 5520:             }
1.632     raeburn  5521:         } else {
                   5522:             $legacy{'login'} = 1;
1.518     albertel 5523:         }
                   5524:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5525:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5526:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5527:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5528:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5529:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5530:                         }
1.518     albertel 5531:                     }
                   5532:                 }
1.632     raeburn  5533:             } else {
                   5534:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5535:             }
1.632     raeburn  5536:         } else {
                   5537:             $legacy{'rolecolors'} = 1;
1.518     albertel 5538:         }
1.948     raeburn  5539:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5540:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5541:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5542:             }
                   5543:         }
1.632     raeburn  5544:         if (keys(%legacy) > 0) {
                   5545:             my %legacyhash = &get_legacy_domconf($udom);
                   5546:             foreach my $item (keys(%legacyhash)) {
                   5547:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5548:                     if ($legacy{'login'}) { 
                   5549:                         $designhash{$item} = $legacyhash{$item};
                   5550:                     }
                   5551:                 } else {
                   5552:                     if ($legacy{'rolecolors'}) {
                   5553:                         $designhash{$item} = $legacyhash{$item};
                   5554:                     }
1.518     albertel 5555:                 }
                   5556:             }
                   5557:         }
1.632     raeburn  5558:     } else {
                   5559:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5560:     }
                   5561:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5562: 				  $cachetime);
                   5563:     return %designhash;
                   5564: }
                   5565: 
1.632     raeburn  5566: sub get_legacy_domconf {
                   5567:     my ($udom) = @_;
                   5568:     my %legacyhash;
                   5569:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5570:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5571:     if (-e $designfile) {
                   5572:         if ( open (my $fh,"<$designfile") ) {
                   5573:             while (my $line = <$fh>) {
                   5574:                 next if ($line =~ /^\#/);
                   5575:                 chomp($line);
                   5576:                 my ($key,$val)=(split(/\=/,$line));
                   5577:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5578:             }
                   5579:             close($fh);
                   5580:         }
                   5581:     }
1.1026    raeburn  5582:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5583:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5584:     }
                   5585:     return %legacyhash;
                   5586: }
                   5587: 
1.63      www      5588: =pod
                   5589: 
1.112     bowersj2 5590: =item * &domainlogo()
1.63      www      5591: 
                   5592: Inputs: $domain (usually will be undef)
                   5593: 
                   5594: Returns: A link to a domain logo, if the domain logo exists.
                   5595: If the domain logo does not exist, a description of the domain.
                   5596: 
                   5597: =cut
1.112     bowersj2 5598: 
1.63      www      5599: ###############################################
                   5600: sub domainlogo {
1.517     raeburn  5601:     my $domain = &determinedomain(shift);
1.518     albertel 5602:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5603:     # See if there is a logo
                   5604:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5605:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5606:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5607: 	    if ($imgsrc =~ m{^/res/}) {
                   5608: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5609: 		&Apache::lonnet::repcopy($local_name);
                   5610: 	    }
                   5611: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5612:         } 
                   5613:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5614:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5615:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5616:     } else {
1.60      matthew  5617:         return '';
1.59      www      5618:     }
                   5619: }
1.63      www      5620: ##############################################
                   5621: 
                   5622: =pod
                   5623: 
1.112     bowersj2 5624: =item * &designparm()
1.63      www      5625: 
                   5626: Inputs: $which parameter; $domain (usually will be undef)
                   5627: 
                   5628: Returns: value of designparamter $which
                   5629: 
                   5630: =cut
1.112     bowersj2 5631: 
1.397     albertel 5632: 
1.400     albertel 5633: ##############################################
1.397     albertel 5634: sub designparm {
                   5635:     my ($which,$domain)=@_;
                   5636:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5637:         return $env{'environment.color.'.$which};
1.96      www      5638:     }
1.63      www      5639:     $domain=&determinedomain($domain);
1.1016    raeburn  5640:     my %domdesign;
                   5641:     unless ($domain eq 'public') {
                   5642:         %domdesign = &get_domainconf($domain);
                   5643:     }
1.520     raeburn  5644:     my $output;
1.517     raeburn  5645:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5646:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5647:     } else {
1.520     raeburn  5648:         $output = $defaultdesign{$which};
                   5649:     }
                   5650:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5651:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5652:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5653:             if ($output =~ m{^/res/}) {
                   5654:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5655:                 &Apache::lonnet::repcopy($local_name);
                   5656:             }
1.520     raeburn  5657:             $output = &lonhttpdurl($output);
                   5658:         }
1.63      www      5659:     }
1.520     raeburn  5660:     return $output;
1.63      www      5661: }
1.59      www      5662: 
1.822     bisitz   5663: ##############################################
                   5664: =pod
                   5665: 
1.832     bisitz   5666: =item * &authorspace()
                   5667: 
1.1028    raeburn  5668: Inputs: $url (usually will be undef).
1.832     bisitz   5669: 
1.1132    raeburn  5670: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5671:          directory being viewed (or for which action is being taken). 
                   5672:          If $url is provided, and begins /priv/<domain>/<uname>
                   5673:          the path will be that portion of the $context argument.
                   5674:          Otherwise the path will be for the author space of the current
                   5675:          user when the current role is author, or for that of the 
                   5676:          co-author/assistant co-author space when the current role 
                   5677:          is co-author or assistant co-author.
1.832     bisitz   5678: 
                   5679: =cut
                   5680: 
                   5681: sub authorspace {
1.1028    raeburn  5682:     my ($url) = @_;
                   5683:     if ($url ne '') {
                   5684:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5685:            return $1;
                   5686:         }
                   5687:     }
1.832     bisitz   5688:     my $caname = '';
1.1024    www      5689:     my $cadom = '';
1.1028    raeburn  5690:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5691:         ($cadom,$caname) =
1.832     bisitz   5692:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5693:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5694:         $caname = $env{'user.name'};
1.1024    www      5695:         $cadom = $env{'user.domain'};
1.832     bisitz   5696:     }
1.1028    raeburn  5697:     if (($caname ne '') && ($cadom ne '')) {
                   5698:         return "/priv/$cadom/$caname/";
                   5699:     }
                   5700:     return;
1.832     bisitz   5701: }
                   5702: 
                   5703: ##############################################
                   5704: =pod
                   5705: 
1.822     bisitz   5706: =item * &head_subbox()
                   5707: 
                   5708: Inputs: $content (contains HTML code with page functions, etc.)
                   5709: 
                   5710: Returns: HTML div with $content
                   5711:          To be included in page header
                   5712: 
                   5713: =cut
                   5714: 
                   5715: sub head_subbox {
                   5716:     my ($content)=@_;
                   5717:     my $output =
1.993     raeburn  5718:         '<div class="LC_head_subbox">'
1.822     bisitz   5719:        .$content
                   5720:        .'</div>'
                   5721: }
                   5722: 
                   5723: ##############################################
                   5724: =pod
                   5725: 
                   5726: =item * &CSTR_pageheader()
                   5727: 
1.1026    raeburn  5728: Input: (optional) filename from which breadcrumb trail is built.
                   5729:        In most cases no input as needed, as $env{'request.filename'}
                   5730:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5731: 
                   5732: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5733:          To be included on Authoring Space pages
1.822     bisitz   5734: 
                   5735: =cut
                   5736: 
                   5737: sub CSTR_pageheader {
1.1026    raeburn  5738:     my ($trailfile) = @_;
                   5739:     if ($trailfile eq '') {
                   5740:         $trailfile = $env{'request.filename'};
                   5741:     }
                   5742: 
                   5743: # this is for resources; directories have customtitle, and crumbs
                   5744: # and select recent are created in lonpubdir.pm
                   5745: 
                   5746:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5747:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5748:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5749:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5750:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5751: 
                   5752:     my $parentpath = '';
                   5753:     my $lastitem = '';
                   5754:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5755:         $parentpath = $1;
                   5756:         $lastitem = $2;
                   5757:     } else {
                   5758:         $lastitem = $thisdisfn;
                   5759:     }
1.921     bisitz   5760: 
1.1246    raeburn  5761:     my ($crsauthor,$title);
                   5762:     if (($env{'request.course.id'}) &&
                   5763:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  5764:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  5765:         $crsauthor = 1;
                   5766:         $title = &mt('Course Authoring Space');
                   5767:     } else {
                   5768:         $title = &mt('Authoring Space');
                   5769:     }
                   5770: 
1.921     bisitz   5771:     my $output =
1.822     bisitz   5772:          '<div>'
                   5773:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  5774:         .'<b>'.$title.'</b> '
1.822     bisitz   5775:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5776:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5777:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5778: 
                   5779:     if ($lastitem) {
                   5780:         $output .=
                   5781:              '<span class="LC_filename">'
                   5782:             .$lastitem
                   5783:             .'</span>';
                   5784:     }
1.1245    raeburn  5785: 
1.1246    raeburn  5786:     if ($crsauthor) {
                   5787:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   5788:     } else {
                   5789:         $output .=
                   5790:              '<br />'
                   5791:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5792:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5793:             .'</form>'
                   5794:             .&Apache::lonmenu::constspaceform();
                   5795:     }
                   5796:     $output .= '</div>';
1.921     bisitz   5797: 
                   5798:     return $output;
1.822     bisitz   5799: }
                   5800: 
1.60      matthew  5801: ###############################################
                   5802: ###############################################
                   5803: 
                   5804: =pod
                   5805: 
1.112     bowersj2 5806: =back
                   5807: 
1.549     albertel 5808: =head1 HTML Helpers
1.112     bowersj2 5809: 
                   5810: =over 4
                   5811: 
                   5812: =item * &bodytag()
1.60      matthew  5813: 
                   5814: Returns a uniform header for LON-CAPA web pages.
                   5815: 
                   5816: Inputs: 
                   5817: 
1.112     bowersj2 5818: =over 4
                   5819: 
                   5820: =item * $title, A title to be displayed on the page.
                   5821: 
                   5822: =item * $function, the current role (can be undef).
                   5823: 
                   5824: =item * $addentries, extra parameters for the <body> tag.
                   5825: 
                   5826: =item * $bodyonly, if defined, only return the <body> tag.
                   5827: 
                   5828: =item * $domain, if defined, force a given domain.
                   5829: 
                   5830: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5831:             text interface only)
1.60      matthew  5832: 
1.814     bisitz   5833: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5834:                      navigational links
1.317     albertel 5835: 
1.338     albertel 5836: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5837: 
1.460     albertel 5838: =item * $args, optional argument valid values are
                   5839:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  5840:             use_absolute     -> for external resource or syllabus, this will
                   5841:                                 contain https://<hostname> if server uses
                   5842:                                 https (as per hosts.tab), but request is for http
                   5843:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5844: 
1.1096    raeburn  5845: =item * $advtoolsref, optional argument, ref to an array containing
                   5846:             inlineremote items to be added in "Functions" menu below
                   5847:             breadcrumbs.
                   5848: 
1.112     bowersj2 5849: =back
                   5850: 
1.60      matthew  5851: Returns: A uniform header for LON-CAPA web pages.  
                   5852: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5853: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5854: other decorations will be returned.
                   5855: 
                   5856: =cut
                   5857: 
1.54      www      5858: sub bodytag {
1.831     bisitz   5859:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5860:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5861: 
1.954     raeburn  5862:     my $public;
                   5863:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5864:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5865:         $public = 1;
                   5866:     }
1.460     albertel 5867:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5868:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  5869:     my $hostname = $args->{'hostname'};
1.339     albertel 5870: 
1.183     matthew  5871:     $function = &get_users_function() if (!$function);
1.339     albertel 5872:     my $img =    &designparm($function.'.img',$domain);
                   5873:     my $font =   &designparm($function.'.font',$domain);
                   5874:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5875: 
1.803     bisitz   5876:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5877: 		   'bgcolor' => $pgbg,
1.339     albertel 5878: 		   'text'    => $font,
                   5879:                    'alink'   => &designparm($function.'.alink',$domain),
                   5880: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5881: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5882:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5883: 
1.63      www      5884:  # role and realm
1.1178    raeburn  5885:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5886:     if ($realm) {
                   5887:         $realm = '/'.$realm;
                   5888:     }
1.378     raeburn  5889:     if ($role  eq 'ca') {
1.479     albertel 5890:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5891:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5892:     } 
1.55      www      5893: # realm
1.258     albertel 5894:     if ($env{'request.course.id'}) {
1.378     raeburn  5895:         if ($env{'request.role'} !~ /^cr/) {
                   5896:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  5897:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  5898:             if ($env{'request.role.desc'}) {
                   5899:                 $role = $env{'request.role.desc'};
                   5900:             } else {
                   5901:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5902:             }
1.1257    raeburn  5903:         } else {
                   5904:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  5905:         }
1.898     raeburn  5906:         if ($env{'request.course.sec'}) {
                   5907:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5908:         }   
1.359     albertel 5909: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5910:     } else {
                   5911:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5912:     }
1.433     albertel 5913: 
1.359     albertel 5914:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5915: 
1.438     albertel 5916:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5917: 
1.101     www      5918: # construct main body tag
1.359     albertel 5919:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  5920: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5921: 
1.1131    raeburn  5922:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5923: 
1.1130    raeburn  5924:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5925:         return $bodytag;
1.1130    raeburn  5926:     }
1.359     albertel 5927: 
1.954     raeburn  5928:     if ($public) {
1.433     albertel 5929: 	undef($role);
                   5930:     }
1.359     albertel 5931:     
1.762     bisitz   5932:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5933:     #
                   5934:     # Extra info if you are the DC
                   5935:     my $dc_info = '';
                   5936:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5937:                         $env{'course.'.$env{'request.course.id'}.
                   5938:                                  '.domain'}.'/'})) {
                   5939:         my $cid = $env{'request.course.id'};
1.917     raeburn  5940:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5941:         $dc_info =~ s/\s+$//;
1.359     albertel 5942:     }
                   5943: 
1.1237    raeburn  5944:     my $crstype;
                   5945:     if ($env{'request.course.id'}) {
                   5946:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   5947:     } elsif ($args->{'crstype'}) {
                   5948:         $crstype = $args->{'crstype'};
                   5949:     }
                   5950:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   5951:         undef($role);
                   5952:     } else {
1.1242    raeburn  5953:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  5954:     }
1.853     droeschl 5955: 
1.903     droeschl 5956:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5957: 
                   5958:         #    if ($env{'request.state'} eq 'construct') {
                   5959:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5960:         #    }
                   5961: 
1.1130    raeburn  5962:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5963:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5964: 
1.1237    raeburn  5965:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
1.359     albertel 5966: 
1.916     droeschl 5967:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5968:              if ($dc_info) {
                   5969:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5970:              }
1.1130    raeburn  5971:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5972:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5973:             return $bodytag;
                   5974:         }
1.894     droeschl 5975: 
1.927     raeburn  5976:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5977:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5978:         }
1.916     droeschl 5979: 
1.1130    raeburn  5980:         $bodytag .= $right;
1.852     droeschl 5981: 
1.917     raeburn  5982:         if ($dc_info) {
                   5983:             $dc_info = &dc_courseid_toggle($dc_info);
                   5984:         }
                   5985:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5986: 
1.1169    raeburn  5987:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5988:         if ($args->{'no_secondary_menu'}) {
                   5989:             return $bodytag;
                   5990:         }
1.1169    raeburn  5991:         #don't show menus for public users
1.954     raeburn  5992:         if (!$public){
1.1154    raeburn  5993:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5994:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5995:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5996:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5997:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1274    raeburn  5998:                                 $args->{'bread_crumbs'},'','',$hostname);
1.1096    raeburn  5999:             } elsif ($forcereg) {
                   6000:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6001:                                                             $args->{'group'},
1.1274    raeburn  6002:                                                             $args->{'hide_buttons'},
                   6003:                                                             $hostname);
1.1096    raeburn  6004:             } else {
                   6005:                 $bodytag .= 
                   6006:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6007:                                                         $forcereg,$args->{'group'},
                   6008:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6009:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6010:             }
1.903     droeschl 6011:         }else{
                   6012:             # this is to seperate menu from content when there's no secondary
                   6013:             # menu. Especially needed for public accessible ressources.
                   6014:             $bodytag .= '<hr style="clear:both" />';
                   6015:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6016:         }
1.903     droeschl 6017: 
1.235     raeburn  6018:         return $bodytag;
1.182     matthew  6019: }
                   6020: 
1.917     raeburn  6021: sub dc_courseid_toggle {
                   6022:     my ($dc_info) = @_;
1.980     raeburn  6023:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6024:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6025:            &mt('(More ...)').'</a></span>'.
                   6026:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6027: }
                   6028: 
1.330     albertel 6029: sub make_attr_string {
                   6030:     my ($register,$attr_ref) = @_;
                   6031: 
                   6032:     if ($attr_ref && !ref($attr_ref)) {
                   6033: 	die("addentries Must be a hash ref ".
                   6034: 	    join(':',caller(1))." ".
                   6035: 	    join(':',caller(0))." ");
                   6036:     }
                   6037: 
                   6038:     if ($register) {
1.339     albertel 6039: 	my ($on_load,$on_unload);
                   6040: 	foreach my $key (keys(%{$attr_ref})) {
                   6041: 	    if      (lc($key) eq 'onload') {
                   6042: 		$on_load.=$attr_ref->{$key}.';';
                   6043: 		delete($attr_ref->{$key});
                   6044: 
                   6045: 	    } elsif (lc($key) eq 'onunload') {
                   6046: 		$on_unload.=$attr_ref->{$key}.';';
                   6047: 		delete($attr_ref->{$key});
                   6048: 	    }
                   6049: 	}
1.953     droeschl 6050: 	$attr_ref->{'onload'}  = $on_load;
                   6051: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6052:     }
1.339     albertel 6053: 
1.330     albertel 6054:     my $attr_string;
1.1159    raeburn  6055:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6056: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6057:     }
                   6058:     return $attr_string;
                   6059: }
                   6060: 
                   6061: 
1.182     matthew  6062: ###############################################
1.251     albertel 6063: ###############################################
                   6064: 
                   6065: =pod
                   6066: 
                   6067: =item * &endbodytag()
                   6068: 
                   6069: Returns a uniform footer for LON-CAPA web pages.
                   6070: 
1.635     raeburn  6071: Inputs: 1 - optional reference to an args hash
                   6072: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6073: a 'Continue' link is not displayed if the page contains an
                   6074: internal redirect in the <head></head> section,
                   6075: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6076: 
                   6077: =cut
                   6078: 
                   6079: sub endbodytag {
1.635     raeburn  6080:     my ($args) = @_;
1.1080    raeburn  6081:     my $endbodytag;
                   6082:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6083:         $endbodytag='</body>';
                   6084:     }
1.315     albertel 6085:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6086:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6087: 	    $endbodytag=
                   6088: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6089: 	        &mt('Continue').'</a>'.
                   6090: 	        $endbodytag;
                   6091:         }
1.315     albertel 6092:     }
1.251     albertel 6093:     return $endbodytag;
                   6094: }
                   6095: 
1.352     albertel 6096: =pod
                   6097: 
                   6098: =item * &standard_css()
                   6099: 
                   6100: Returns a style sheet
                   6101: 
                   6102: Inputs: (all optional)
                   6103:             domain         -> force to color decorate a page for a specific
                   6104:                                domain
                   6105:             function       -> force usage of a specific rolish color scheme
                   6106:             bgcolor        -> override the default page bgcolor
                   6107: 
                   6108: =cut
                   6109: 
1.343     albertel 6110: sub standard_css {
1.345     albertel 6111:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6112:     $function  = &get_users_function() if (!$function);
                   6113:     my $img    = &designparm($function.'.img',   $domain);
                   6114:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6115:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6116:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6117: #second colour for later usage
1.345     albertel 6118:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6119:     my $pgbg_or_bgcolor =
                   6120: 	         $bgcolor ||
1.352     albertel 6121: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6122:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6123:     my $alink  = &designparm($function.'.alink', $domain);
                   6124:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6125:     my $link   = &designparm($function.'.link',  $domain);
                   6126: 
1.602     albertel 6127:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6128:     my $mono                 = 'monospace';
1.850     bisitz   6129:     my $data_table_head      = $sidebg;
                   6130:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6131:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6132:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6133:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6134:     my $mail_new             = '#FFBB77';
                   6135:     my $mail_new_hover       = '#DD9955';
                   6136:     my $mail_read            = '#BBBB77';
                   6137:     my $mail_read_hover      = '#999944';
                   6138:     my $mail_replied         = '#AAAA88';
                   6139:     my $mail_replied_hover   = '#888855';
                   6140:     my $mail_other           = '#99BBBB';
                   6141:     my $mail_other_hover     = '#669999';
1.391     albertel 6142:     my $table_header         = '#DDDDDD';
1.489     raeburn  6143:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6144:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6145:     my $button_hover         = '#BF2317';
1.392     albertel 6146: 
1.608     albertel 6147:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6148:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6149:                                              : '0 3px 0 4px';
1.448     albertel 6150: 
1.523     albertel 6151: 
1.343     albertel 6152:     return <<END;
1.947     droeschl 6153: 
                   6154: /* needed for iframe to allow 100% height in FF */
                   6155: body, html { 
                   6156:     margin: 0;
                   6157:     padding: 0 0.5%;
                   6158:     height: 99%; /* to avoid scrollbars */
                   6159: }
                   6160: 
1.795     www      6161: body {
1.911     bisitz   6162:   font-family: $sans;
                   6163:   line-height:130%;
                   6164:   font-size:0.83em;
                   6165:   color:$font;
1.795     www      6166: }
                   6167: 
1.959     onken    6168: a:focus,
                   6169: a:focus img {
1.795     www      6170:   color: red;
                   6171: }
1.698     harmsja  6172: 
1.911     bisitz   6173: form, .inline {
                   6174:   display: inline;
1.795     www      6175: }
1.721     harmsja  6176: 
1.795     www      6177: .LC_right {
1.911     bisitz   6178:   text-align:right;
1.795     www      6179: }
                   6180: 
                   6181: .LC_middle {
1.911     bisitz   6182:   vertical-align:middle;
1.795     www      6183: }
1.721     harmsja  6184: 
1.1130    raeburn  6185: .LC_floatleft {
                   6186:   float: left;
                   6187: }
                   6188: 
                   6189: .LC_floatright {
                   6190:   float: right;
                   6191: }
                   6192: 
1.911     bisitz   6193: .LC_400Box {
                   6194:   width:400px;
                   6195: }
1.721     harmsja  6196: 
1.947     droeschl 6197: .LC_iframecontainer {
                   6198:     width: 98%;
                   6199:     margin: 0;
                   6200:     position: fixed;
                   6201:     top: 8.5em;
                   6202:     bottom: 0;
                   6203: }
                   6204: 
                   6205: .LC_iframecontainer iframe{
                   6206:     border: none;
                   6207:     width: 100%;
                   6208:     height: 100%;
                   6209: }
                   6210: 
1.778     bisitz   6211: .LC_filename {
                   6212:   font-family: $mono;
                   6213:   white-space:pre;
1.921     bisitz   6214:   font-size: 120%;
1.778     bisitz   6215: }
                   6216: 
                   6217: .LC_fileicon {
                   6218:   border: none;
                   6219:   height: 1.3em;
                   6220:   vertical-align: text-bottom;
                   6221:   margin-right: 0.3em;
                   6222:   text-decoration:none;
                   6223: }
                   6224: 
1.1008    www      6225: .LC_setting {
                   6226:   text-decoration:underline;
                   6227: }
                   6228: 
1.350     albertel 6229: .LC_error {
                   6230:   color: red;
                   6231: }
1.795     www      6232: 
1.1097    bisitz   6233: .LC_warning {
                   6234:   color: darkorange;
                   6235: }
                   6236: 
1.457     albertel 6237: .LC_diff_removed {
1.733     bisitz   6238:   color: red;
1.394     albertel 6239: }
1.532     albertel 6240: 
                   6241: .LC_info,
1.457     albertel 6242: .LC_success,
                   6243: .LC_diff_added {
1.350     albertel 6244:   color: green;
                   6245: }
1.795     www      6246: 
1.802     bisitz   6247: div.LC_confirm_box {
                   6248:   background-color: #FAFAFA;
                   6249:   border: 1px solid $lg_border_color;
                   6250:   margin-right: 0;
                   6251:   padding: 5px;
                   6252: }
                   6253: 
                   6254: div.LC_confirm_box .LC_error img,
                   6255: div.LC_confirm_box .LC_success img {
                   6256:   vertical-align: middle;
                   6257: }
                   6258: 
1.1242    raeburn  6259: .LC_maxwidth {
                   6260:   max-width: 100%;
                   6261:   height: auto;
                   6262: }
                   6263: 
1.1243    raeburn  6264: .LC_textsize_mobile {
                   6265:   \@media only screen and (max-device-width: 480px) {
                   6266:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6267:   }
                   6268: }
                   6269: 
1.440     albertel 6270: .LC_icon {
1.771     droeschl 6271:   border: none;
1.790     droeschl 6272:   vertical-align: middle;
1.771     droeschl 6273: }
                   6274: 
1.543     albertel 6275: .LC_docs_spacer {
                   6276:   width: 25px;
                   6277:   height: 1px;
1.771     droeschl 6278:   border: none;
1.543     albertel 6279: }
1.346     albertel 6280: 
1.532     albertel 6281: .LC_internal_info {
1.735     bisitz   6282:   color: #999999;
1.532     albertel 6283: }
                   6284: 
1.794     www      6285: .LC_discussion {
1.1050    www      6286:   background: $data_table_dark;
1.911     bisitz   6287:   border: 1px solid black;
                   6288:   margin: 2px;
1.794     www      6289: }
                   6290: 
                   6291: .LC_disc_action_left {
1.1050    www      6292:   background: $sidebg;
1.911     bisitz   6293:   text-align: left;
1.1050    www      6294:   padding: 4px;
                   6295:   margin: 2px;
1.794     www      6296: }
                   6297: 
                   6298: .LC_disc_action_right {
1.1050    www      6299:   background: $sidebg;
1.911     bisitz   6300:   text-align: right;
1.1050    www      6301:   padding: 4px;
                   6302:   margin: 2px;
1.794     www      6303: }
                   6304: 
                   6305: .LC_disc_new_item {
1.911     bisitz   6306:   background: white;
                   6307:   border: 2px solid red;
1.1050    www      6308:   margin: 4px;
                   6309:   padding: 4px;
1.794     www      6310: }
                   6311: 
                   6312: .LC_disc_old_item {
1.911     bisitz   6313:   background: white;
1.1050    www      6314:   margin: 4px;
                   6315:   padding: 4px;
1.794     www      6316: }
                   6317: 
1.458     albertel 6318: table.LC_pastsubmission {
                   6319:   border: 1px solid black;
                   6320:   margin: 2px;
                   6321: }
                   6322: 
1.924     bisitz   6323: table#LC_menubuttons {
1.345     albertel 6324:   width: 100%;
                   6325:   background: $pgbg;
1.392     albertel 6326:   border: 2px;
1.402     albertel 6327:   border-collapse: separate;
1.803     bisitz   6328:   padding: 0;
1.345     albertel 6329: }
1.392     albertel 6330: 
1.801     tempelho 6331: table#LC_title_bar a {
                   6332:   color: $fontmenu;
                   6333: }
1.836     bisitz   6334: 
1.807     droeschl 6335: table#LC_title_bar {
1.819     tempelho 6336:   clear: both;
1.836     bisitz   6337:   display: none;
1.807     droeschl 6338: }
                   6339: 
1.795     www      6340: table#LC_title_bar,
1.933     droeschl 6341: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6342: table#LC_title_bar.LC_with_remote {
1.359     albertel 6343:   width: 100%;
1.392     albertel 6344:   border-color: $pgbg;
                   6345:   border-style: solid;
                   6346:   border-width: $border;
1.379     albertel 6347:   background: $pgbg;
1.801     tempelho 6348:   color: $fontmenu;
1.392     albertel 6349:   border-collapse: collapse;
1.803     bisitz   6350:   padding: 0;
1.819     tempelho 6351:   margin: 0;
1.359     albertel 6352: }
1.795     www      6353: 
1.933     droeschl 6354: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6355:     margin: 0;
                   6356:     padding: 0;
1.933     droeschl 6357:     position: relative;
                   6358:     list-style: none;
1.913     droeschl 6359: }
1.933     droeschl 6360: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6361:     display: inline;
                   6362: }
1.933     droeschl 6363: 
                   6364: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6365:     padding: 0;
1.933     droeschl 6366:     margin: 0;
                   6367:     float: left;
1.913     droeschl 6368: }
1.933     droeschl 6369: .LC_breadcrumb_tools_tools {
                   6370:     padding: 0;
                   6371:     margin: 0;
1.913     droeschl 6372:     float: right;
                   6373: }
                   6374: 
1.1240    raeburn  6375: .LC_placement_prog {
                   6376:     padding-right: 20px;
                   6377:     font-weight: bold;
                   6378:     font-size: 90%;
                   6379: }
                   6380: 
1.359     albertel 6381: table#LC_title_bar td {
                   6382:   background: $tabbg;
                   6383: }
1.795     www      6384: 
1.911     bisitz   6385: table#LC_menubuttons img {
1.803     bisitz   6386:   border: none;
1.346     albertel 6387: }
1.795     www      6388: 
1.842     droeschl 6389: .LC_breadcrumbs_component {
1.911     bisitz   6390:   float: right;
                   6391:   margin: 0 1em;
1.357     albertel 6392: }
1.842     droeschl 6393: .LC_breadcrumbs_component img {
1.911     bisitz   6394:   vertical-align: middle;
1.777     tempelho 6395: }
1.795     www      6396: 
1.1243    raeburn  6397: .LC_breadcrumbs_hoverable {
                   6398:   background: $sidebg;
                   6399: }
                   6400: 
1.383     albertel 6401: td.LC_table_cell_checkbox {
                   6402:   text-align: center;
                   6403: }
1.795     www      6404: 
                   6405: .LC_fontsize_small {
1.911     bisitz   6406:   font-size: 70%;
1.705     tempelho 6407: }
                   6408: 
1.844     bisitz   6409: #LC_breadcrumbs {
1.911     bisitz   6410:   clear:both;
                   6411:   background: $sidebg;
                   6412:   border-bottom: 1px solid $lg_border_color;
                   6413:   line-height: 2.5em;
1.933     droeschl 6414:   overflow: hidden;
1.911     bisitz   6415:   margin: 0;
                   6416:   padding: 0;
1.995     raeburn  6417:   text-align: left;
1.819     tempelho 6418: }
1.862     bisitz   6419: 
1.1098    bisitz   6420: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6421:   clear:both;
                   6422:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6423:   border: 1px solid $sidebg;
1.1098    bisitz   6424:   margin: 0 0 10px 0;
1.966     bisitz   6425:   padding: 3px;
1.995     raeburn  6426:   text-align: left;
1.822     bisitz   6427: }
                   6428: 
1.795     www      6429: .LC_fontsize_medium {
1.911     bisitz   6430:   font-size: 85%;
1.705     tempelho 6431: }
                   6432: 
1.795     www      6433: .LC_fontsize_large {
1.911     bisitz   6434:   font-size: 120%;
1.705     tempelho 6435: }
                   6436: 
1.346     albertel 6437: .LC_menubuttons_inline_text {
                   6438:   color: $font;
1.698     harmsja  6439:   font-size: 90%;
1.701     harmsja  6440:   padding-left:3px;
1.346     albertel 6441: }
                   6442: 
1.934     droeschl 6443: .LC_menubuttons_inline_text img{
                   6444:   vertical-align: middle;
                   6445: }
                   6446: 
1.1051    www      6447: li.LC_menubuttons_inline_text img {
1.951     onken    6448:   cursor:pointer;
1.1002    droeschl 6449:   text-decoration: none;
1.951     onken    6450: }
                   6451: 
1.526     www      6452: .LC_menubuttons_link {
                   6453:   text-decoration: none;
                   6454: }
1.795     www      6455: 
1.522     albertel 6456: .LC_menubuttons_category {
1.521     www      6457:   color: $font;
1.526     www      6458:   background: $pgbg;
1.521     www      6459:   font-size: larger;
                   6460:   font-weight: bold;
                   6461: }
                   6462: 
1.346     albertel 6463: td.LC_menubuttons_text {
1.911     bisitz   6464:   color: $font;
1.346     albertel 6465: }
1.706     harmsja  6466: 
1.346     albertel 6467: .LC_current_location {
                   6468:   background: $tabbg;
                   6469: }
1.795     www      6470: 
1.1286    raeburn  6471: td.LC_zero_height {
                   6472:   line-height: 0; 
                   6473:   cellpadding: 0;
                   6474: }
                   6475: 
1.938     bisitz   6476: table.LC_data_table {
1.347     albertel 6477:   border: 1px solid #000000;
1.402     albertel 6478:   border-collapse: separate;
1.426     albertel 6479:   border-spacing: 1px;
1.610     albertel 6480:   background: $pgbg;
1.347     albertel 6481: }
1.795     www      6482: 
1.422     albertel 6483: .LC_data_table_dense {
                   6484:   font-size: small;
                   6485: }
1.795     www      6486: 
1.507     raeburn  6487: table.LC_nested_outer {
                   6488:   border: 1px solid #000000;
1.589     raeburn  6489:   border-collapse: collapse;
1.803     bisitz   6490:   border-spacing: 0;
1.507     raeburn  6491:   width: 100%;
                   6492: }
1.795     www      6493: 
1.879     raeburn  6494: table.LC_innerpickbox,
1.507     raeburn  6495: table.LC_nested {
1.803     bisitz   6496:   border: none;
1.589     raeburn  6497:   border-collapse: collapse;
1.803     bisitz   6498:   border-spacing: 0;
1.507     raeburn  6499:   width: 100%;
                   6500: }
1.795     www      6501: 
1.911     bisitz   6502: table.LC_data_table tr th,
                   6503: table.LC_calendar tr th,
1.879     raeburn  6504: table.LC_prior_tries tr th,
                   6505: table.LC_innerpickbox tr th {
1.349     albertel 6506:   font-weight: bold;
                   6507:   background-color: $data_table_head;
1.801     tempelho 6508:   color:$fontmenu;
1.701     harmsja  6509:   font-size:90%;
1.347     albertel 6510: }
1.795     www      6511: 
1.879     raeburn  6512: table.LC_innerpickbox tr th,
                   6513: table.LC_innerpickbox tr td {
                   6514:   vertical-align: top;
                   6515: }
                   6516: 
1.711     raeburn  6517: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6518:   background-color: #CCCCCC;
1.711     raeburn  6519:   font-weight: bold;
                   6520:   text-align: left;
                   6521: }
1.795     www      6522: 
1.912     bisitz   6523: table.LC_data_table tr.LC_odd_row > td {
                   6524:   background-color: $data_table_light;
                   6525:   padding: 2px;
                   6526:   vertical-align: top;
                   6527: }
                   6528: 
1.809     bisitz   6529: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6530:   background-color: $data_table_light;
1.912     bisitz   6531:   vertical-align: top;
                   6532: }
                   6533: 
                   6534: table.LC_data_table tr.LC_even_row > td {
                   6535:   background-color: $data_table_dark;
1.425     albertel 6536:   padding: 2px;
1.900     bisitz   6537:   vertical-align: top;
1.347     albertel 6538: }
1.795     www      6539: 
1.809     bisitz   6540: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6541:   background-color: $data_table_dark;
1.900     bisitz   6542:   vertical-align: top;
1.347     albertel 6543: }
1.795     www      6544: 
1.425     albertel 6545: table.LC_data_table tr.LC_data_table_highlight td {
                   6546:   background-color: $data_table_darker;
                   6547: }
1.795     www      6548: 
1.639     raeburn  6549: table.LC_data_table tr td.LC_leftcol_header {
                   6550:   background-color: $data_table_head;
                   6551:   font-weight: bold;
                   6552: }
1.795     www      6553: 
1.451     albertel 6554: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6555: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6556:   font-weight: bold;
                   6557:   font-style: italic;
                   6558:   text-align: center;
                   6559:   padding: 8px;
1.347     albertel 6560: }
1.795     www      6561: 
1.1114    raeburn  6562: table.LC_data_table tr.LC_empty_row td,
                   6563: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6564:   background-color: $sidebg;
                   6565: }
                   6566: 
                   6567: table.LC_nested tr.LC_empty_row td {
                   6568:   background-color: #FFFFFF;
                   6569: }
                   6570: 
1.890     droeschl 6571: table.LC_caption {
                   6572: }
                   6573: 
1.507     raeburn  6574: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6575:   padding: 4ex
                   6576: }
1.795     www      6577: 
1.507     raeburn  6578: table.LC_nested_outer tr th {
                   6579:   font-weight: bold;
1.801     tempelho 6580:   color:$fontmenu;
1.507     raeburn  6581:   background-color: $data_table_head;
1.701     harmsja  6582:   font-size: small;
1.507     raeburn  6583:   border-bottom: 1px solid #000000;
                   6584: }
1.795     www      6585: 
1.507     raeburn  6586: table.LC_nested_outer tr td.LC_subheader {
                   6587:   background-color: $data_table_head;
                   6588:   font-weight: bold;
                   6589:   font-size: small;
                   6590:   border-bottom: 1px solid #000000;
                   6591:   text-align: right;
1.451     albertel 6592: }
1.795     www      6593: 
1.507     raeburn  6594: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6595:   background-color: #CCCCCC;
1.451     albertel 6596:   font-weight: bold;
                   6597:   font-size: small;
1.507     raeburn  6598:   text-align: center;
                   6599: }
1.795     www      6600: 
1.589     raeburn  6601: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6602: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6603:   text-align: left;
1.451     albertel 6604: }
1.795     www      6605: 
1.507     raeburn  6606: table.LC_nested td {
1.735     bisitz   6607:   background-color: #FFFFFF;
1.451     albertel 6608:   font-size: small;
1.507     raeburn  6609: }
1.795     www      6610: 
1.507     raeburn  6611: table.LC_nested_outer tr th.LC_right_item,
                   6612: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6613: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6614: table.LC_nested tr td.LC_right_item {
1.451     albertel 6615:   text-align: right;
                   6616: }
                   6617: 
1.507     raeburn  6618: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6619:   background-color: #EEEEEE;
1.451     albertel 6620: }
                   6621: 
1.473     raeburn  6622: table.LC_createuser {
                   6623: }
                   6624: 
                   6625: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6626:   font-size: small;
1.473     raeburn  6627: }
                   6628: 
                   6629: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6630:   background-color: #CCCCCC;
1.473     raeburn  6631:   font-weight: bold;
                   6632:   text-align: center;
                   6633: }
                   6634: 
1.349     albertel 6635: table.LC_calendar {
                   6636:   border: 1px solid #000000;
                   6637:   border-collapse: collapse;
1.917     raeburn  6638:   width: 98%;
1.349     albertel 6639: }
1.795     www      6640: 
1.349     albertel 6641: table.LC_calendar_pickdate {
                   6642:   font-size: xx-small;
                   6643: }
1.795     www      6644: 
1.349     albertel 6645: table.LC_calendar tr td {
                   6646:   border: 1px solid #000000;
                   6647:   vertical-align: top;
1.917     raeburn  6648:   width: 14%;
1.349     albertel 6649: }
1.795     www      6650: 
1.349     albertel 6651: table.LC_calendar tr td.LC_calendar_day_empty {
                   6652:   background-color: $data_table_dark;
                   6653: }
1.795     www      6654: 
1.779     bisitz   6655: table.LC_calendar tr td.LC_calendar_day_current {
                   6656:   background-color: $data_table_highlight;
1.777     tempelho 6657: }
1.795     www      6658: 
1.938     bisitz   6659: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6660:   background-color: $mail_new;
                   6661: }
1.795     www      6662: 
1.938     bisitz   6663: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6664:   background-color: $mail_new_hover;
                   6665: }
1.795     www      6666: 
1.938     bisitz   6667: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6668:   background-color: $mail_read;
                   6669: }
1.795     www      6670: 
1.938     bisitz   6671: /*
                   6672: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6673:   background-color: $mail_read_hover;
                   6674: }
1.938     bisitz   6675: */
1.795     www      6676: 
1.938     bisitz   6677: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6678:   background-color: $mail_replied;
                   6679: }
1.795     www      6680: 
1.938     bisitz   6681: /*
                   6682: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6683:   background-color: $mail_replied_hover;
                   6684: }
1.938     bisitz   6685: */
1.795     www      6686: 
1.938     bisitz   6687: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6688:   background-color: $mail_other;
                   6689: }
1.795     www      6690: 
1.938     bisitz   6691: /*
                   6692: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6693:   background-color: $mail_other_hover;
                   6694: }
1.938     bisitz   6695: */
1.494     raeburn  6696: 
1.777     tempelho 6697: table.LC_data_table tr > td.LC_browser_file,
                   6698: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6699:   background: #AAEE77;
1.389     albertel 6700: }
1.795     www      6701: 
1.777     tempelho 6702: table.LC_data_table tr > td.LC_browser_file_locked,
                   6703: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6704:   background: #FFAA99;
1.387     albertel 6705: }
1.795     www      6706: 
1.777     tempelho 6707: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6708:   background: #888888;
1.779     bisitz   6709: }
1.795     www      6710: 
1.777     tempelho 6711: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6712: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6713:   background: #F8F866;
1.777     tempelho 6714: }
1.795     www      6715: 
1.696     bisitz   6716: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6717:   background: #E0E8FF;
1.387     albertel 6718: }
1.696     bisitz   6719: 
1.707     bisitz   6720: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6721:   /* background: #77FF77; */
1.707     bisitz   6722: }
1.795     www      6723: 
1.707     bisitz   6724: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6725:   border-right: 8px solid #FFFF77;
1.707     bisitz   6726: }
1.795     www      6727: 
1.707     bisitz   6728: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6729:   border-right: 8px solid #FFAA77;
1.707     bisitz   6730: }
1.795     www      6731: 
1.707     bisitz   6732: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6733:   border-right: 8px solid #FF7777;
1.707     bisitz   6734: }
1.795     www      6735: 
1.707     bisitz   6736: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6737:   border-right: 8px solid #AAFF77;
1.707     bisitz   6738: }
1.795     www      6739: 
1.707     bisitz   6740: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6741:   border-right: 8px solid #11CC55;
1.707     bisitz   6742: }
                   6743: 
1.388     albertel 6744: span.LC_current_location {
1.701     harmsja  6745:   font-size:larger;
1.388     albertel 6746:   background: $pgbg;
                   6747: }
1.387     albertel 6748: 
1.1029    www      6749: span.LC_current_nav_location {
                   6750:   font-weight:bold;
                   6751:   background: $sidebg;
                   6752: }
                   6753: 
1.395     albertel 6754: span.LC_parm_menu_item {
                   6755:   font-size: larger;
                   6756: }
1.795     www      6757: 
1.395     albertel 6758: span.LC_parm_scope_all {
                   6759:   color: red;
                   6760: }
1.795     www      6761: 
1.395     albertel 6762: span.LC_parm_scope_folder {
                   6763:   color: green;
                   6764: }
1.795     www      6765: 
1.395     albertel 6766: span.LC_parm_scope_resource {
                   6767:   color: orange;
                   6768: }
1.795     www      6769: 
1.395     albertel 6770: span.LC_parm_part {
                   6771:   color: blue;
                   6772: }
1.795     www      6773: 
1.911     bisitz   6774: span.LC_parm_folder,
                   6775: span.LC_parm_symb {
1.395     albertel 6776:   font-size: x-small;
                   6777:   font-family: $mono;
                   6778:   color: #AAAAAA;
                   6779: }
                   6780: 
1.977     bisitz   6781: ul.LC_parm_parmlist li {
                   6782:   display: inline-block;
                   6783:   padding: 0.3em 0.8em;
                   6784:   vertical-align: top;
                   6785:   width: 150px;
                   6786:   border-top:1px solid $lg_border_color;
                   6787: }
                   6788: 
1.795     www      6789: td.LC_parm_overview_level_menu,
                   6790: td.LC_parm_overview_map_menu,
                   6791: td.LC_parm_overview_parm_selectors,
                   6792: td.LC_parm_overview_restrictions  {
1.396     albertel 6793:   border: 1px solid black;
                   6794:   border-collapse: collapse;
                   6795: }
1.795     www      6796: 
1.1285    raeburn  6797: span.LC_parm_recursive,
                   6798: td.LC_parm_recursive {
                   6799:   font-weight: bold;
                   6800:   font-size: smaller;
                   6801: }
                   6802: 
1.396     albertel 6803: table.LC_parm_overview_restrictions td {
                   6804:   border-width: 1px 4px 1px 4px;
                   6805:   border-style: solid;
                   6806:   border-color: $pgbg;
                   6807:   text-align: center;
                   6808: }
1.795     www      6809: 
1.396     albertel 6810: table.LC_parm_overview_restrictions th {
                   6811:   background: $tabbg;
                   6812:   border-width: 1px 4px 1px 4px;
                   6813:   border-style: solid;
                   6814:   border-color: $pgbg;
                   6815: }
1.795     www      6816: 
1.398     albertel 6817: table#LC_helpmenu {
1.803     bisitz   6818:   border: none;
1.398     albertel 6819:   height: 55px;
1.803     bisitz   6820:   border-spacing: 0;
1.398     albertel 6821: }
                   6822: 
                   6823: table#LC_helpmenu fieldset legend {
                   6824:   font-size: larger;
                   6825: }
1.795     www      6826: 
1.397     albertel 6827: table#LC_helpmenu_links {
                   6828:   width: 100%;
                   6829:   border: 1px solid black;
                   6830:   background: $pgbg;
1.803     bisitz   6831:   padding: 0;
1.397     albertel 6832:   border-spacing: 1px;
                   6833: }
1.795     www      6834: 
1.397     albertel 6835: table#LC_helpmenu_links tr td {
                   6836:   padding: 1px;
                   6837:   background: $tabbg;
1.399     albertel 6838:   text-align: center;
                   6839:   font-weight: bold;
1.397     albertel 6840: }
1.396     albertel 6841: 
1.795     www      6842: table#LC_helpmenu_links a:link,
                   6843: table#LC_helpmenu_links a:visited,
1.397     albertel 6844: table#LC_helpmenu_links a:active {
                   6845:   text-decoration: none;
                   6846:   color: $font;
                   6847: }
1.795     www      6848: 
1.397     albertel 6849: table#LC_helpmenu_links a:hover {
                   6850:   text-decoration: underline;
                   6851:   color: $vlink;
                   6852: }
1.396     albertel 6853: 
1.417     albertel 6854: .LC_chrt_popup_exists {
                   6855:   border: 1px solid #339933;
                   6856:   margin: -1px;
                   6857: }
1.795     www      6858: 
1.417     albertel 6859: .LC_chrt_popup_up {
                   6860:   border: 1px solid yellow;
                   6861:   margin: -1px;
                   6862: }
1.795     www      6863: 
1.417     albertel 6864: .LC_chrt_popup {
                   6865:   border: 1px solid #8888FF;
                   6866:   background: #CCCCFF;
                   6867: }
1.795     www      6868: 
1.421     albertel 6869: table.LC_pick_box {
                   6870:   border-collapse: separate;
                   6871:   background: white;
                   6872:   border: 1px solid black;
                   6873:   border-spacing: 1px;
                   6874: }
1.795     www      6875: 
1.421     albertel 6876: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6877:   background: $sidebg;
1.421     albertel 6878:   font-weight: bold;
1.900     bisitz   6879:   text-align: left;
1.740     bisitz   6880:   vertical-align: top;
1.421     albertel 6881:   width: 184px;
                   6882:   padding: 8px;
                   6883: }
1.795     www      6884: 
1.579     raeburn  6885: table.LC_pick_box td.LC_pick_box_value {
                   6886:   text-align: left;
                   6887:   padding: 8px;
                   6888: }
1.795     www      6889: 
1.579     raeburn  6890: table.LC_pick_box td.LC_pick_box_select {
                   6891:   text-align: left;
                   6892:   padding: 8px;
                   6893: }
1.795     www      6894: 
1.424     albertel 6895: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6896:   padding: 0;
1.421     albertel 6897:   height: 1px;
                   6898:   background: black;
                   6899: }
1.795     www      6900: 
1.421     albertel 6901: table.LC_pick_box td.LC_pick_box_submit {
                   6902:   text-align: right;
                   6903: }
1.795     www      6904: 
1.579     raeburn  6905: table.LC_pick_box td.LC_evenrow_value {
                   6906:   text-align: left;
                   6907:   padding: 8px;
                   6908:   background-color: $data_table_light;
                   6909: }
1.795     www      6910: 
1.579     raeburn  6911: table.LC_pick_box td.LC_oddrow_value {
                   6912:   text-align: left;
                   6913:   padding: 8px;
                   6914:   background-color: $data_table_light;
                   6915: }
1.795     www      6916: 
1.579     raeburn  6917: span.LC_helpform_receipt_cat {
                   6918:   font-weight: bold;
                   6919: }
1.795     www      6920: 
1.424     albertel 6921: table.LC_group_priv_box {
                   6922:   background: white;
                   6923:   border: 1px solid black;
                   6924:   border-spacing: 1px;
                   6925: }
1.795     www      6926: 
1.424     albertel 6927: table.LC_group_priv_box td.LC_pick_box_title {
                   6928:   background: $tabbg;
                   6929:   font-weight: bold;
                   6930:   text-align: right;
                   6931:   width: 184px;
                   6932: }
1.795     www      6933: 
1.424     albertel 6934: table.LC_group_priv_box td.LC_groups_fixed {
                   6935:   background: $data_table_light;
                   6936:   text-align: center;
                   6937: }
1.795     www      6938: 
1.424     albertel 6939: table.LC_group_priv_box td.LC_groups_optional {
                   6940:   background: $data_table_dark;
                   6941:   text-align: center;
                   6942: }
1.795     www      6943: 
1.424     albertel 6944: table.LC_group_priv_box td.LC_groups_functionality {
                   6945:   background: $data_table_darker;
                   6946:   text-align: center;
                   6947:   font-weight: bold;
                   6948: }
1.795     www      6949: 
1.424     albertel 6950: table.LC_group_priv td {
                   6951:   text-align: left;
1.803     bisitz   6952:   padding: 0;
1.424     albertel 6953: }
                   6954: 
                   6955: .LC_navbuttons {
                   6956:   margin: 2ex 0ex 2ex 0ex;
                   6957: }
1.795     www      6958: 
1.423     albertel 6959: .LC_topic_bar {
                   6960:   font-weight: bold;
                   6961:   background: $tabbg;
1.918     wenzelju 6962:   margin: 1em 0em 1em 2em;
1.805     bisitz   6963:   padding: 3px;
1.918     wenzelju 6964:   font-size: 1.2em;
1.423     albertel 6965: }
1.795     www      6966: 
1.423     albertel 6967: .LC_topic_bar span {
1.918     wenzelju 6968:   left: 0.5em;
                   6969:   position: absolute;
1.423     albertel 6970:   vertical-align: middle;
1.918     wenzelju 6971:   font-size: 1.2em;
1.423     albertel 6972: }
1.795     www      6973: 
1.423     albertel 6974: table.LC_course_group_status {
                   6975:   margin: 20px;
                   6976: }
1.795     www      6977: 
1.423     albertel 6978: table.LC_status_selector td {
                   6979:   vertical-align: top;
                   6980:   text-align: center;
1.424     albertel 6981:   padding: 4px;
                   6982: }
1.795     www      6983: 
1.599     albertel 6984: div.LC_feedback_link {
1.616     albertel 6985:   clear: both;
1.829     kalberla 6986:   background: $sidebg;
1.779     bisitz   6987:   width: 100%;
1.829     kalberla 6988:   padding-bottom: 10px;
                   6989:   border: 1px $tabbg solid;
1.833     kalberla 6990:   height: 22px;
                   6991:   line-height: 22px;
                   6992:   padding-top: 5px;
                   6993: }
                   6994: 
                   6995: div.LC_feedback_link img {
                   6996:   height: 22px;
1.867     kalberla 6997:   vertical-align:middle;
1.829     kalberla 6998: }
                   6999: 
1.911     bisitz   7000: div.LC_feedback_link a {
1.829     kalberla 7001:   text-decoration: none;
1.489     raeburn  7002: }
1.795     www      7003: 
1.867     kalberla 7004: div.LC_comblock {
1.911     bisitz   7005:   display:inline;
1.867     kalberla 7006:   color:$font;
                   7007:   font-size:90%;
                   7008: }
                   7009: 
                   7010: div.LC_feedback_link div.LC_comblock {
                   7011:   padding-left:5px;
                   7012: }
                   7013: 
                   7014: div.LC_feedback_link div.LC_comblock a {
                   7015:   color:$font;
                   7016: }
                   7017: 
1.489     raeburn  7018: span.LC_feedback_link {
1.858     bisitz   7019:   /* background: $feedback_link_bg; */
1.599     albertel 7020:   font-size: larger;
                   7021: }
1.795     www      7022: 
1.599     albertel 7023: span.LC_message_link {
1.858     bisitz   7024:   /* background: $feedback_link_bg; */
1.599     albertel 7025:   font-size: larger;
                   7026:   position: absolute;
                   7027:   right: 1em;
1.489     raeburn  7028: }
1.421     albertel 7029: 
1.515     albertel 7030: table.LC_prior_tries {
1.524     albertel 7031:   border: 1px solid #000000;
                   7032:   border-collapse: separate;
                   7033:   border-spacing: 1px;
1.515     albertel 7034: }
1.523     albertel 7035: 
1.515     albertel 7036: table.LC_prior_tries td {
1.524     albertel 7037:   padding: 2px;
1.515     albertel 7038: }
1.523     albertel 7039: 
                   7040: .LC_answer_correct {
1.795     www      7041:   background: lightgreen;
                   7042:   color: darkgreen;
                   7043:   padding: 6px;
1.523     albertel 7044: }
1.795     www      7045: 
1.523     albertel 7046: .LC_answer_charged_try {
1.797     www      7047:   background: #FFAAAA;
1.795     www      7048:   color: darkred;
                   7049:   padding: 6px;
1.523     albertel 7050: }
1.795     www      7051: 
1.779     bisitz   7052: .LC_answer_not_charged_try,
1.523     albertel 7053: .LC_answer_no_grade,
                   7054: .LC_answer_late {
1.795     www      7055:   background: lightyellow;
1.523     albertel 7056:   color: black;
1.795     www      7057:   padding: 6px;
1.523     albertel 7058: }
1.795     www      7059: 
1.523     albertel 7060: .LC_answer_previous {
1.795     www      7061:   background: lightblue;
                   7062:   color: darkblue;
                   7063:   padding: 6px;
1.523     albertel 7064: }
1.795     www      7065: 
1.779     bisitz   7066: .LC_answer_no_message {
1.777     tempelho 7067:   background: #FFFFFF;
                   7068:   color: black;
1.795     www      7069:   padding: 6px;
1.779     bisitz   7070: }
1.795     www      7071: 
1.779     bisitz   7072: .LC_answer_unknown {
                   7073:   background: orange;
                   7074:   color: black;
1.795     www      7075:   padding: 6px;
1.777     tempelho 7076: }
1.795     www      7077: 
1.529     albertel 7078: span.LC_prior_numerical,
                   7079: span.LC_prior_string,
                   7080: span.LC_prior_custom,
                   7081: span.LC_prior_reaction,
                   7082: span.LC_prior_math {
1.925     bisitz   7083:   font-family: $mono;
1.523     albertel 7084:   white-space: pre;
                   7085: }
                   7086: 
1.525     albertel 7087: span.LC_prior_string {
1.925     bisitz   7088:   font-family: $mono;
1.525     albertel 7089:   white-space: pre;
                   7090: }
                   7091: 
1.523     albertel 7092: table.LC_prior_option {
                   7093:   width: 100%;
                   7094:   border-collapse: collapse;
                   7095: }
1.795     www      7096: 
1.911     bisitz   7097: table.LC_prior_rank,
1.795     www      7098: table.LC_prior_match {
1.528     albertel 7099:   border-collapse: collapse;
                   7100: }
1.795     www      7101: 
1.528     albertel 7102: table.LC_prior_option tr td,
                   7103: table.LC_prior_rank tr td,
                   7104: table.LC_prior_match tr td {
1.524     albertel 7105:   border: 1px solid #000000;
1.515     albertel 7106: }
                   7107: 
1.855     bisitz   7108: .LC_nobreak {
1.544     albertel 7109:   white-space: nowrap;
1.519     raeburn  7110: }
                   7111: 
1.576     raeburn  7112: span.LC_cusr_emph {
                   7113:   font-style: italic;
                   7114: }
                   7115: 
1.633     raeburn  7116: span.LC_cusr_subheading {
                   7117:   font-weight: normal;
                   7118:   font-size: 85%;
                   7119: }
                   7120: 
1.861     bisitz   7121: div.LC_docs_entry_move {
1.859     bisitz   7122:   border: 1px solid #BBBBBB;
1.545     albertel 7123:   background: #DDDDDD;
1.861     bisitz   7124:   width: 22px;
1.859     bisitz   7125:   padding: 1px;
                   7126:   margin: 0;
1.545     albertel 7127: }
                   7128: 
1.861     bisitz   7129: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7130: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7131:   font-size: x-small;
                   7132: }
1.795     www      7133: 
1.861     bisitz   7134: .LC_docs_entry_parameter {
                   7135:   white-space: nowrap;
                   7136: }
                   7137: 
1.544     albertel 7138: .LC_docs_copy {
1.545     albertel 7139:   color: #000099;
1.544     albertel 7140: }
1.795     www      7141: 
1.544     albertel 7142: .LC_docs_cut {
1.545     albertel 7143:   color: #550044;
1.544     albertel 7144: }
1.795     www      7145: 
1.544     albertel 7146: .LC_docs_rename {
1.545     albertel 7147:   color: #009900;
1.544     albertel 7148: }
1.795     www      7149: 
1.544     albertel 7150: .LC_docs_remove {
1.545     albertel 7151:   color: #990000;
                   7152: }
                   7153: 
1.1284    raeburn  7154: .LC_docs_alias {
                   7155:   color: #440055;  
                   7156: }
                   7157: 
1.1286    raeburn  7158: .LC_domprefs_email,
1.1284    raeburn  7159: .LC_docs_alias_name,
1.547     albertel 7160: .LC_docs_reinit_warn,
                   7161: .LC_docs_ext_edit {
                   7162:   font-size: x-small;
                   7163: }
                   7164: 
1.545     albertel 7165: table.LC_docs_adddocs td,
                   7166: table.LC_docs_adddocs th {
                   7167:   border: 1px solid #BBBBBB;
                   7168:   padding: 4px;
                   7169:   background: #DDDDDD;
1.543     albertel 7170: }
                   7171: 
1.584     albertel 7172: table.LC_sty_begin {
                   7173:   background: #BBFFBB;
                   7174: }
1.795     www      7175: 
1.584     albertel 7176: table.LC_sty_end {
                   7177:   background: #FFBBBB;
                   7178: }
                   7179: 
1.589     raeburn  7180: table.LC_double_column {
1.803     bisitz   7181:   border-width: 0;
1.589     raeburn  7182:   border-collapse: collapse;
                   7183:   width: 100%;
                   7184:   padding: 2px;
                   7185: }
                   7186: 
                   7187: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7188:   top: 2px;
1.589     raeburn  7189:   left: 2px;
                   7190:   width: 47%;
                   7191:   vertical-align: top;
                   7192: }
                   7193: 
                   7194: table.LC_double_column tr td.LC_right_col {
                   7195:   top: 2px;
1.779     bisitz   7196:   right: 2px;
1.589     raeburn  7197:   width: 47%;
                   7198:   vertical-align: top;
                   7199: }
                   7200: 
1.591     raeburn  7201: div.LC_left_float {
                   7202:   float: left;
                   7203:   padding-right: 5%;
1.597     albertel 7204:   padding-bottom: 4px;
1.591     raeburn  7205: }
                   7206: 
                   7207: div.LC_clear_float_header {
1.597     albertel 7208:   padding-bottom: 2px;
1.591     raeburn  7209: }
                   7210: 
                   7211: div.LC_clear_float_footer {
1.597     albertel 7212:   padding-top: 10px;
1.591     raeburn  7213:   clear: both;
                   7214: }
                   7215: 
1.597     albertel 7216: div.LC_grade_show_user {
1.941     bisitz   7217: /*  border-left: 5px solid $sidebg; */
                   7218:   border-top: 5px solid #000000;
                   7219:   margin: 50px 0 0 0;
1.936     bisitz   7220:   padding: 15px 0 5px 10px;
1.597     albertel 7221: }
1.795     www      7222: 
1.936     bisitz   7223: div.LC_grade_show_user_odd_row {
1.941     bisitz   7224: /*  border-left: 5px solid #000000; */
                   7225: }
                   7226: 
                   7227: div.LC_grade_show_user div.LC_Box {
                   7228:   margin-right: 50px;
1.597     albertel 7229: }
                   7230: 
                   7231: div.LC_grade_submissions,
                   7232: div.LC_grade_message_center,
1.936     bisitz   7233: div.LC_grade_info_links {
1.597     albertel 7234:   margin: 5px;
                   7235:   width: 99%;
                   7236:   background: #FFFFFF;
                   7237: }
1.795     www      7238: 
1.597     albertel 7239: div.LC_grade_submissions_header,
1.936     bisitz   7240: div.LC_grade_message_center_header {
1.705     tempelho 7241:   font-weight: bold;
                   7242:   font-size: large;
1.597     albertel 7243: }
1.795     www      7244: 
1.597     albertel 7245: div.LC_grade_submissions_body,
1.936     bisitz   7246: div.LC_grade_message_center_body {
1.597     albertel 7247:   border: 1px solid black;
                   7248:   width: 99%;
                   7249:   background: #FFFFFF;
                   7250: }
1.795     www      7251: 
1.613     albertel 7252: table.LC_scantron_action {
                   7253:   width: 100%;
                   7254: }
1.795     www      7255: 
1.613     albertel 7256: table.LC_scantron_action tr th {
1.698     harmsja  7257:   font-weight:bold;
                   7258:   font-style:normal;
1.613     albertel 7259: }
1.795     www      7260: 
1.779     bisitz   7261: .LC_edit_problem_header,
1.614     albertel 7262: div.LC_edit_problem_footer {
1.705     tempelho 7263:   font-weight: normal;
                   7264:   font-size:  medium;
1.602     albertel 7265:   margin: 2px;
1.1060    bisitz   7266:   background-color: $sidebg;
1.600     albertel 7267: }
1.795     www      7268: 
1.600     albertel 7269: div.LC_edit_problem_header,
1.602     albertel 7270: div.LC_edit_problem_header div,
1.614     albertel 7271: div.LC_edit_problem_footer,
                   7272: div.LC_edit_problem_footer div,
1.602     albertel 7273: div.LC_edit_problem_editxml_header,
                   7274: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7275:   z-index: 100;
1.600     albertel 7276: }
1.795     www      7277: 
1.600     albertel 7278: div.LC_edit_problem_header_title {
1.705     tempelho 7279:   font-weight: bold;
                   7280:   font-size: larger;
1.602     albertel 7281:   background: $tabbg;
                   7282:   padding: 3px;
1.1060    bisitz   7283:   margin: 0 0 5px 0;
1.602     albertel 7284: }
1.795     www      7285: 
1.602     albertel 7286: table.LC_edit_problem_header_title {
                   7287:   width: 100%;
1.600     albertel 7288:   background: $tabbg;
1.602     albertel 7289: }
                   7290: 
1.1205    golterma 7291: div.LC_edit_actionbar {
                   7292:     background-color: $sidebg;
1.1218    droeschl 7293:     margin: 0;
                   7294:     padding: 0;
                   7295:     line-height: 200%;
1.602     albertel 7296: }
1.795     www      7297: 
1.1218    droeschl 7298: div.LC_edit_actionbar div{
                   7299:     padding: 0;
                   7300:     margin: 0;
                   7301:     display: inline-block;
1.600     albertel 7302: }
1.795     www      7303: 
1.1124    bisitz   7304: .LC_edit_opt {
                   7305:   padding-left: 1em;
                   7306:   white-space: nowrap;
                   7307: }
                   7308: 
1.1152    golterma 7309: .LC_edit_problem_latexhelper{
                   7310:     text-align: right;
                   7311: }
                   7312: 
                   7313: #LC_edit_problem_colorful div{
                   7314:     margin-left: 40px;
                   7315: }
                   7316: 
1.1205    golterma 7317: #LC_edit_problem_codemirror div{
                   7318:     margin-left: 0px;
                   7319: }
                   7320: 
1.911     bisitz   7321: img.stift {
1.803     bisitz   7322:   border-width: 0;
                   7323:   vertical-align: middle;
1.677     riegler  7324: }
1.680     riegler  7325: 
1.923     bisitz   7326: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7327:   vertical-align: top;
1.777     tempelho 7328: }
1.795     www      7329: 
1.716     raeburn  7330: div.LC_createcourse {
1.911     bisitz   7331:   margin: 10px 10px 10px 10px;
1.716     raeburn  7332: }
                   7333: 
1.917     raeburn  7334: .LC_dccid {
1.1130    raeburn  7335:   float: right;
1.917     raeburn  7336:   margin: 0.2em 0 0 0;
                   7337:   padding: 0;
                   7338:   font-size: 90%;
                   7339:   display:none;
                   7340: }
                   7341: 
1.897     wenzelju 7342: ol.LC_primary_menu a:hover,
1.721     harmsja  7343: ol#LC_MenuBreadcrumbs a:hover,
                   7344: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7345: ul#LC_secondary_menu a:hover,
1.721     harmsja  7346: .LC_FormSectionClearButton input:hover
1.795     www      7347: ul.LC_TabContent   li:hover a {
1.952     onken    7348:   color:$button_hover;
1.911     bisitz   7349:   text-decoration:none;
1.693     droeschl 7350: }
                   7351: 
1.779     bisitz   7352: h1 {
1.911     bisitz   7353:   padding: 0;
                   7354:   line-height:130%;
1.693     droeschl 7355: }
1.698     harmsja  7356: 
1.911     bisitz   7357: h2,
                   7358: h3,
                   7359: h4,
                   7360: h5,
                   7361: h6 {
                   7362:   margin: 5px 0 5px 0;
                   7363:   padding: 0;
                   7364:   line-height:130%;
1.693     droeschl 7365: }
1.795     www      7366: 
                   7367: .LC_hcell {
1.911     bisitz   7368:   padding:3px 15px 3px 15px;
                   7369:   margin: 0;
                   7370:   background-color:$tabbg;
                   7371:   color:$fontmenu;
                   7372:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7373: }
1.795     www      7374: 
1.840     bisitz   7375: .LC_Box > .LC_hcell {
1.911     bisitz   7376:   margin: 0 -10px 10px -10px;
1.835     bisitz   7377: }
                   7378: 
1.721     harmsja  7379: .LC_noBorder {
1.911     bisitz   7380:   border: 0;
1.698     harmsja  7381: }
1.693     droeschl 7382: 
1.721     harmsja  7383: .LC_FormSectionClearButton input {
1.911     bisitz   7384:   background-color:transparent;
                   7385:   border: none;
                   7386:   cursor:pointer;
                   7387:   text-decoration:underline;
1.693     droeschl 7388: }
1.763     bisitz   7389: 
                   7390: .LC_help_open_topic {
1.911     bisitz   7391:   color: #FFFFFF;
                   7392:   background-color: #EEEEFF;
                   7393:   margin: 1px;
                   7394:   padding: 4px;
                   7395:   border: 1px solid #000033;
                   7396:   white-space: nowrap;
                   7397:   /* vertical-align: middle; */
1.759     neumanie 7398: }
1.693     droeschl 7399: 
1.911     bisitz   7400: dl,
                   7401: ul,
                   7402: div,
                   7403: fieldset {
                   7404:   margin: 10px 10px 10px 0;
                   7405:   /* overflow: hidden; */
1.693     droeschl 7406: }
1.795     www      7407: 
1.1211    raeburn  7408: article.geogebraweb div {
                   7409:     margin: 0;
                   7410: }
                   7411: 
1.838     bisitz   7412: fieldset > legend {
1.911     bisitz   7413:   font-weight: bold;
                   7414:   padding: 0 5px 0 5px;
1.838     bisitz   7415: }
                   7416: 
1.813     bisitz   7417: #LC_nav_bar {
1.911     bisitz   7418:   float: left;
1.995     raeburn  7419:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7420:   margin: 0 0 2px 0;
1.807     droeschl 7421: }
                   7422: 
1.916     droeschl 7423: #LC_realm {
                   7424:   margin: 0.2em 0 0 0;
                   7425:   padding: 0;
                   7426:   font-weight: bold;
                   7427:   text-align: center;
1.995     raeburn  7428:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7429: }
                   7430: 
1.911     bisitz   7431: #LC_nav_bar em {
                   7432:   font-weight: bold;
                   7433:   font-style: normal;
1.807     droeschl 7434: }
                   7435: 
1.897     wenzelju 7436: ol.LC_primary_menu {
1.934     droeschl 7437:   margin: 0;
1.1076    raeburn  7438:   padding: 0;
1.807     droeschl 7439: }
                   7440: 
1.852     droeschl 7441: ol#LC_PathBreadcrumbs {
1.911     bisitz   7442:   margin: 0;
1.693     droeschl 7443: }
                   7444: 
1.897     wenzelju 7445: ol.LC_primary_menu li {
1.1076    raeburn  7446:   color: RGB(80, 80, 80);
                   7447:   vertical-align: middle;
                   7448:   text-align: left;
                   7449:   list-style: none;
1.1205    golterma 7450:   position: relative;
1.1076    raeburn  7451:   float: left;
1.1205    golterma 7452:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7453:   line-height: 1.5em;
1.1076    raeburn  7454: }
                   7455: 
1.1205    golterma 7456: ol.LC_primary_menu li a,
                   7457: ol.LC_primary_menu li p {
1.1076    raeburn  7458:   display: block;
                   7459:   margin: 0;
                   7460:   padding: 0 5px 0 10px;
                   7461:   text-decoration: none;
                   7462: }
                   7463: 
1.1205    golterma 7464: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7465:   display: inline-block;
                   7466:   width: 95%;
                   7467:   text-align: left;
                   7468: }
                   7469: 
                   7470: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7471:   display: inline-block;	
                   7472:   width: 5%;
                   7473:   float: right;
                   7474:   text-align: right;
                   7475:   font-size: 70%;
                   7476: }
                   7477: 
                   7478: ol.LC_primary_menu ul {
1.1076    raeburn  7479:   display: none;
1.1205    golterma 7480:   width: 15em;
1.1076    raeburn  7481:   background-color: $data_table_light;
1.1205    golterma 7482:   position: absolute;
                   7483:   top: 100%;
1.1076    raeburn  7484: }
                   7485: 
1.1205    golterma 7486: ol.LC_primary_menu ul ul {
                   7487:   left: 100%;
                   7488:   top: 0;
                   7489: }
                   7490: 
                   7491: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7492:   display: block;
                   7493:   position: absolute;
                   7494:   margin: 0;
                   7495:   padding: 0;
1.1078    raeburn  7496:   z-index: 2;
1.1076    raeburn  7497: }
                   7498: 
                   7499: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7500: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7501:   font-size: 90%;
1.911     bisitz   7502:   vertical-align: top;
1.1076    raeburn  7503:   float: none;
1.1079    raeburn  7504:   border-left: 1px solid black;
                   7505:   border-right: 1px solid black;
1.1205    golterma 7506: /* A dark bottom border to visualize different menu options; 
                   7507: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7508:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7509: }
                   7510: 
1.1205    golterma 7511: ol.LC_primary_menu li li p:hover {
                   7512:   color:$button_hover;
                   7513:   text-decoration:none;
                   7514:   background-color:$data_table_dark;
1.1076    raeburn  7515: }
                   7516: 
                   7517: ol.LC_primary_menu li li a:hover {
                   7518:    color:$button_hover;
                   7519:    background-color:$data_table_dark;
1.693     droeschl 7520: }
                   7521: 
1.1205    golterma 7522: /* Font-size equal to the size of the predecessors*/
                   7523: ol.LC_primary_menu li:hover li li {
                   7524:   font-size: 100%;
                   7525: }
                   7526: 
1.897     wenzelju 7527: ol.LC_primary_menu li img {
1.911     bisitz   7528:   vertical-align: bottom;
1.934     droeschl 7529:   height: 1.1em;
1.1077    raeburn  7530:   margin: 0.2em 0 0 0;
1.693     droeschl 7531: }
                   7532: 
1.897     wenzelju 7533: ol.LC_primary_menu a {
1.911     bisitz   7534:   color: RGB(80, 80, 80);
                   7535:   text-decoration: none;
1.693     droeschl 7536: }
1.795     www      7537: 
1.949     droeschl 7538: ol.LC_primary_menu a.LC_new_message {
                   7539:   font-weight:bold;
                   7540:   color: darkred;
                   7541: }
                   7542: 
1.975     raeburn  7543: ol.LC_docs_parameters {
                   7544:   margin-left: 0;
                   7545:   padding: 0;
                   7546:   list-style: none;
                   7547: }
                   7548: 
                   7549: ol.LC_docs_parameters li {
                   7550:   margin: 0;
                   7551:   padding-right: 20px;
                   7552:   display: inline;
                   7553: }
                   7554: 
1.976     raeburn  7555: ol.LC_docs_parameters li:before {
                   7556:   content: "\\002022 \\0020";
                   7557: }
                   7558: 
                   7559: li.LC_docs_parameters_title {
                   7560:   font-weight: bold;
                   7561: }
                   7562: 
                   7563: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7564:   content: "";
                   7565: }
                   7566: 
1.897     wenzelju 7567: ul#LC_secondary_menu {
1.1107    raeburn  7568:   clear: right;
1.911     bisitz   7569:   color: $fontmenu;
                   7570:   background: $tabbg;
                   7571:   list-style: none;
                   7572:   padding: 0;
                   7573:   margin: 0;
                   7574:   width: 100%;
1.995     raeburn  7575:   text-align: left;
1.1107    raeburn  7576:   float: left;
1.808     droeschl 7577: }
                   7578: 
1.897     wenzelju 7579: ul#LC_secondary_menu li {
1.911     bisitz   7580:   font-weight: bold;
                   7581:   line-height: 1.8em;
1.1107    raeburn  7582:   border-right: 1px solid black;
                   7583:   float: left;
                   7584: }
                   7585: 
                   7586: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7587:   background-color: $data_table_light;
                   7588: }
                   7589: 
                   7590: ul#LC_secondary_menu li a {
1.911     bisitz   7591:   padding: 0 0.8em;
1.1107    raeburn  7592: }
                   7593: 
                   7594: ul#LC_secondary_menu li ul {
                   7595:   display: none;
                   7596: }
                   7597: 
                   7598: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7599:   display: block;
                   7600:   position: absolute;
                   7601:   margin: 0;
                   7602:   padding: 0;
                   7603:   list-style:none;
                   7604:   float: none;
                   7605:   background-color: $data_table_light;
                   7606:   z-index: 2;
                   7607:   margin-left: -1px;
                   7608: }
                   7609: 
                   7610: ul#LC_secondary_menu li ul li {
                   7611:   font-size: 90%;
                   7612:   vertical-align: top;
                   7613:   border-left: 1px solid black;
1.911     bisitz   7614:   border-right: 1px solid black;
1.1119    raeburn  7615:   background-color: $data_table_light;
1.1107    raeburn  7616:   list-style:none;
                   7617:   float: none;
                   7618: }
                   7619: 
                   7620: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7621:   background-color: $data_table_dark;
1.807     droeschl 7622: }
                   7623: 
1.847     tempelho 7624: ul.LC_TabContent {
1.911     bisitz   7625:   display:block;
                   7626:   background: $sidebg;
                   7627:   border-bottom: solid 1px $lg_border_color;
                   7628:   list-style:none;
1.1020    raeburn  7629:   margin: -1px -10px 0 -10px;
1.911     bisitz   7630:   padding: 0;
1.693     droeschl 7631: }
                   7632: 
1.795     www      7633: ul.LC_TabContent li,
                   7634: ul.LC_TabContentBigger li {
1.911     bisitz   7635:   float:left;
1.741     harmsja  7636: }
1.795     www      7637: 
1.897     wenzelju 7638: ul#LC_secondary_menu li a {
1.911     bisitz   7639:   color: $fontmenu;
                   7640:   text-decoration: none;
1.693     droeschl 7641: }
1.795     www      7642: 
1.721     harmsja  7643: ul.LC_TabContent {
1.952     onken    7644:   min-height:20px;
1.721     harmsja  7645: }
1.795     www      7646: 
                   7647: ul.LC_TabContent li {
1.911     bisitz   7648:   vertical-align:middle;
1.959     onken    7649:   padding: 0 16px 0 10px;
1.911     bisitz   7650:   background-color:$tabbg;
                   7651:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7652:   border-left: solid 1px $font;
1.721     harmsja  7653: }
1.795     www      7654: 
1.847     tempelho 7655: ul.LC_TabContent .right {
1.911     bisitz   7656:   float:right;
1.847     tempelho 7657: }
                   7658: 
1.911     bisitz   7659: ul.LC_TabContent li a,
                   7660: ul.LC_TabContent li {
                   7661:   color:rgb(47,47,47);
                   7662:   text-decoration:none;
                   7663:   font-size:95%;
                   7664:   font-weight:bold;
1.952     onken    7665:   min-height:20px;
                   7666: }
                   7667: 
1.959     onken    7668: ul.LC_TabContent li a:hover,
                   7669: ul.LC_TabContent li a:focus {
1.952     onken    7670:   color: $button_hover;
1.959     onken    7671:   background:none;
                   7672:   outline:none;
1.952     onken    7673: }
                   7674: 
                   7675: ul.LC_TabContent li:hover {
                   7676:   color: $button_hover;
                   7677:   cursor:pointer;
1.721     harmsja  7678: }
1.795     www      7679: 
1.911     bisitz   7680: ul.LC_TabContent li.active {
1.952     onken    7681:   color: $font;
1.911     bisitz   7682:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7683:   border-bottom:solid 1px #FFFFFF;
                   7684:   cursor: default;
1.744     ehlerst  7685: }
1.795     www      7686: 
1.959     onken    7687: ul.LC_TabContent li.active a {
                   7688:   color:$font;
                   7689:   background:#FFFFFF;
                   7690:   outline: none;
                   7691: }
1.1047    raeburn  7692: 
                   7693: ul.LC_TabContent li.goback {
                   7694:   float: left;
                   7695:   border-left: none;
                   7696: }
                   7697: 
1.870     tempelho 7698: #maincoursedoc {
1.911     bisitz   7699:   clear:both;
1.870     tempelho 7700: }
                   7701: 
                   7702: ul.LC_TabContentBigger {
1.911     bisitz   7703:   display:block;
                   7704:   list-style:none;
                   7705:   padding: 0;
1.870     tempelho 7706: }
                   7707: 
1.795     www      7708: ul.LC_TabContentBigger li {
1.911     bisitz   7709:   vertical-align:bottom;
                   7710:   height: 30px;
                   7711:   font-size:110%;
                   7712:   font-weight:bold;
                   7713:   color: #737373;
1.841     tempelho 7714: }
                   7715: 
1.957     onken    7716: ul.LC_TabContentBigger li.active {
                   7717:   position: relative;
                   7718:   top: 1px;
                   7719: }
                   7720: 
1.870     tempelho 7721: ul.LC_TabContentBigger li a {
1.911     bisitz   7722:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7723:   height: 30px;
                   7724:   line-height: 30px;
                   7725:   text-align: center;
                   7726:   display: block;
                   7727:   text-decoration: none;
1.958     onken    7728:   outline: none;  
1.741     harmsja  7729: }
1.795     www      7730: 
1.870     tempelho 7731: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7732:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7733:   color:$font;
1.744     ehlerst  7734: }
1.795     www      7735: 
1.870     tempelho 7736: ul.LC_TabContentBigger li b {
1.911     bisitz   7737:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7738:   display: block;
                   7739:   float: left;
                   7740:   padding: 0 30px;
1.957     onken    7741:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7742: }
                   7743: 
1.956     onken    7744: ul.LC_TabContentBigger li:hover b {
                   7745:   color:$button_hover;
                   7746: }
                   7747: 
1.870     tempelho 7748: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7749:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7750:   color:$font;
1.957     onken    7751:   border: 0;
1.741     harmsja  7752: }
1.693     droeschl 7753: 
1.870     tempelho 7754: 
1.862     bisitz   7755: ul.LC_CourseBreadcrumbs {
                   7756:   background: $sidebg;
1.1020    raeburn  7757:   height: 2em;
1.862     bisitz   7758:   padding-left: 10px;
1.1020    raeburn  7759:   margin: 0;
1.862     bisitz   7760:   list-style-position: inside;
                   7761: }
                   7762: 
1.911     bisitz   7763: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7764: ol#LC_PathBreadcrumbs {
1.911     bisitz   7765:   padding-left: 10px;
                   7766:   margin: 0;
1.933     droeschl 7767:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7768: }
                   7769: 
1.911     bisitz   7770: ol#LC_MenuBreadcrumbs li,
                   7771: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7772: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7773:   display: inline;
1.933     droeschl 7774:   white-space: normal;  
1.693     droeschl 7775: }
                   7776: 
1.823     bisitz   7777: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7778: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7779:   text-decoration: none;
                   7780:   font-size:90%;
1.693     droeschl 7781: }
1.795     www      7782: 
1.969     droeschl 7783: ol#LC_MenuBreadcrumbs h1 {
                   7784:   display: inline;
                   7785:   font-size: 90%;
                   7786:   line-height: 2.5em;
                   7787:   margin: 0;
                   7788:   padding: 0;
                   7789: }
                   7790: 
1.795     www      7791: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7792:   text-decoration:none;
                   7793:   font-size:100%;
                   7794:   font-weight:bold;
1.693     droeschl 7795: }
1.795     www      7796: 
1.840     bisitz   7797: .LC_Box {
1.911     bisitz   7798:   border: solid 1px $lg_border_color;
                   7799:   padding: 0 10px 10px 10px;
1.746     neumanie 7800: }
1.795     www      7801: 
1.1020    raeburn  7802: .LC_DocsBox {
                   7803:   border: solid 1px $lg_border_color;
                   7804:   padding: 0 0 10px 10px;
                   7805: }
                   7806: 
1.795     www      7807: .LC_AboutMe_Image {
1.911     bisitz   7808:   float:left;
                   7809:   margin-right:10px;
1.747     neumanie 7810: }
1.795     www      7811: 
                   7812: .LC_Clear_AboutMe_Image {
1.911     bisitz   7813:   clear:left;
1.747     neumanie 7814: }
1.795     www      7815: 
1.721     harmsja  7816: dl.LC_ListStyleClean dt {
1.911     bisitz   7817:   padding-right: 5px;
                   7818:   display: table-header-group;
1.693     droeschl 7819: }
                   7820: 
1.721     harmsja  7821: dl.LC_ListStyleClean dd {
1.911     bisitz   7822:   display: table-row;
1.693     droeschl 7823: }
                   7824: 
1.721     harmsja  7825: .LC_ListStyleClean,
                   7826: .LC_ListStyleSimple,
                   7827: .LC_ListStyleNormal,
1.795     www      7828: .LC_ListStyleSpecial {
1.911     bisitz   7829:   /* display:block; */
                   7830:   list-style-position: inside;
                   7831:   list-style-type: none;
                   7832:   overflow: hidden;
                   7833:   padding: 0;
1.693     droeschl 7834: }
                   7835: 
1.721     harmsja  7836: .LC_ListStyleSimple li,
                   7837: .LC_ListStyleSimple dd,
                   7838: .LC_ListStyleNormal li,
                   7839: .LC_ListStyleNormal dd,
                   7840: .LC_ListStyleSpecial li,
1.795     www      7841: .LC_ListStyleSpecial dd {
1.911     bisitz   7842:   margin: 0;
                   7843:   padding: 5px 5px 5px 10px;
                   7844:   clear: both;
1.693     droeschl 7845: }
                   7846: 
1.721     harmsja  7847: .LC_ListStyleClean li,
                   7848: .LC_ListStyleClean dd {
1.911     bisitz   7849:   padding-top: 0;
                   7850:   padding-bottom: 0;
1.693     droeschl 7851: }
                   7852: 
1.721     harmsja  7853: .LC_ListStyleSimple dd,
1.795     www      7854: .LC_ListStyleSimple li {
1.911     bisitz   7855:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7856: }
                   7857: 
1.721     harmsja  7858: .LC_ListStyleSpecial li,
                   7859: .LC_ListStyleSpecial dd {
1.911     bisitz   7860:   list-style-type: none;
                   7861:   background-color: RGB(220, 220, 220);
                   7862:   margin-bottom: 4px;
1.693     droeschl 7863: }
                   7864: 
1.721     harmsja  7865: table.LC_SimpleTable {
1.911     bisitz   7866:   margin:5px;
                   7867:   border:solid 1px $lg_border_color;
1.795     www      7868: }
1.693     droeschl 7869: 
1.721     harmsja  7870: table.LC_SimpleTable tr {
1.911     bisitz   7871:   padding: 0;
                   7872:   border:solid 1px $lg_border_color;
1.693     droeschl 7873: }
1.795     www      7874: 
                   7875: table.LC_SimpleTable thead {
1.911     bisitz   7876:   background:rgb(220,220,220);
1.693     droeschl 7877: }
                   7878: 
1.721     harmsja  7879: div.LC_columnSection {
1.911     bisitz   7880:   display: block;
                   7881:   clear: both;
                   7882:   overflow: hidden;
                   7883:   margin: 0;
1.693     droeschl 7884: }
                   7885: 
1.721     harmsja  7886: div.LC_columnSection>* {
1.911     bisitz   7887:   float: left;
                   7888:   margin: 10px 20px 10px 0;
                   7889:   overflow:hidden;
1.693     droeschl 7890: }
1.721     harmsja  7891: 
1.795     www      7892: table em {
1.911     bisitz   7893:   font-weight: bold;
                   7894:   font-style: normal;
1.748     schulted 7895: }
1.795     www      7896: 
1.779     bisitz   7897: table.LC_tableBrowseRes,
1.795     www      7898: table.LC_tableOfContent {
1.911     bisitz   7899:   border:none;
                   7900:   border-spacing: 1px;
                   7901:   padding: 3px;
                   7902:   background-color: #FFFFFF;
                   7903:   font-size: 90%;
1.753     droeschl 7904: }
1.789     droeschl 7905: 
1.911     bisitz   7906: table.LC_tableOfContent {
                   7907:   border-collapse: collapse;
1.789     droeschl 7908: }
                   7909: 
1.771     droeschl 7910: table.LC_tableBrowseRes a,
1.768     schulted 7911: table.LC_tableOfContent a {
1.911     bisitz   7912:   background-color: transparent;
                   7913:   text-decoration: none;
1.753     droeschl 7914: }
                   7915: 
1.795     www      7916: table.LC_tableOfContent img {
1.911     bisitz   7917:   border: none;
                   7918:   height: 1.3em;
                   7919:   vertical-align: text-bottom;
                   7920:   margin-right: 0.3em;
1.753     droeschl 7921: }
1.757     schulted 7922: 
1.795     www      7923: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7924:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7925: }
                   7926: 
1.795     www      7927: a#LC_content_toolbar_everything {
1.911     bisitz   7928:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7929: }
                   7930: 
1.795     www      7931: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7932:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7933: }
                   7934: 
1.795     www      7935: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7936:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7937: }
                   7938: 
1.795     www      7939: a#LC_content_toolbar_changefolder {
1.911     bisitz   7940:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7941: }
                   7942: 
1.795     www      7943: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7944:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7945: }
                   7946: 
1.1043    raeburn  7947: a#LC_content_toolbar_edittoplevel {
                   7948:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7949: }
                   7950: 
1.795     www      7951: ul#LC_toolbar li a:hover {
1.911     bisitz   7952:   background-position: bottom center;
1.757     schulted 7953: }
                   7954: 
1.795     www      7955: ul#LC_toolbar {
1.911     bisitz   7956:   padding: 0;
                   7957:   margin: 2px;
                   7958:   list-style:none;
                   7959:   position:relative;
                   7960:   background-color:white;
1.1082    raeburn  7961:   overflow: auto;
1.757     schulted 7962: }
                   7963: 
1.795     www      7964: ul#LC_toolbar li {
1.911     bisitz   7965:   border:1px solid white;
                   7966:   padding: 0;
                   7967:   margin: 0;
                   7968:   float: left;
                   7969:   display:inline;
                   7970:   vertical-align:middle;
1.1082    raeburn  7971:   white-space: nowrap;
1.911     bisitz   7972: }
1.757     schulted 7973: 
1.783     amueller 7974: 
1.795     www      7975: a.LC_toolbarItem {
1.911     bisitz   7976:   display:block;
                   7977:   padding: 0;
                   7978:   margin: 0;
                   7979:   height: 32px;
                   7980:   width: 32px;
                   7981:   color:white;
                   7982:   border: none;
                   7983:   background-repeat:no-repeat;
                   7984:   background-color:transparent;
1.757     schulted 7985: }
                   7986: 
1.915     droeschl 7987: ul.LC_funclist {
                   7988:     margin: 0;
                   7989:     padding: 0.5em 1em 0.5em 0;
                   7990: }
                   7991: 
1.933     droeschl 7992: ul.LC_funclist > li:first-child {
                   7993:     font-weight:bold; 
                   7994:     margin-left:0.8em;
                   7995: }
                   7996: 
1.915     droeschl 7997: ul.LC_funclist + ul.LC_funclist {
                   7998:     /* 
                   7999:        left border as a seperator if we have more than
                   8000:        one list 
                   8001:     */
                   8002:     border-left: 1px solid $sidebg;
                   8003:     /* 
                   8004:        this hides the left border behind the border of the 
                   8005:        outer box if element is wrapped to the next 'line' 
                   8006:     */
                   8007:     margin-left: -1px;
                   8008: }
                   8009: 
1.843     bisitz   8010: ul.LC_funclist li {
1.915     droeschl 8011:   display: inline;
1.782     bisitz   8012:   white-space: nowrap;
1.915     droeschl 8013:   margin: 0 0 0 25px;
                   8014:   line-height: 150%;
1.782     bisitz   8015: }
                   8016: 
1.974     wenzelju 8017: .LC_hidden {
                   8018:   display: none;
                   8019: }
                   8020: 
1.1030    www      8021: .LCmodal-overlay {
                   8022: 		position:fixed;
                   8023: 		top:0;
                   8024: 		right:0;
                   8025: 		bottom:0;
                   8026: 		left:0;
                   8027: 		height:100%;
                   8028: 		width:100%;
                   8029: 		margin:0;
                   8030: 		padding:0;
                   8031: 		background:#999;
                   8032: 		opacity:.75;
                   8033: 		filter: alpha(opacity=75);
                   8034: 		-moz-opacity: 0.75;
                   8035: 		z-index:101;
                   8036: }
                   8037: 
                   8038: * html .LCmodal-overlay {   
                   8039: 		position: absolute;
                   8040: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8041: }
                   8042: 
                   8043: .LCmodal-window {
                   8044: 		position:fixed;
                   8045: 		top:50%;
                   8046: 		left:50%;
                   8047: 		margin:0;
                   8048: 		padding:0;
                   8049: 		z-index:102;
                   8050: 	}
                   8051: 
                   8052: * html .LCmodal-window {
                   8053: 		position:absolute;
                   8054: }
                   8055: 
                   8056: .LCclose-window {
                   8057: 		position:absolute;
                   8058: 		width:32px;
                   8059: 		height:32px;
                   8060: 		right:8px;
                   8061: 		top:8px;
                   8062: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8063: 		text-indent:-99999px;
                   8064: 		overflow:hidden;
                   8065: 		cursor:pointer;
                   8066: }
                   8067: 
1.1100    raeburn  8068: /*
1.1231    damieng  8069:   styles used for response display
                   8070: */
                   8071: div.LC_radiofoil, div.LC_rankfoil {
                   8072:   margin: .5em 0em .5em 0em;
                   8073: }
                   8074: table.LC_itemgroup {
                   8075:   margin-top: 1em;
                   8076: }
                   8077: 
                   8078: /*
1.1100    raeburn  8079:   styles used by TTH when "Default set of options to pass to tth/m
                   8080:   when converting TeX" in course settings has been set
                   8081: 
                   8082:   option passed: -t
                   8083: 
                   8084: */
                   8085: 
                   8086: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8087: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8088: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8089: td div.norm {line-height:normal;}
                   8090: 
                   8091: /*
                   8092:   option passed -y3
                   8093: */
                   8094: 
                   8095: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8096: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8097: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8098: 
1.1230    damieng  8099: /*
                   8100:   sections with roles, for content only
                   8101: */
                   8102: section[class^="role-"] {
                   8103:   padding-left: 10px;
                   8104:   padding-right: 5px;
                   8105:   margin-top: 8px;
                   8106:   margin-bottom: 8px;
                   8107:   border: 1px solid #2A4;
                   8108:   border-radius: 5px;
                   8109:   box-shadow: 0px 1px 1px #BBB;
                   8110: }
                   8111: section[class^="role-"]>h1 {
                   8112:   position: relative;
                   8113:   margin: 0px;
                   8114:   padding-top: 10px;
                   8115:   padding-left: 40px;
                   8116: }
                   8117: section[class^="role-"]>h1:before {
                   8118:   position: absolute;
                   8119:   left: -5px;
                   8120:   top: 5px;
                   8121: }
                   8122: section.role-activity>h1:before {
                   8123:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8124: }
                   8125: section.role-advice>h1:before {
                   8126:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8127: }
                   8128: section.role-bibliography>h1:before {
                   8129:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8130: }
                   8131: section.role-citation>h1:before {
                   8132:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8133: }
                   8134: section.role-conclusion>h1:before {
                   8135:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8136: }
                   8137: section.role-definition>h1:before {
                   8138:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8139: }
                   8140: section.role-demonstration>h1:before {
                   8141:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8142: }
                   8143: section.role-example>h1:before {
                   8144:   content:url('/adm/daxe/images/section_icons/example.png');
                   8145: }
                   8146: section.role-explanation>h1:before {
                   8147:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8148: }
                   8149: section.role-introduction>h1:before {
                   8150:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8151: }
                   8152: section.role-method>h1:before {
                   8153:   content:url('/adm/daxe/images/section_icons/method.png');
                   8154: }
                   8155: section.role-more_information>h1:before {
                   8156:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8157: }
                   8158: section.role-objectives>h1:before {
                   8159:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8160: }
                   8161: section.role-prerequisites>h1:before {
                   8162:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8163: }
                   8164: section.role-remark>h1:before {
                   8165:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8166: }
                   8167: section.role-reminder>h1:before {
                   8168:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8169: }
                   8170: section.role-summary>h1:before {
                   8171:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8172: }
                   8173: section.role-syntax>h1:before {
                   8174:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8175: }
                   8176: section.role-warning>h1:before {
                   8177:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8178: }
                   8179: 
1.1269    raeburn  8180: #LC_minitab_header {
                   8181:   float:left;
                   8182:   width:100%;
                   8183:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8184:   font-size:93%;
                   8185:   line-height:normal;
                   8186:   margin: 0.5em 0 0.5em 0;
                   8187: }
                   8188: #LC_minitab_header ul {
                   8189:   margin:0;
                   8190:   padding:10px 10px 0;
                   8191:   list-style:none;
                   8192: }
                   8193: #LC_minitab_header li {
                   8194:   float:left;
                   8195:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8196:   margin:0;
                   8197:   padding:0 0 0 9px;
                   8198: }
                   8199: #LC_minitab_header a {
                   8200:   display:block;
                   8201:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8202:   padding:5px 15px 4px 6px;
                   8203: }
                   8204: #LC_minitab_header #LC_current_minitab {
                   8205:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8206: }
                   8207: #LC_minitab_header #LC_current_minitab a {
                   8208:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8209:   padding-bottom:5px;
                   8210: }
                   8211: 
                   8212: 
1.343     albertel 8213: END
                   8214: }
                   8215: 
1.306     albertel 8216: =pod
                   8217: 
                   8218: =item * &headtag()
                   8219: 
                   8220: Returns a uniform footer for LON-CAPA web pages.
                   8221: 
1.307     albertel 8222: Inputs: $title - optional title for the head
                   8223:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8224:         $args - optional arguments
1.319     albertel 8225:             force_register - if is true call registerurl so the remote is 
                   8226:                              informed
1.415     albertel 8227:             redirect       -> array ref of
                   8228:                                    1- seconds before redirect occurs
                   8229:                                    2- url to redirect to
                   8230:                                    3- whether the side effect should occur
1.315     albertel 8231:                            (side effect of setting 
                   8232:                                $env{'internal.head.redirect'} to the url 
                   8233:                                redirected too)
1.352     albertel 8234:             domain         -> force to color decorate a page for a specific
                   8235:                                domain
                   8236:             function       -> force usage of a specific rolish color scheme
                   8237:             bgcolor        -> override the default page bgcolor
1.460     albertel 8238:             no_auto_mt_title
                   8239:                            -> prevent &mt()ing the title arg
1.464     albertel 8240: 
1.306     albertel 8241: =cut
                   8242: 
                   8243: sub headtag {
1.313     albertel 8244:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8245:     
1.363     albertel 8246:     my $function = $args->{'function'} || &get_users_function();
                   8247:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8248:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8249:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8250:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8251: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8252: 		   #time(),
1.418     albertel 8253: 		   $env{'environment.color.timestamp'},
1.363     albertel 8254: 		   $function,$domain,$bgcolor);
                   8255: 
1.369     www      8256:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8257: 
1.308     albertel 8258:     my $result =
                   8259: 	'<head>'.
1.1160    raeburn  8260: 	&font_settings($args);
1.319     albertel 8261: 
1.1188    raeburn  8262:     my $inhibitprint;
                   8263:     if ($args->{'print_suppress'}) {
                   8264:         $inhibitprint = &print_suppression();
                   8265:     }
1.1064    raeburn  8266: 
1.461     albertel 8267:     if (!$args->{'frameset'}) {
                   8268: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8269:     }
1.962     droeschl 8270:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8271:         $result .= Apache::lonxml::display_title();
1.319     albertel 8272:     }
1.436     albertel 8273:     if (!$args->{'no_nav_bar'} 
                   8274: 	&& !$args->{'only_body'}
                   8275: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8276: 	$result .= &help_menu_js($httphost);
1.1032    www      8277:         $result.=&modal_window();
1.1038    www      8278:         $result.=&togglebox_script();
1.1034    www      8279:         $result.=&wishlist_window();
1.1041    www      8280:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8281:     } else {
                   8282:         if ($args->{'add_modal'}) {
                   8283:            $result.=&modal_window();
                   8284:         }
                   8285:         if ($args->{'add_wishlist'}) {
                   8286:            $result.=&wishlist_window();
                   8287:         }
1.1038    www      8288:         if ($args->{'add_togglebox'}) {
                   8289:            $result.=&togglebox_script();
                   8290:         }
1.1041    www      8291:         if ($args->{'add_progressbar'}) {
                   8292:            $result.=&LCprogressbarUpdate_script();
                   8293:         }
1.436     albertel 8294:     }
1.314     albertel 8295:     if (ref($args->{'redirect'})) {
1.414     albertel 8296: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8297: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8298: 	if (!$inhibit_continue) {
                   8299: 	    $env{'internal.head.redirect'} = $url;
                   8300: 	}
1.313     albertel 8301: 	$result.=<<ADDMETA
                   8302: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8303: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8304: ADDMETA
1.1210    raeburn  8305:     } else {
                   8306:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8307:             my $requrl = $env{'request.uri'};
                   8308:             if ($requrl eq '') {
                   8309:                 $requrl = $ENV{'REQUEST_URI'};
                   8310:                 $requrl =~ s/\?.+$//;
                   8311:             }
                   8312:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8313:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8314:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8315:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8316:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8317:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   8318:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8319:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   8320:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   8321:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8322:                             if (($newserver) && ($newserver ne $lonhost)) {
                   8323:                                 my $numsec = 5;
                   8324:                                 my $timeout = $numsec * 1000;
                   8325:                                 my ($newurl,$locknum,%locks,$msg);
                   8326:                                 if ($env{'request.role.adv'}) {
                   8327:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8328:                                 }
                   8329:                                 my $disable_submit = 0;
                   8330:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   8331:                                     $disable_submit = 1;
                   8332:                                 }
                   8333:                                 if ($locknum) {
                   8334:                                     my @lockinfo = sort(values(%locks));
                   8335:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   8336:                                            join(", ",sort(values(%locks)))."\\n".
                   8337:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   8338:                                 } else {
                   8339:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8340:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   8341:                                     }
                   8342:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8343:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8344:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8345:                                         $newurl .= '&role='.$env{'request.role'};
                   8346:                                     }
                   8347:                                     if ($env{'request.symb'}) {
                   8348:                                         $newurl .= '&symb='.$env{'request.symb'};
                   8349:                                     } else {
                   8350:                                         $newurl .= '&origurl='.$requrl;
                   8351:                                     }
                   8352:                                 }
1.1222    damieng  8353:                                 &js_escape(\$msg);
1.1210    raeburn  8354:                                 $result.=<<OFFLOAD
                   8355: <meta http-equiv="pragma" content="no-cache" />
                   8356: <script type="text/javascript">
1.1215    raeburn  8357: // <![CDATA[
1.1210    raeburn  8358: function LC_Offload_Now() {
                   8359:     var dest = "$newurl";
                   8360:     if (dest != '') {
                   8361:         window.location.href="$newurl";
                   8362:     }
                   8363: }
1.1214    raeburn  8364: \$(document).ready(function () {
                   8365:     window.alert('$msg');
                   8366:     if ($disable_submit) {
1.1210    raeburn  8367:         \$(".LC_hwk_submit").prop("disabled", true);
                   8368:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8369:     }
                   8370:     setTimeout('LC_Offload_Now()', $timeout);
                   8371: });
1.1215    raeburn  8372: // ]]>
1.1210    raeburn  8373: </script>
                   8374: OFFLOAD
                   8375:                             }
                   8376:                         }
                   8377:                     }
                   8378:                 }
                   8379:             }
                   8380:         }
1.313     albertel 8381:     }
1.306     albertel 8382:     if (!defined($title)) {
                   8383: 	$title = 'The LearningOnline Network with CAPA';
                   8384:     }
1.460     albertel 8385:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8386:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8387: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8388:     if (!$args->{'frameset'}) {
                   8389:         $result .= ' /';
                   8390:     }
                   8391:     $result .= '>' 
1.1064    raeburn  8392:         .$inhibitprint
1.414     albertel 8393: 	.$head_extra;
1.1242    raeburn  8394:     my $clientmobile;
                   8395:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8396:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8397:     } else {
                   8398:         $clientmobile = $env{'browser.mobile'};
                   8399:     }
                   8400:     if ($clientmobile) {
1.1137    raeburn  8401:         $result .= '
                   8402: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8403: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8404:     }
1.1278    raeburn  8405:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8406:     return $result.'</head>';
1.306     albertel 8407: }
                   8408: 
                   8409: =pod
                   8410: 
1.340     albertel 8411: =item * &font_settings()
                   8412: 
                   8413: Returns neccessary <meta> to set the proper encoding
                   8414: 
1.1160    raeburn  8415: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8416: 
                   8417: =cut
                   8418: 
                   8419: sub font_settings {
1.1160    raeburn  8420:     my ($args) = @_;
1.340     albertel 8421:     my $headerstring='';
1.1160    raeburn  8422:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8423:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8424:         $headerstring.=
                   8425:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8426:         if (!$args->{'frameset'}) {
                   8427: 	    $headerstring.= ' /';
                   8428:         }
                   8429: 	$headerstring .= '>'."\n";
1.340     albertel 8430:     }
                   8431:     return $headerstring;
                   8432: }
                   8433: 
1.341     albertel 8434: =pod
                   8435: 
1.1064    raeburn  8436: =item * &print_suppression()
                   8437: 
                   8438: In course context returns css which causes the body to be blank when media="print",
                   8439: if printout generation is unavailable for the current resource.
                   8440: 
                   8441: This could be because:
                   8442: 
                   8443: (a) printstartdate is in the future
                   8444: 
                   8445: (b) printenddate is in the past
                   8446: 
                   8447: (c) there is an active exam block with "printout"
                   8448: functionality blocked
                   8449: 
                   8450: Users with pav, pfo or evb privileges are exempt.
                   8451: 
                   8452: Inputs: none
                   8453: 
                   8454: =cut
                   8455: 
                   8456: 
                   8457: sub print_suppression {
                   8458:     my $noprint;
                   8459:     if ($env{'request.course.id'}) {
                   8460:         my $scope = $env{'request.course.id'};
                   8461:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8462:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8463:             return;
                   8464:         }
                   8465:         if ($env{'request.course.sec'} ne '') {
                   8466:             $scope .= "/$env{'request.course.sec'}";
                   8467:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8468:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8469:                 return;
1.1064    raeburn  8470:             }
                   8471:         }
                   8472:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8473:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8474:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8475:         if ($blocked) {
                   8476:             my $checkrole = "cm./$cdom/$cnum";
                   8477:             if ($env{'request.course.sec'} ne '') {
                   8478:                 $checkrole .= "/$env{'request.course.sec'}";
                   8479:             }
                   8480:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8481:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8482:                 $noprint = 1;
                   8483:             }
                   8484:         }
                   8485:         unless ($noprint) {
                   8486:             my $symb = &Apache::lonnet::symbread();
                   8487:             if ($symb ne '') {
                   8488:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8489:                 if (ref($navmap)) {
                   8490:                     my $res = $navmap->getBySymb($symb);
                   8491:                     if (ref($res)) {
                   8492:                         if (!$res->resprintable()) {
                   8493:                             $noprint = 1;
                   8494:                         }
                   8495:                     }
                   8496:                 }
                   8497:             }
                   8498:         }
                   8499:         if ($noprint) {
                   8500:             return <<"ENDSTYLE";
                   8501: <style type="text/css" media="print">
                   8502:     body { display:none }
                   8503: </style>
                   8504: ENDSTYLE
                   8505:         }
                   8506:     }
                   8507:     return;
                   8508: }
                   8509: 
                   8510: =pod
                   8511: 
1.341     albertel 8512: =item * &xml_begin()
                   8513: 
                   8514: Returns the needed doctype and <html>
                   8515: 
                   8516: Inputs: none
                   8517: 
                   8518: =cut
                   8519: 
                   8520: sub xml_begin {
1.1168    raeburn  8521:     my ($is_frameset) = @_;
1.341     albertel 8522:     my $output='';
                   8523: 
                   8524:     if ($env{'browser.mathml'}) {
                   8525: 	$output='<?xml version="1.0"?>'
                   8526:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8527: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8528:             
                   8529: #	    .'<!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">] >'
                   8530: 	    .'<!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">'
                   8531:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8532: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8533:     } elsif ($is_frameset) {
                   8534:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8535:                 '<html>'."\n";
1.341     albertel 8536:     } else {
1.1168    raeburn  8537: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8538:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8539:     }
                   8540:     return $output;
                   8541: }
1.340     albertel 8542: 
                   8543: =pod
                   8544: 
1.306     albertel 8545: =item * &start_page()
                   8546: 
                   8547: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8548: 
1.648     raeburn  8549: Inputs:
                   8550: 
                   8551: =over 4
                   8552: 
                   8553: $title - optional title for the page
                   8554: 
                   8555: $head_extra - optional extra HTML to incude inside the <head>
                   8556: 
                   8557: $args - additional optional args supported are:
                   8558: 
                   8559: =over 8
                   8560: 
                   8561:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8562:                                     arg on
1.814     bisitz   8563:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8564:              add_entries    -> additional attributes to add to the  <body>
                   8565:              domain         -> force to color decorate a page for a 
1.317     albertel 8566:                                     specific domain
1.648     raeburn  8567:              function       -> force usage of a specific rolish color
1.317     albertel 8568:                                     scheme
1.648     raeburn  8569:              redirect       -> see &headtag()
                   8570:              bgcolor        -> override the default page bg color
                   8571:              js_ready       -> return a string ready for being used in 
1.317     albertel 8572:                                     a javascript writeln
1.648     raeburn  8573:              html_encode    -> return a string ready for being used in 
1.320     albertel 8574:                                     a html attribute
1.648     raeburn  8575:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8576:                                     $forcereg arg
1.648     raeburn  8577:              frameset       -> if true will start with a <frameset>
1.330     albertel 8578:                                     rather than <body>
1.648     raeburn  8579:              skip_phases    -> hash ref of 
1.338     albertel 8580:                                     head -> skip the <html><head> generation
                   8581:                                     body -> skip all <body> generation
1.648     raeburn  8582:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8583:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8584:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  8585:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8586:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  8587:              group          -> includes the current group, if page is for a 
1.1274    raeburn  8588:                                specific group
                   8589:              use_absolute   -> for request for external resource or syllabus, this
                   8590:                                will contain https://<hostname> if server uses
                   8591:                                https (as per hosts.tab), but request is for http
                   8592:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8593: 
1.648     raeburn  8594: =back
1.460     albertel 8595: 
1.648     raeburn  8596: =back
1.562     albertel 8597: 
1.306     albertel 8598: =cut
                   8599: 
                   8600: sub start_page {
1.309     albertel 8601:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8602:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8603: 
1.315     albertel 8604:     $env{'internal.start_page'}++;
1.1096    raeburn  8605:     my ($result,@advtools);
1.964     droeschl 8606: 
1.338     albertel 8607:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8608:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8609:     }
                   8610:     
                   8611:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8612: 	if ($args->{'frameset'}) {
                   8613: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8614: 						$args->{'add_entries'});
                   8615: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8616:         } else {
                   8617:             $result .=
                   8618:                 &bodytag($title, 
                   8619:                          $args->{'function'},       $args->{'add_entries'},
                   8620:                          $args->{'only_body'},      $args->{'domain'},
                   8621:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8622:                          $args->{'bgcolor'},        $args,
                   8623:                          \@advtools);
1.831     bisitz   8624:         }
1.330     albertel 8625:     }
1.338     albertel 8626: 
1.315     albertel 8627:     if ($args->{'js_ready'}) {
1.713     kaisler  8628: 		$result = &js_ready($result);
1.315     albertel 8629:     }
1.320     albertel 8630:     if ($args->{'html_encode'}) {
1.713     kaisler  8631: 		$result = &html_encode($result);
                   8632:     }
                   8633: 
1.813     bisitz   8634:     # Preparation for new and consistent functionlist at top of screen
                   8635:     # if ($args->{'functionlist'}) {
                   8636:     #            $result .= &build_functionlist();
                   8637:     #}
                   8638: 
1.964     droeschl 8639:     # Don't add anything more if only_body wanted or in const space
                   8640:     return $result if    $args->{'only_body'} 
                   8641:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8642: 
                   8643:     #Breadcrumbs
1.758     kaisler  8644:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8645: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8646: 		#if any br links exists, add them to the breadcrumbs
                   8647: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8648: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8649: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8650: 			}
                   8651: 		}
1.1096    raeburn  8652:                 # if @advtools array contains items add then to the breadcrumbs
                   8653:                 if (@advtools > 0) {
                   8654:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8655:                 }
1.1272    raeburn  8656:                 my $menulink;
                   8657:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8658:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
                   8659:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   8660:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   8661:                      (!$env{'request.role.adv'}))) {
                   8662:                     $menulink = 0;
                   8663:                 } else {
                   8664:                     undef($menulink);
                   8665:                 }
1.758     kaisler  8666: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8667: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  8668: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  8669:                 } else {
1.1272    raeburn  8670: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8671: 		}
1.320     albertel 8672:     }
1.315     albertel 8673:     return $result;
1.306     albertel 8674: }
                   8675: 
                   8676: sub end_page {
1.315     albertel 8677:     my ($args) = @_;
                   8678:     $env{'internal.end_page'}++;
1.330     albertel 8679:     my $result;
1.335     albertel 8680:     if ($args->{'discussion'}) {
                   8681: 	my ($target,$parser);
                   8682: 	if (ref($args->{'discussion'})) {
                   8683: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8684: 				$args->{'discussion'}{'parser'});
                   8685: 	}
                   8686: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8687:     }
1.330     albertel 8688:     if ($args->{'frameset'}) {
                   8689: 	$result .= '</frameset>';
                   8690:     } else {
1.635     raeburn  8691: 	$result .= &endbodytag($args);
1.330     albertel 8692:     }
1.1080    raeburn  8693:     unless ($args->{'notbody'}) {
                   8694:         $result .= "\n</html>";
                   8695:     }
1.330     albertel 8696: 
1.315     albertel 8697:     if ($args->{'js_ready'}) {
1.317     albertel 8698: 	$result = &js_ready($result);
1.315     albertel 8699:     }
1.335     albertel 8700: 
1.320     albertel 8701:     if ($args->{'html_encode'}) {
                   8702: 	$result = &html_encode($result);
                   8703:     }
1.335     albertel 8704: 
1.315     albertel 8705:     return $result;
                   8706: }
                   8707: 
1.1034    www      8708: sub wishlist_window {
                   8709:     return(<<'ENDWISHLIST');
1.1046    raeburn  8710: <script type="text/javascript">
1.1034    www      8711: // <![CDATA[
                   8712: // <!-- BEGIN LON-CAPA Internal
                   8713: function set_wishlistlink(title, path) {
                   8714:     if (!title) {
                   8715:         title = document.title;
                   8716:         title = title.replace(/^LON-CAPA /,'');
                   8717:     }
1.1175    raeburn  8718:     title = encodeURIComponent(title);
1.1203    raeburn  8719:     title = title.replace("'","\\\'");
1.1034    www      8720:     if (!path) {
                   8721:         path = location.pathname;
                   8722:     }
1.1175    raeburn  8723:     path = encodeURIComponent(path);
1.1203    raeburn  8724:     path = path.replace("'","\\\'");
1.1034    www      8725:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8726:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8727: }
                   8728: // END LON-CAPA Internal -->
                   8729: // ]]>
                   8730: </script>
                   8731: ENDWISHLIST
                   8732: }
                   8733: 
1.1030    www      8734: sub modal_window {
                   8735:     return(<<'ENDMODAL');
1.1046    raeburn  8736: <script type="text/javascript">
1.1030    www      8737: // <![CDATA[
                   8738: // <!-- BEGIN LON-CAPA Internal
                   8739: var modalWindow = {
                   8740: 	parent:"body",
                   8741: 	windowId:null,
                   8742: 	content:null,
                   8743: 	width:null,
                   8744: 	height:null,
                   8745: 	close:function()
                   8746: 	{
                   8747: 	        $(".LCmodal-window").remove();
                   8748: 	        $(".LCmodal-overlay").remove();
                   8749: 	},
                   8750: 	open:function()
                   8751: 	{
                   8752: 		var modal = "";
                   8753: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8754: 		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;\">";
                   8755: 		modal += this.content;
                   8756: 		modal += "</div>";	
                   8757: 
                   8758: 		$(this.parent).append(modal);
                   8759: 
                   8760: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8761: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8762: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8763: 	}
                   8764: };
1.1140    raeburn  8765: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8766: 	{
1.1266    raeburn  8767:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8768: 		modalWindow.windowId = "myModal";
                   8769: 		modalWindow.width = width;
                   8770: 		modalWindow.height = height;
1.1196    raeburn  8771: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8772: 		modalWindow.open();
1.1208    raeburn  8773: 	};
1.1030    www      8774: // END LON-CAPA Internal -->
                   8775: // ]]>
                   8776: </script>
                   8777: ENDMODAL
                   8778: }
                   8779: 
                   8780: sub modal_link {
1.1140    raeburn  8781:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8782:     unless ($width) { $width=480; }
                   8783:     unless ($height) { $height=400; }
1.1031    www      8784:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8785:     unless ($transparency) { $transparency='true'; }
                   8786: 
1.1074    raeburn  8787:     my $target_attr;
                   8788:     if (defined($target)) {
                   8789:         $target_attr = 'target="'.$target.'"';
                   8790:     }
                   8791:     return <<"ENDLINK";
1.1140    raeburn  8792: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8793:            $linktext</a>
                   8794: ENDLINK
1.1030    www      8795: }
                   8796: 
1.1032    www      8797: sub modal_adhoc_script {
                   8798:     my ($funcname,$width,$height,$content)=@_;
                   8799:     return (<<ENDADHOC);
1.1046    raeburn  8800: <script type="text/javascript">
1.1032    www      8801: // <![CDATA[
                   8802:         var $funcname = function()
                   8803:         {
                   8804:                 modalWindow.windowId = "myModal";
                   8805:                 modalWindow.width = $width;
                   8806:                 modalWindow.height = $height;
                   8807:                 modalWindow.content = '$content';
                   8808:                 modalWindow.open();
                   8809:         };  
                   8810: // ]]>
                   8811: </script>
                   8812: ENDADHOC
                   8813: }
                   8814: 
1.1041    www      8815: sub modal_adhoc_inner {
                   8816:     my ($funcname,$width,$height,$content)=@_;
                   8817:     my $innerwidth=$width-20;
                   8818:     $content=&js_ready(
1.1140    raeburn  8819:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8820:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8821:                  $content.
1.1041    www      8822:                  &end_scrollbox().
1.1140    raeburn  8823:                  &end_page()
1.1041    www      8824:              );
                   8825:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8826: }
                   8827: 
                   8828: sub modal_adhoc_window {
                   8829:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8830:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8831:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8832: }
                   8833: 
                   8834: sub modal_adhoc_launch {
                   8835:     my ($funcname,$width,$height,$content)=@_;
                   8836:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8837: <script type="text/javascript">
                   8838: // <![CDATA[
                   8839: $funcname();
                   8840: // ]]>
                   8841: </script>
                   8842: ENDLAUNCH
                   8843: }
                   8844: 
                   8845: sub modal_adhoc_close {
                   8846:     return (<<ENDCLOSE);
                   8847: <script type="text/javascript">
                   8848: // <![CDATA[
                   8849: modalWindow.close();
                   8850: // ]]>
                   8851: </script>
                   8852: ENDCLOSE
                   8853: }
                   8854: 
1.1038    www      8855: sub togglebox_script {
                   8856:    return(<<ENDTOGGLE);
                   8857: <script type="text/javascript"> 
                   8858: // <![CDATA[
                   8859: function LCtoggleDisplay(id,hidetext,showtext) {
                   8860:    link = document.getElementById(id + "link").childNodes[0];
                   8861:    with (document.getElementById(id).style) {
                   8862:       if (display == "none" ) {
                   8863:           display = "inline";
                   8864:           link.nodeValue = hidetext;
                   8865:         } else {
                   8866:           display = "none";
                   8867:           link.nodeValue = showtext;
                   8868:        }
                   8869:    }
                   8870: }
                   8871: // ]]>
                   8872: </script>
                   8873: ENDTOGGLE
                   8874: }
                   8875: 
1.1039    www      8876: sub start_togglebox {
                   8877:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8878:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8879:     unless ($showtext) { $showtext=&mt('show'); }
                   8880:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8881:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8882:     return &start_data_table().
                   8883:            &start_data_table_header_row().
                   8884:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8885:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8886:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8887:            &end_data_table_header_row().
                   8888:            '<tr id="'.$id.'" style="display:none""><td>';
                   8889: }
                   8890: 
                   8891: sub end_togglebox {
                   8892:     return '</td></tr>'.&end_data_table();
                   8893: }
                   8894: 
1.1041    www      8895: sub LCprogressbar_script {
1.1302    raeburn  8896:    my ($id,$number_to_do)=@_;
                   8897:    if ($number_to_do) {
                   8898:        return(<<ENDPROGRESS);
1.1041    www      8899: <script type="text/javascript">
                   8900: // <![CDATA[
1.1045    www      8901: \$('#progressbar$id').progressbar({
1.1041    www      8902:   value: 0,
                   8903:   change: function(event, ui) {
                   8904:     var newVal = \$(this).progressbar('option', 'value');
                   8905:     \$('.pblabel', this).text(LCprogressTxt);
                   8906:   }
                   8907: });
                   8908: // ]]>
                   8909: </script>
                   8910: ENDPROGRESS
1.1302    raeburn  8911:    } else {
                   8912:        return(<<ENDPROGRESS);
                   8913: <script type="text/javascript">
                   8914: // <![CDATA[
                   8915: \$('#progressbar$id').progressbar({
                   8916:   value: false,
                   8917:   create: function(event, ui) {
                   8918:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   8919:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   8920:   }
                   8921: });
                   8922: // ]]>
                   8923: </script>
                   8924: ENDPROGRESS
                   8925:    }
1.1041    www      8926: }
                   8927: 
                   8928: sub LCprogressbarUpdate_script {
                   8929:    return(<<ENDPROGRESSUPDATE);
                   8930: <style type="text/css">
                   8931: .ui-progressbar { position:relative; }
1.1302    raeburn  8932: .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      8933: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8934: </style>
                   8935: <script type="text/javascript">
                   8936: // <![CDATA[
1.1045    www      8937: var LCprogressTxt='---';
                   8938: 
1.1302    raeburn  8939: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      8940:    LCprogressTxt=progresstext;
1.1302    raeburn  8941:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   8942:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   8943:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  8944:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   8945:    } else {
                   8946:        \$('#progressbar'+id).progressbar('value',percent);
                   8947:    }
1.1041    www      8948: }
                   8949: // ]]>
                   8950: </script>
                   8951: ENDPROGRESSUPDATE
                   8952: }
                   8953: 
1.1042    www      8954: my $LClastpercent;
1.1045    www      8955: my $LCidcnt;
                   8956: my $LCcurrentid;
1.1042    www      8957: 
1.1041    www      8958: sub LCprogressbar {
1.1302    raeburn  8959:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      8960:     $LClastpercent=0;
1.1045    www      8961:     $LCidcnt++;
                   8962:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  8963:     my ($starting,$content);
                   8964:     if ($number_to_do) {
                   8965:         $starting=&mt('Starting');
                   8966:         $content=(<<ENDPROGBAR);
                   8967: $preamble
1.1045    www      8968:   <div id="progressbar$LCcurrentid">
1.1041    www      8969:     <span class="pblabel">$starting</span>
                   8970:   </div>
                   8971: ENDPROGBAR
1.1302    raeburn  8972:     } else {
                   8973:         $starting=&mt('Loading...');
                   8974:         $LClastpercent='false';
                   8975:         $content=(<<ENDPROGBAR);
                   8976: $preamble
                   8977:   <div id="progressbar$LCcurrentid">
                   8978:       <div class="progress-label">$starting</div>
                   8979:   </div>
                   8980: ENDPROGBAR
                   8981:     }
                   8982:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      8983: }
                   8984: 
                   8985: sub LCprogressbarUpdate {
1.1302    raeburn  8986:     my ($r,$val,$text,$number_to_do)=@_;
                   8987:     if ($number_to_do) {
                   8988:         unless ($val) { 
                   8989:             if ($LClastpercent) {
                   8990:                 $val=$LClastpercent;
                   8991:             } else {
                   8992:                 $val=0;
                   8993:             }
                   8994:         }
                   8995:         if ($val<0) { $val=0; }
                   8996:         if ($val>100) { $val=0; }
                   8997:         $LClastpercent=$val;
                   8998:         unless ($text) { $text=$val.'%'; }
                   8999:     } else {
                   9000:         $val = 'false';
1.1042    www      9001:     }
1.1041    www      9002:     $text=&js_ready($text);
1.1044    www      9003:     &r_print($r,<<ENDUPDATE);
1.1041    www      9004: <script type="text/javascript">
                   9005: // <![CDATA[
1.1302    raeburn  9006: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9007: // ]]>
                   9008: </script>
                   9009: ENDUPDATE
1.1035    www      9010: }
                   9011: 
1.1042    www      9012: sub LCprogressbarClose {
                   9013:     my ($r)=@_;
                   9014:     $LClastpercent=0;
1.1044    www      9015:     &r_print($r,<<ENDCLOSE);
1.1042    www      9016: <script type="text/javascript">
                   9017: // <![CDATA[
1.1045    www      9018: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9019: // ]]>
                   9020: </script>
                   9021: ENDCLOSE
1.1044    www      9022: }
                   9023: 
                   9024: sub r_print {
                   9025:     my ($r,$to_print)=@_;
                   9026:     if ($r) {
                   9027:       $r->print($to_print);
                   9028:       $r->rflush();
                   9029:     } else {
                   9030:       print($to_print);
                   9031:     }
1.1042    www      9032: }
                   9033: 
1.320     albertel 9034: sub html_encode {
                   9035:     my ($result) = @_;
                   9036: 
1.322     albertel 9037:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9038:     
                   9039:     return $result;
                   9040: }
1.1044    www      9041: 
1.317     albertel 9042: sub js_ready {
                   9043:     my ($result) = @_;
                   9044: 
1.323     albertel 9045:     $result =~ s/[\n\r]/ /xmsg;
                   9046:     $result =~ s/\\/\\\\/xmsg;
                   9047:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9048:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9049:     
                   9050:     return $result;
                   9051: }
                   9052: 
1.315     albertel 9053: sub validate_page {
                   9054:     if (  exists($env{'internal.start_page'})
1.316     albertel 9055: 	  &&     $env{'internal.start_page'} > 1) {
                   9056: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9057: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9058: 				 $ENV{'request.filename'});
1.315     albertel 9059:     }
                   9060:     if (  exists($env{'internal.end_page'})
1.316     albertel 9061: 	  &&     $env{'internal.end_page'} > 1) {
                   9062: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9063: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9064: 				 $env{'request.filename'});
1.315     albertel 9065:     }
                   9066:     if (     exists($env{'internal.start_page'})
                   9067: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9068: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9069: 				 $env{'request.filename'});
1.315     albertel 9070:     }
                   9071:     if (   ! exists($env{'internal.start_page'})
                   9072: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9073: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9074: 				 $env{'request.filename'});
1.315     albertel 9075:     }
1.306     albertel 9076: }
1.315     albertel 9077: 
1.996     www      9078: 
                   9079: sub start_scrollbox {
1.1140    raeburn  9080:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9081:     unless ($outerwidth) { $outerwidth='520px'; }
                   9082:     unless ($width) { $width='500px'; }
                   9083:     unless ($height) { $height='200px'; }
1.1075    raeburn  9084:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9085:     if ($id ne '') {
1.1140    raeburn  9086:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9087:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9088:     }
1.1075    raeburn  9089:     if ($bgcolor ne '') {
                   9090:         $tdcol = "background-color: $bgcolor;";
                   9091:     }
1.1137    raeburn  9092:     my $nicescroll_js;
                   9093:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9094:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9095:     }
                   9096:     return <<"END";
                   9097: $nicescroll_js
                   9098: 
                   9099: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9100: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9101: END
                   9102: }
                   9103: 
                   9104: sub end_scrollbox {
                   9105:     return '</div></td></tr></table>';
                   9106: }
                   9107: 
                   9108: sub nicescroll_javascript {
                   9109:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9110:     my %options;
                   9111:     if (ref($cursor) eq 'HASH') {
                   9112:         %options = %{$cursor};
                   9113:     }
                   9114:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9115:         $options{'railalign'} = 'left';
                   9116:     }
                   9117:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9118:         my $function  = &get_users_function();
                   9119:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9120:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9121:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9122:         }
1.1140    raeburn  9123:     }
                   9124:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9125:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9126:             $options{'cursoropacity'}='1.0';
                   9127:         }
1.1140    raeburn  9128:     } else {
                   9129:         $options{'cursoropacity'}='1.0';
                   9130:     }
                   9131:     if ($options{'cursorfixedheight'} eq 'none') {
                   9132:         delete($options{'cursorfixedheight'});
                   9133:     } else {
                   9134:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9135:     }
                   9136:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9137:         delete($options{'railoffset'});
                   9138:     }
                   9139:     my @niceoptions;
                   9140:     while (my($key,$value) = each(%options)) {
                   9141:         if ($value =~ /^\{.+\}$/) {
                   9142:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9143:         } else {
1.1140    raeburn  9144:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9145:         }
1.1140    raeburn  9146:     }
                   9147:     my $nicescroll_js = '
1.1137    raeburn  9148: $(document).ready(
1.1140    raeburn  9149:       function() {
                   9150:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9151:       }
1.1137    raeburn  9152: );
                   9153: ';
1.1140    raeburn  9154:     if ($framecheck) {
                   9155:         $nicescroll_js .= '
                   9156: function expand_div(caller) {
                   9157:     if (top === self) {
                   9158:         document.getElementById("'.$id.'").style.width = "auto";
                   9159:         document.getElementById("'.$id.'").style.height = "auto";
                   9160:     } else {
                   9161:         try {
                   9162:             if (parent.frames) {
                   9163:                 if (parent.frames.length > 1) {
                   9164:                     var framesrc = parent.frames[1].location.href;
                   9165:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9166:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9167:                         document.getElementById("'.$id.'").style.width = "auto";
                   9168:                         document.getElementById("'.$id.'").style.height = "auto";
                   9169:                     }
                   9170:                 }
                   9171:             }
                   9172:         } catch (e) {
                   9173:             return;
                   9174:         }
1.1137    raeburn  9175:     }
1.1140    raeburn  9176:     return;
1.996     www      9177: }
1.1140    raeburn  9178: ';
                   9179:     }
                   9180:     if ($needjsready) {
                   9181:         $nicescroll_js = '
                   9182: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9183:     } else {
                   9184:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9185:     }
                   9186:     return $nicescroll_js;
1.996     www      9187: }
                   9188: 
1.318     albertel 9189: sub simple_error_page {
1.1150    bisitz   9190:     my ($r,$title,$msg,$args) = @_;
1.1304  ! raeburn  9191:     my %displayargs;
1.1151    raeburn  9192:     if (ref($args) eq 'HASH') {
                   9193:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304  ! raeburn  9194:         if ($args->{'only_body'}) {
        !          9195:             $displayargs{'only_body'} = 1;
        !          9196:         }
        !          9197:         if ($args->{'no_nav_bar'}) {
        !          9198:             $displayargs{'no_nav_bar'} = 1;
        !          9199:         }
1.1151    raeburn  9200:     } else {
                   9201:         $msg = &mt($msg);
                   9202:     }
1.1150    bisitz   9203: 
1.318     albertel 9204:     my $page =
1.1304  ! raeburn  9205: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   9206: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9207: 	&Apache::loncommon::end_page();
                   9208:     if (ref($r)) {
                   9209: 	$r->print($page);
1.327     albertel 9210: 	return;
1.318     albertel 9211:     }
                   9212:     return $page;
                   9213: }
1.347     albertel 9214: 
                   9215: {
1.610     albertel 9216:     my @row_count;
1.961     onken    9217: 
                   9218:     sub start_data_table_count {
                   9219:         unshift(@row_count, 0);
                   9220:         return;
                   9221:     }
                   9222: 
                   9223:     sub end_data_table_count {
                   9224:         shift(@row_count);
                   9225:         return;
                   9226:     }
                   9227: 
1.347     albertel 9228:     sub start_data_table {
1.1018    raeburn  9229: 	my ($add_class,$id) = @_;
1.422     albertel 9230: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9231:         my $table_id;
                   9232:         if (defined($id)) {
                   9233:             $table_id = ' id="'.$id.'"';
                   9234:         }
1.961     onken    9235: 	&start_data_table_count();
1.1018    raeburn  9236: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9237:     }
                   9238: 
                   9239:     sub end_data_table {
1.961     onken    9240: 	&end_data_table_count();
1.389     albertel 9241: 	return '</table>'."\n";;
1.347     albertel 9242:     }
                   9243: 
                   9244:     sub start_data_table_row {
1.974     wenzelju 9245: 	my ($add_class, $id) = @_;
1.610     albertel 9246: 	$row_count[0]++;
                   9247: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9248: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9249:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9250:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9251:     }
1.471     banghart 9252:     
                   9253:     sub continue_data_table_row {
1.974     wenzelju 9254: 	my ($add_class, $id) = @_;
1.610     albertel 9255: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9256: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9257:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9258:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9259:     }
1.347     albertel 9260: 
                   9261:     sub end_data_table_row {
1.389     albertel 9262: 	return '</tr>'."\n";;
1.347     albertel 9263:     }
1.367     www      9264: 
1.421     albertel 9265:     sub start_data_table_empty_row {
1.707     bisitz   9266: #	$row_count[0]++;
1.421     albertel 9267: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9268:     }
                   9269: 
                   9270:     sub end_data_table_empty_row {
                   9271: 	return '</tr>'."\n";;
                   9272:     }
                   9273: 
1.367     www      9274:     sub start_data_table_header_row {
1.389     albertel 9275: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9276:     }
                   9277: 
                   9278:     sub end_data_table_header_row {
1.389     albertel 9279: 	return '</tr>'."\n";;
1.367     www      9280:     }
1.890     droeschl 9281: 
                   9282:     sub data_table_caption {
                   9283:         my $caption = shift;
                   9284:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9285:     }
1.347     albertel 9286: }
                   9287: 
1.548     albertel 9288: =pod
                   9289: 
                   9290: =item * &inhibit_menu_check($arg)
                   9291: 
                   9292: Checks for a inhibitmenu state and generates output to preserve it
                   9293: 
                   9294: Inputs:         $arg - can be any of
                   9295:                      - undef - in which case the return value is a string 
                   9296:                                to add  into arguments list of a uri
                   9297:                      - 'input' - in which case the return value is a HTML
                   9298:                                  <form> <input> field of type hidden to
                   9299:                                  preserve the value
                   9300:                      - a url - in which case the return value is the url with
                   9301:                                the neccesary cgi args added to preserve the
                   9302:                                inhibitmenu state
                   9303:                      - a ref to a url - no return value, but the string is
                   9304:                                         updated to include the neccessary cgi
                   9305:                                         args to preserve the inhibitmenu state
                   9306: 
                   9307: =cut
                   9308: 
                   9309: sub inhibit_menu_check {
                   9310:     my ($arg) = @_;
                   9311:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9312:     if ($arg eq 'input') {
                   9313: 	if ($env{'form.inhibitmenu'}) {
                   9314: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9315: 	} else {
                   9316: 	    return
                   9317: 	}
                   9318:     }
                   9319:     if ($env{'form.inhibitmenu'}) {
                   9320: 	if (ref($arg)) {
                   9321: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9322: 	} elsif ($arg eq '') {
                   9323: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9324: 	} else {
                   9325: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9326: 	}
                   9327:     }
                   9328:     if (!ref($arg)) {
                   9329: 	return $arg;
                   9330:     }
                   9331: }
                   9332: 
1.251     albertel 9333: ###############################################
1.182     matthew  9334: 
                   9335: =pod
                   9336: 
1.549     albertel 9337: =back
                   9338: 
                   9339: =head1 User Information Routines
                   9340: 
                   9341: =over 4
                   9342: 
1.405     albertel 9343: =item * &get_users_function()
1.182     matthew  9344: 
                   9345: Used by &bodytag to determine the current users primary role.
                   9346: Returns either 'student','coordinator','admin', or 'author'.
                   9347: 
                   9348: =cut
                   9349: 
                   9350: ###############################################
                   9351: sub get_users_function {
1.815     tempelho 9352:     my $function = 'norole';
1.818     tempelho 9353:     if ($env{'request.role'}=~/^(st)/) {
                   9354:         $function='student';
                   9355:     }
1.907     raeburn  9356:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9357:         $function='coordinator';
                   9358:     }
1.258     albertel 9359:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9360:         $function='admin';
                   9361:     }
1.826     bisitz   9362:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9363:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9364:         $function='author';
                   9365:     }
                   9366:     return $function;
1.54      www      9367: }
1.99      www      9368: 
                   9369: ###############################################
                   9370: 
1.233     raeburn  9371: =pod
                   9372: 
1.821     raeburn  9373: =item * &show_course()
                   9374: 
                   9375: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9376: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9377: 
                   9378: Inputs:
                   9379: None
                   9380: 
                   9381: Outputs:
                   9382: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9383: 
                   9384: =cut
                   9385: 
                   9386: ###############################################
                   9387: sub show_course {
                   9388:     my $course = !$env{'user.adv'};
                   9389:     if (!$env{'user.adv'}) {
                   9390:         foreach my $env (keys(%env)) {
                   9391:             next if ($env !~ m/^user\.priv\./);
                   9392:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9393:                 $course = 0;
                   9394:                 last;
                   9395:             }
                   9396:         }
                   9397:     }
                   9398:     return $course;
                   9399: }
                   9400: 
                   9401: ###############################################
                   9402: 
                   9403: =pod
                   9404: 
1.542     raeburn  9405: =item * &check_user_status()
1.274     raeburn  9406: 
                   9407: Determines current status of supplied role for a
                   9408: specific user. Roles can be active, previous or future.
                   9409: 
                   9410: Inputs: 
                   9411: user's domain, user's username, course's domain,
1.375     raeburn  9412: course's number, optional section ID.
1.274     raeburn  9413: 
                   9414: Outputs:
                   9415: role status: active, previous or future. 
                   9416: 
                   9417: =cut
                   9418: 
                   9419: sub check_user_status {
1.412     raeburn  9420:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9421:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9422:     my @uroles = keys(%userinfo);
1.274     raeburn  9423:     my $srchstr;
                   9424:     my $active_chk = 'none';
1.412     raeburn  9425:     my $now = time;
1.274     raeburn  9426:     if (@uroles > 0) {
1.908     raeburn  9427:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9428:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9429:         } else {
1.412     raeburn  9430:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9431:         }
                   9432:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9433:             my $role_end = 0;
                   9434:             my $role_start = 0;
                   9435:             $active_chk = 'active';
1.412     raeburn  9436:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9437:                 $role_end = $1;
                   9438:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9439:                     $role_start = $1;
1.274     raeburn  9440:                 }
                   9441:             }
                   9442:             if ($role_start > 0) {
1.412     raeburn  9443:                 if ($now < $role_start) {
1.274     raeburn  9444:                     $active_chk = 'future';
                   9445:                 }
                   9446:             }
                   9447:             if ($role_end > 0) {
1.412     raeburn  9448:                 if ($now > $role_end) {
1.274     raeburn  9449:                     $active_chk = 'previous';
                   9450:                 }
                   9451:             }
                   9452:         }
                   9453:     }
                   9454:     return $active_chk;
                   9455: }
                   9456: 
                   9457: ###############################################
                   9458: 
                   9459: =pod
                   9460: 
1.405     albertel 9461: =item * &get_sections()
1.233     raeburn  9462: 
                   9463: Determines all the sections for a course including
                   9464: sections with students and sections containing other roles.
1.419     raeburn  9465: Incoming parameters: 
                   9466: 
                   9467: 1. domain
                   9468: 2. course number 
                   9469: 3. reference to array containing roles for which sections should 
                   9470: be gathered (optional).
                   9471: 4. reference to array containing status types for which sections 
                   9472: should be gathered (optional).
                   9473: 
                   9474: If the third argument is undefined, sections are gathered for any role. 
                   9475: If the fourth argument is undefined, sections are gathered for any status.
                   9476: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9477:  
1.374     raeburn  9478: Returns section hash (keys are section IDs, values are
                   9479: number of users in each section), subject to the
1.419     raeburn  9480: optional roles filter, optional status filter 
1.233     raeburn  9481: 
                   9482: =cut
                   9483: 
                   9484: ###############################################
                   9485: sub get_sections {
1.419     raeburn  9486:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9487:     if (!defined($cdom) || !defined($cnum)) {
                   9488:         my $cid =  $env{'request.course.id'};
                   9489: 
                   9490: 	return if (!defined($cid));
                   9491: 
                   9492:         $cdom = $env{'course.'.$cid.'.domain'};
                   9493:         $cnum = $env{'course.'.$cid.'.num'};
                   9494:     }
                   9495: 
                   9496:     my %sectioncount;
1.419     raeburn  9497:     my $now = time;
1.240     albertel 9498: 
1.1118    raeburn  9499:     my $check_students = 1;
                   9500:     my $only_students = 0;
                   9501:     if (ref($possible_roles) eq 'ARRAY') {
                   9502:         if (grep(/^st$/,@{$possible_roles})) {
                   9503:             if (@{$possible_roles} == 1) {
                   9504:                 $only_students = 1;
                   9505:             }
                   9506:         } else {
                   9507:             $check_students = 0;
                   9508:         }
                   9509:     }
                   9510: 
                   9511:     if ($check_students) { 
1.276     albertel 9512: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9513: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9514: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9515:         my $start_index = &Apache::loncoursedata::CL_START();
                   9516:         my $end_index = &Apache::loncoursedata::CL_END();
                   9517:         my $status;
1.366     albertel 9518: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9519: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9520: 				                     $data->[$status_index],
                   9521:                                                      $data->[$start_index],
                   9522:                                                      $data->[$end_index]);
                   9523:             if ($stu_status eq 'Active') {
                   9524:                 $status = 'active';
                   9525:             } elsif ($end < $now) {
                   9526:                 $status = 'previous';
                   9527:             } elsif ($start > $now) {
                   9528:                 $status = 'future';
                   9529:             } 
                   9530: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9531:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9532:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9533: 		    $sectioncount{$section}++;
                   9534:                 }
1.240     albertel 9535: 	    }
                   9536: 	}
                   9537:     }
1.1118    raeburn  9538:     if ($only_students) {
                   9539:         return %sectioncount;
                   9540:     }
1.240     albertel 9541:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9542:     foreach my $user (sort(keys(%courseroles))) {
                   9543: 	if ($user !~ /^(\w{2})/) { next; }
                   9544: 	my ($role) = ($user =~ /^(\w{2})/);
                   9545: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9546: 	my ($section,$status);
1.240     albertel 9547: 	if ($role eq 'cr' &&
                   9548: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9549: 	    $section=$1;
                   9550: 	}
                   9551: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9552: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9553:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9554:         if ($end == -1 && $start == -1) {
                   9555:             next; #deleted role
                   9556:         }
                   9557:         if (!defined($possible_status)) { 
                   9558:             $sectioncount{$section}++;
                   9559:         } else {
                   9560:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9561:                 $status = 'active';
                   9562:             } elsif ($end < $now) {
                   9563:                 $status = 'future';
                   9564:             } elsif ($start > $now) {
                   9565:                 $status = 'previous';
                   9566:             }
                   9567:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9568:                 $sectioncount{$section}++;
                   9569:             }
                   9570:         }
1.233     raeburn  9571:     }
1.366     albertel 9572:     return %sectioncount;
1.233     raeburn  9573: }
                   9574: 
1.274     raeburn  9575: ###############################################
1.294     raeburn  9576: 
                   9577: =pod
1.405     albertel 9578: 
                   9579: =item * &get_course_users()
                   9580: 
1.275     raeburn  9581: Retrieves usernames:domains for users in the specified course
                   9582: with specific role(s), and access status. 
                   9583: 
                   9584: Incoming parameters:
1.277     albertel 9585: 1. course domain
                   9586: 2. course number
                   9587: 3. access status: users must have - either active, 
1.275     raeburn  9588: previous, future, or all.
1.277     albertel 9589: 4. reference to array of permissible roles
1.288     raeburn  9590: 5. reference to array of section restrictions (optional)
                   9591: 6. reference to results object (hash of hashes).
                   9592: 7. reference to optional userdata hash
1.609     raeburn  9593: 8. reference to optional statushash
1.630     raeburn  9594: 9. flag if privileged users (except those set to unhide in
                   9595:    course settings) should be excluded    
1.609     raeburn  9596: Keys of top level results hash are roles.
1.275     raeburn  9597: Keys of inner hashes are username:domain, with 
                   9598: values set to access type.
1.288     raeburn  9599: Optional userdata hash returns an array with arguments in the 
                   9600: same order as loncoursedata::get_classlist() for student data.
                   9601: 
1.609     raeburn  9602: Optional statushash returns
                   9603: 
1.288     raeburn  9604: Entries for end, start, section and status are blank because
                   9605: of the possibility of multiple values for non-student roles.
                   9606: 
1.275     raeburn  9607: =cut
1.405     albertel 9608: 
1.275     raeburn  9609: ###############################################
1.405     albertel 9610: 
1.275     raeburn  9611: sub get_course_users {
1.630     raeburn  9612:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9613:     my %idx = ();
1.419     raeburn  9614:     my %seclists;
1.288     raeburn  9615: 
                   9616:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9617:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9618:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9619:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9620:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9621:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9622:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9623:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9624: 
1.290     albertel 9625:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9626:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9627:         my $now = time;
1.277     albertel 9628:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9629:             my $match = 0;
1.412     raeburn  9630:             my $secmatch = 0;
1.419     raeburn  9631:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9632:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9633:             if ($section eq '') {
                   9634:                 $section = 'none';
                   9635:             }
1.291     albertel 9636:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9637:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9638:                     $secmatch = 1;
                   9639:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9640:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9641:                         $secmatch = 1;
                   9642:                     }
                   9643:                 } else {  
1.419     raeburn  9644: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9645: 		        $secmatch = 1;
                   9646:                     }
1.290     albertel 9647: 		}
1.412     raeburn  9648:                 if (!$secmatch) {
                   9649:                     next;
                   9650:                 }
1.419     raeburn  9651:             }
1.275     raeburn  9652:             if (defined($$types{'active'})) {
1.288     raeburn  9653:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9654:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9655:                     $match = 1;
1.275     raeburn  9656:                 }
                   9657:             }
                   9658:             if (defined($$types{'previous'})) {
1.609     raeburn  9659:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9660:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9661:                     $match = 1;
1.275     raeburn  9662:                 }
                   9663:             }
                   9664:             if (defined($$types{'future'})) {
1.609     raeburn  9665:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9666:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9667:                     $match = 1;
1.275     raeburn  9668:                 }
                   9669:             }
1.609     raeburn  9670:             if ($match) {
                   9671:                 push(@{$seclists{$student}},$section);
                   9672:                 if (ref($userdata) eq 'HASH') {
                   9673:                     $$userdata{$student} = $$classlist{$student};
                   9674:                 }
                   9675:                 if (ref($statushash) eq 'HASH') {
                   9676:                     $statushash->{$student}{'st'}{$section} = $status;
                   9677:                 }
1.288     raeburn  9678:             }
1.275     raeburn  9679:         }
                   9680:     }
1.412     raeburn  9681:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9682:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9683:         my $now = time;
1.609     raeburn  9684:         my %displaystatus = ( previous => 'Expired',
                   9685:                               active   => 'Active',
                   9686:                               future   => 'Future',
                   9687:                             );
1.1121    raeburn  9688:         my (%nothide,@possdoms);
1.630     raeburn  9689:         if ($hidepriv) {
                   9690:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9691:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9692:                 if ($user !~ /:/) {
                   9693:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9694:                 } else {
                   9695:                     $nothide{$user} = 1;
                   9696:                 }
                   9697:             }
1.1121    raeburn  9698:             my @possdoms = ($cdom);
                   9699:             if ($coursehash{'checkforpriv'}) {
                   9700:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9701:             }
1.630     raeburn  9702:         }
1.439     raeburn  9703:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9704:             my $match = 0;
1.412     raeburn  9705:             my $secmatch = 0;
1.439     raeburn  9706:             my $status;
1.412     raeburn  9707:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9708:             $user =~ s/:$//;
1.439     raeburn  9709:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9710:             if ($end == -1 || $start == -1) {
                   9711:                 next;
                   9712:             }
                   9713:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9714:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9715:                 my ($uname,$udom) = split(/:/,$user);
                   9716:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9717:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9718:                         $secmatch = 1;
                   9719:                     } elsif ($usec eq '') {
1.420     albertel 9720:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9721:                             $secmatch = 1;
                   9722:                         }
                   9723:                     } else {
                   9724:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9725:                             $secmatch = 1;
                   9726:                         }
                   9727:                     }
                   9728:                     if (!$secmatch) {
                   9729:                         next;
                   9730:                     }
1.288     raeburn  9731:                 }
1.419     raeburn  9732:                 if ($usec eq '') {
                   9733:                     $usec = 'none';
                   9734:                 }
1.275     raeburn  9735:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9736:                     if ($hidepriv) {
1.1121    raeburn  9737:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9738:                             (!$nothide{$uname.':'.$udom})) {
                   9739:                             next;
                   9740:                         }
                   9741:                     }
1.503     raeburn  9742:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9743:                         $status = 'previous';
                   9744:                     } elsif ($start > $now) {
                   9745:                         $status = 'future';
                   9746:                     } else {
                   9747:                         $status = 'active';
                   9748:                     }
1.277     albertel 9749:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9750:                         if ($status eq $type) {
1.420     albertel 9751:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9752:                                 push(@{$$users{$role}{$user}},$type);
                   9753:                             }
1.288     raeburn  9754:                             $match = 1;
                   9755:                         }
                   9756:                     }
1.419     raeburn  9757:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9758:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9759: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9760:                         }
1.420     albertel 9761:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9762:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9763:                         }
1.609     raeburn  9764:                         if (ref($statushash) eq 'HASH') {
                   9765:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9766:                         }
1.275     raeburn  9767:                     }
                   9768:                 }
                   9769:             }
                   9770:         }
1.290     albertel 9771:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9772:             if ((defined($cdom)) && (defined($cnum))) {
                   9773:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9774:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9775:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9776:                     next if ($owner eq '');
                   9777:                     my ($ownername,$ownerdom);
                   9778:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9779:                         $ownername = $1;
                   9780:                         $ownerdom = $2;
                   9781:                     } else {
                   9782:                         $ownername = $owner;
                   9783:                         $ownerdom = $cdom;
                   9784:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9785:                     }
                   9786:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9787:                     if (defined($userdata) && 
1.609     raeburn  9788: 			!exists($$userdata{$owner})) {
                   9789: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9790:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9791:                             push(@{$seclists{$owner}},'none');
                   9792:                         }
                   9793:                         if (ref($statushash) eq 'HASH') {
                   9794:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9795:                         }
1.290     albertel 9796: 		    }
1.279     raeburn  9797:                 }
                   9798:             }
                   9799:         }
1.419     raeburn  9800:         foreach my $user (keys(%seclists)) {
                   9801:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9802:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9803:         }
1.275     raeburn  9804:     }
                   9805:     return;
                   9806: }
                   9807: 
1.288     raeburn  9808: sub get_user_info {
                   9809:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9810:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9811: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9812:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9813:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9814:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9815:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9816:     return;
                   9817: }
1.275     raeburn  9818: 
1.472     raeburn  9819: ###############################################
                   9820: 
                   9821: =pod
                   9822: 
                   9823: =item * &get_user_quota()
                   9824: 
1.1134    raeburn  9825: Retrieves quota assigned for storage of user files.
                   9826: Default is to report quota for portfolio files.
1.472     raeburn  9827: 
                   9828: Incoming parameters:
                   9829: 1. user's username
                   9830: 2. user's domain
1.1134    raeburn  9831: 3. quota name - portfolio, author, or course
1.1136    raeburn  9832:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  9833: 4. crstype - official, unofficial, textbook, placement or community, 
                   9834:    if quota name is course
1.472     raeburn  9835: 
                   9836: Returns:
1.1163    raeburn  9837: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9838: 2. (Optional) Type of setting: custom or default
                   9839:    (individually assigned or default for user's 
                   9840:    institutional status).
                   9841: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9842:    or student - types as defined in localenroll::inst_usertypes 
                   9843:    for user's domain, which determines default quota for user.
                   9844: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9845: 
                   9846: If a value has been stored in the user's environment, 
1.536     raeburn  9847: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9848: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9849: 
                   9850: =cut
                   9851: 
                   9852: ###############################################
                   9853: 
                   9854: 
                   9855: sub get_user_quota {
1.1136    raeburn  9856:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9857:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9858:     if (!defined($udom)) {
                   9859:         $udom = $env{'user.domain'};
                   9860:     }
                   9861:     if (!defined($uname)) {
                   9862:         $uname = $env{'user.name'};
                   9863:     }
                   9864:     if (($udom eq '' || $uname eq '') ||
                   9865:         ($udom eq 'public') && ($uname eq 'public')) {
                   9866:         $quota = 0;
1.536     raeburn  9867:         $quotatype = 'default';
                   9868:         $defquota = 0; 
1.472     raeburn  9869:     } else {
1.536     raeburn  9870:         my $inststatus;
1.1134    raeburn  9871:         if ($quotaname eq 'course') {
                   9872:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9873:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9874:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9875:             } else {
                   9876:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9877:                 $quota = $cenv{'internal.uploadquota'};
                   9878:             }
1.536     raeburn  9879:         } else {
1.1134    raeburn  9880:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9881:                 if ($quotaname eq 'author') {
                   9882:                     $quota = $env{'environment.authorquota'};
                   9883:                 } else {
                   9884:                     $quota = $env{'environment.portfolioquota'};
                   9885:                 }
                   9886:                 $inststatus = $env{'environment.inststatus'};
                   9887:             } else {
                   9888:                 my %userenv = 
                   9889:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9890:                                          'authorquota','inststatus'],$udom,$uname);
                   9891:                 my ($tmp) = keys(%userenv);
                   9892:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9893:                     if ($quotaname eq 'author') {
                   9894:                         $quota = $userenv{'authorquota'};
                   9895:                     } else {
                   9896:                         $quota = $userenv{'portfolioquota'};
                   9897:                     }
                   9898:                     $inststatus = $userenv{'inststatus'};
                   9899:                 } else {
                   9900:                     undef(%userenv);
                   9901:                 }
                   9902:             }
                   9903:         }
                   9904:         if ($quota eq '' || wantarray) {
                   9905:             if ($quotaname eq 'course') {
                   9906:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9907:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  9908:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   9909:                     ($crstype eq 'placement')) { 
1.1136    raeburn  9910:                     $defquota = $domdefs{$crstype.'quota'};
                   9911:                 }
                   9912:                 if ($defquota eq '') {
                   9913:                     $defquota = 500;
                   9914:                 }
1.1134    raeburn  9915:             } else {
                   9916:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9917:             }
                   9918:             if ($quota eq '') {
                   9919:                 $quota = $defquota;
                   9920:                 $quotatype = 'default';
                   9921:             } else {
                   9922:                 $quotatype = 'custom';
                   9923:             }
1.472     raeburn  9924:         }
                   9925:     }
1.536     raeburn  9926:     if (wantarray) {
                   9927:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9928:     } else {
                   9929:         return $quota;
                   9930:     }
1.472     raeburn  9931: }
                   9932: 
                   9933: ###############################################
                   9934: 
                   9935: =pod
                   9936: 
                   9937: =item * &default_quota()
                   9938: 
1.536     raeburn  9939: Retrieves default quota assigned for storage of user portfolio files,
                   9940: given an (optional) user's institutional status.
1.472     raeburn  9941: 
                   9942: Incoming parameters:
1.1142    raeburn  9943: 
1.472     raeburn  9944: 1. domain
1.536     raeburn  9945: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9946:    status types (e.g., faculty, staff, student etc.)
                   9947:    which apply to the user for whom the default is being retrieved.
                   9948:    If the institutional status string in undefined, the domain
1.1134    raeburn  9949:    default quota will be returned.
                   9950: 3.  quota name - portfolio, author, or course
                   9951:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9952: 
                   9953: Returns:
1.1142    raeburn  9954: 
1.1163    raeburn  9955: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9956: 2. (Optional) institutional type which determined the value of the
                   9957:    default quota.
1.472     raeburn  9958: 
                   9959: If a value has been stored in the domain's configuration db,
                   9960: it will return that, otherwise it returns 20 (for backwards 
                   9961: compatibility with domains which have not set up a configuration
1.1163    raeburn  9962: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9963: 
1.536     raeburn  9964: If the user's status includes multiple types (e.g., staff and student),
                   9965: the largest default quota which applies to the user determines the
                   9966: default quota returned.
                   9967: 
1.472     raeburn  9968: =cut
                   9969: 
                   9970: ###############################################
                   9971: 
                   9972: 
                   9973: sub default_quota {
1.1134    raeburn  9974:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9975:     my ($defquota,$settingstatus);
                   9976:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9977:                                             ['quotas'],$udom);
1.1134    raeburn  9978:     my $key = 'defaultquota';
                   9979:     if ($quotaname eq 'author') {
                   9980:         $key = 'authorquota';
                   9981:     }
1.622     raeburn  9982:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9983:         if ($inststatus ne '') {
1.765     raeburn  9984:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9985:             foreach my $item (@statuses) {
1.1134    raeburn  9986:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9987:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9988:                         if ($defquota eq '') {
1.1134    raeburn  9989:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9990:                             $settingstatus = $item;
1.1134    raeburn  9991:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9992:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9993:                             $settingstatus = $item;
                   9994:                         }
                   9995:                     }
1.1134    raeburn  9996:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9997:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9998:                         if ($defquota eq '') {
                   9999:                             $defquota = $quotahash{'quotas'}{$item};
                   10000:                             $settingstatus = $item;
                   10001:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10002:                             $defquota = $quotahash{'quotas'}{$item};
                   10003:                             $settingstatus = $item;
                   10004:                         }
1.536     raeburn  10005:                     }
                   10006:                 }
                   10007:             }
                   10008:         }
                   10009:         if ($defquota eq '') {
1.1134    raeburn  10010:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10011:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10012:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10013:                 $defquota = $quotahash{'quotas'}{'default'};
                   10014:             }
1.536     raeburn  10015:             $settingstatus = 'default';
1.1139    raeburn  10016:             if ($defquota eq '') {
                   10017:                 if ($quotaname eq 'author') {
                   10018:                     $defquota = 500;
                   10019:                 }
                   10020:             }
1.536     raeburn  10021:         }
                   10022:     } else {
                   10023:         $settingstatus = 'default';
1.1134    raeburn  10024:         if ($quotaname eq 'author') {
                   10025:             $defquota = 500;
                   10026:         } else {
                   10027:             $defquota = 20;
                   10028:         }
1.536     raeburn  10029:     }
                   10030:     if (wantarray) {
                   10031:         return ($defquota,$settingstatus);
1.472     raeburn  10032:     } else {
1.536     raeburn  10033:         return $defquota;
1.472     raeburn  10034:     }
                   10035: }
                   10036: 
1.1135    raeburn  10037: ###############################################
                   10038: 
                   10039: =pod
                   10040: 
1.1136    raeburn  10041: =item * &excess_filesize_warning()
1.1135    raeburn  10042: 
                   10043: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10044: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10045: space to be exceeded.
1.1136    raeburn  10046: 
                   10047: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10048: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10049: 
1.1165    raeburn  10050: Inputs: 7 
1.1136    raeburn  10051: 1. username or coursenum
1.1135    raeburn  10052: 2. domain
1.1136    raeburn  10053: 3. context ('author' or 'course')
1.1135    raeburn  10054: 4. filename of file for which action is being requested
                   10055: 5. filesize (kB) of file
                   10056: 6. action being taken: copy or upload.
1.1237    raeburn  10057: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10058: 
                   10059: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10060:          otherwise return null.
                   10061: 
                   10062: =back
1.1135    raeburn  10063: 
                   10064: =cut
                   10065: 
1.1136    raeburn  10066: sub excess_filesize_warning {
1.1165    raeburn  10067:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10068:     my $current_disk_usage = 0;
1.1165    raeburn  10069:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10070:     if ($context eq 'author') {
                   10071:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10072:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10073:     } else {
                   10074:         foreach my $subdir ('docs','supplemental') {
                   10075:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10076:         }
                   10077:     }
1.1135    raeburn  10078:     $disk_quota = int($disk_quota * 1000);
                   10079:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10080:         return '<p class="LC_warning">'.
1.1135    raeburn  10081:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10082:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10083:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10084:                             $disk_quota,$current_disk_usage).
                   10085:                '</p>';
                   10086:     }
                   10087:     return;
                   10088: }
                   10089: 
                   10090: ###############################################
                   10091: 
                   10092: 
1.1136    raeburn  10093: 
                   10094: 
1.384     raeburn  10095: sub get_secgrprole_info {
                   10096:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10097:     my %sections_count = &get_sections($cdom,$cnum);
                   10098:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10099:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10100:     my @groups = sort(keys(%curr_groups));
                   10101:     my $allroles = [];
                   10102:     my $rolehash;
                   10103:     my $accesshash = {
                   10104:                      active => 'Currently has access',
                   10105:                      future => 'Will have future access',
                   10106:                      previous => 'Previously had access',
                   10107:                   };
                   10108:     if ($needroles) {
                   10109:         $rolehash = {'all' => 'all'};
1.385     albertel 10110:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10111: 	if (&Apache::lonnet::error(%user_roles)) {
                   10112: 	    undef(%user_roles);
                   10113: 	}
                   10114:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10115:             my ($role)=split(/\:/,$item,2);
                   10116:             if ($role eq 'cr') { next; }
                   10117:             if ($role =~ /^cr/) {
                   10118:                 $$rolehash{$role} = (split('/',$role))[3];
                   10119:             } else {
                   10120:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10121:             }
                   10122:         }
                   10123:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10124:             push(@{$allroles},$key);
                   10125:         }
                   10126:         push (@{$allroles},'st');
                   10127:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10128:     }
                   10129:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10130: }
                   10131: 
1.555     raeburn  10132: sub user_picker {
1.1279    raeburn  10133:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10134:     my $currdom = $dom;
1.1253    raeburn  10135:     my @alldoms = &Apache::lonnet::all_domains();
                   10136:     if (@alldoms == 1) {
                   10137:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10138:                                                ['directorysrch'],$alldoms[0]);
                   10139:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10140:         my $showdom = $domdesc;
                   10141:         if ($showdom eq '') {
                   10142:             $showdom = $dom;
                   10143:         }
                   10144:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10145:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10146:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10147:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10148:             }
                   10149:         }
                   10150:     }
1.555     raeburn  10151:     my %curr_selected = (
                   10152:                         srchin => 'dom',
1.580     raeburn  10153:                         srchby => 'lastname',
1.555     raeburn  10154:                       );
                   10155:     my $srchterm;
1.625     raeburn  10156:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10157:         if ($srch->{'srchby'} ne '') {
                   10158:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10159:         }
                   10160:         if ($srch->{'srchin'} ne '') {
                   10161:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10162:         }
                   10163:         if ($srch->{'srchtype'} ne '') {
                   10164:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10165:         }
                   10166:         if ($srch->{'srchdomain'} ne '') {
                   10167:             $currdom = $srch->{'srchdomain'};
                   10168:         }
                   10169:         $srchterm = $srch->{'srchterm'};
                   10170:     }
1.1222    damieng  10171:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10172:                     'usr'       => 'Search criteria',
1.563     raeburn  10173:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10174:                     'uname'     => 'username',
                   10175:                     'lastname'  => 'last name',
1.555     raeburn  10176:                     'lastfirst' => 'last name, first name',
1.558     albertel 10177:                     'crs'       => 'in this course',
1.576     raeburn  10178:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10179:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10180:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10181:                     'exact'     => 'is',
                   10182:                     'contains'  => 'contains',
1.569     raeburn  10183:                     'begins'    => 'begins with',
1.1222    damieng  10184:                                        );
                   10185:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10186:                     'youm'      => "You must include some text to search for.",
                   10187:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10188:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10189:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10190:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10191:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10192:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10193:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10194:                                        );
1.1222    damieng  10195:     &html_escape(\%html_lt);
                   10196:     &js_escape(\%js_lt);
1.1255    raeburn  10197:     my $domform;
1.1277    raeburn  10198:     my $allow_blank = 1;
1.1255    raeburn  10199:     if ($fixeddom) {
1.1277    raeburn  10200:         $allow_blank = 0;
                   10201:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  10202:     } else {
1.1287    raeburn  10203:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  10204:         my ($trusted,$untrusted);
1.1287    raeburn  10205:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  10206:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  10207:         } elsif ($context eq 'author') {
1.1288    raeburn  10208:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  10209:         } elsif ($context eq 'domain') {
1.1288    raeburn  10210:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  10211:         }
1.1288    raeburn  10212:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  10213:     }
1.563     raeburn  10214:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10215: 
                   10216:     my @srchins = ('crs','dom','alc','instd');
                   10217: 
                   10218:     foreach my $option (@srchins) {
                   10219:         # FIXME 'alc' option unavailable until 
                   10220:         #       loncreateuser::print_user_query_page()
                   10221:         #       has been completed.
                   10222:         next if ($option eq 'alc');
1.880     raeburn  10223:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10224:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  10225:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10226:         if ($curr_selected{'srchin'} eq $option) {
                   10227:             $srchinsel .= ' 
1.1222    damieng  10228:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10229:         } else {
                   10230:             $srchinsel .= '
1.1222    damieng  10231:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10232:         }
1.555     raeburn  10233:     }
1.563     raeburn  10234:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10235: 
                   10236:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10237:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10238:         if ($curr_selected{'srchby'} eq $option) {
                   10239:             $srchbysel .= '
1.1222    damieng  10240:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10241:         } else {
                   10242:             $srchbysel .= '
1.1222    damieng  10243:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10244:          }
                   10245:     }
                   10246:     $srchbysel .= "\n  </select>\n";
                   10247: 
                   10248:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10249:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10250:         if ($curr_selected{'srchtype'} eq $option) {
                   10251:             $srchtypesel .= '
1.1222    damieng  10252:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10253:         } else {
                   10254:             $srchtypesel .= '
1.1222    damieng  10255:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10256:         }
                   10257:     }
                   10258:     $srchtypesel .= "\n  </select>\n";
                   10259: 
1.558     albertel 10260:     my ($newuserscript,$new_user_create);
1.994     raeburn  10261:     my $context_dom = $env{'request.role.domain'};
                   10262:     if ($context eq 'requestcrs') {
                   10263:         if ($env{'form.coursedom'} ne '') { 
                   10264:             $context_dom = $env{'form.coursedom'};
                   10265:         }
                   10266:     }
1.556     raeburn  10267:     if ($forcenewuser) {
1.576     raeburn  10268:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10269:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10270:                 if ($cancreate) {
                   10271:                     $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>';
                   10272:                 } else {
1.799     bisitz   10273:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10274:                     my %usertypetext = (
                   10275:                         official   => 'institutional',
                   10276:                         unofficial => 'non-institutional',
                   10277:                     );
1.799     bisitz   10278:                     $new_user_create = '<p class="LC_warning">'
                   10279:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10280:                                       .' '
                   10281:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10282:                                           ,'<a href="'.$helplink.'">','</a>')
                   10283:                                       .'</p><br />';
1.627     raeburn  10284:                 }
1.576     raeburn  10285:             }
                   10286:         }
                   10287: 
1.556     raeburn  10288:         $newuserscript = <<"ENDSCRIPT";
                   10289: 
1.570     raeburn  10290: function setSearch(createnew,callingForm) {
1.556     raeburn  10291:     if (createnew == 1) {
1.570     raeburn  10292:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10293:             if (callingForm.srchby.options[i].value == 'uname') {
                   10294:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10295:             }
                   10296:         }
1.570     raeburn  10297:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10298:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10299: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10300:             }
                   10301:         }
1.570     raeburn  10302:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10303:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10304:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10305:             }
                   10306:         }
1.570     raeburn  10307:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10308:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10309:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10310:             }
                   10311:         }
                   10312:     }
                   10313: }
                   10314: ENDSCRIPT
1.558     albertel 10315: 
1.556     raeburn  10316:     }
                   10317: 
1.555     raeburn  10318:     my $output = <<"END_BLOCK";
1.556     raeburn  10319: <script type="text/javascript">
1.824     bisitz   10320: // <![CDATA[
1.570     raeburn  10321: function validateEntry(callingForm) {
1.558     albertel 10322: 
1.556     raeburn  10323:     var checkok = 1;
1.558     albertel 10324:     var srchin;
1.570     raeburn  10325:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10326: 	if ( callingForm.srchin[i].checked ) {
                   10327: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10328: 	}
                   10329:     }
                   10330: 
1.570     raeburn  10331:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10332:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10333:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10334:     var srchterm =  callingForm.srchterm.value;
                   10335:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10336:     var msg = "";
                   10337: 
                   10338:     if (srchterm == "") {
                   10339:         checkok = 0;
1.1222    damieng  10340:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10341:     }
                   10342: 
1.569     raeburn  10343:     if (srchtype== 'begins') {
                   10344:         if (srchterm.length < 2) {
                   10345:             checkok = 0;
1.1222    damieng  10346:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10347:         }
                   10348:     }
                   10349: 
1.556     raeburn  10350:     if (srchtype== 'contains') {
                   10351:         if (srchterm.length < 3) {
                   10352:             checkok = 0;
1.1222    damieng  10353:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10354:         }
                   10355:     }
                   10356:     if (srchin == 'instd') {
                   10357:         if (srchdomain == '') {
                   10358:             checkok = 0;
1.1222    damieng  10359:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10360:         }
                   10361:     }
                   10362:     if (srchin == 'dom') {
                   10363:         if (srchdomain == '') {
                   10364:             checkok = 0;
1.1222    damieng  10365:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10366:         }
                   10367:     }
                   10368:     if (srchby == 'lastfirst') {
                   10369:         if (srchterm.indexOf(",") == -1) {
                   10370:             checkok = 0;
1.1222    damieng  10371:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10372:         }
                   10373:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10374:             checkok = 0;
1.1222    damieng  10375:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10376:         }
                   10377:     }
                   10378:     if (checkok == 0) {
1.1222    damieng  10379:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10380:         return;
                   10381:     }
                   10382:     if (checkok == 1) {
1.570     raeburn  10383:         callingForm.submit();
1.556     raeburn  10384:     }
                   10385: }
                   10386: 
                   10387: $newuserscript
                   10388: 
1.824     bisitz   10389: // ]]>
1.556     raeburn  10390: </script>
1.558     albertel 10391: 
                   10392: $new_user_create
                   10393: 
1.555     raeburn  10394: END_BLOCK
1.558     albertel 10395: 
1.876     raeburn  10396:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10397:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10398:                $domform.
                   10399:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10400:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10401:                $srchbysel.
                   10402:                $srchtypesel. 
                   10403:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10404:                $srchinsel.
                   10405:                &Apache::lonhtmlcommon::row_closure(1). 
                   10406:                &Apache::lonhtmlcommon::end_pick_box().
                   10407:                '<br />';
1.1253    raeburn  10408:     return ($output,1);
1.555     raeburn  10409: }
                   10410: 
1.612     raeburn  10411: sub user_rule_check {
1.615     raeburn  10412:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10413:     my ($response,%inst_response);
1.612     raeburn  10414:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10415:         if (keys(%{$usershash}) > 1) {
                   10416:             my (%by_username,%by_id,%userdoms);
                   10417:             my $checkid; 
                   10418:             if (ref($checks) eq 'HASH') {
                   10419:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10420:                     $checkid = 1;
                   10421:                 }
                   10422:             }
                   10423:             foreach my $user (keys(%{$usershash})) {
                   10424:                 my ($uname,$udom) = split(/:/,$user);
                   10425:                 if ($checkid) {
                   10426:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10427:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10428:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10429:                             $userdoms{$udom} = 1;
1.1227    raeburn  10430:                             if (ref($inst_results) eq 'HASH') {
                   10431:                                 $inst_results->{$uname.':'.$udom} = {};
                   10432:                             }
1.1226    raeburn  10433:                         }
                   10434:                     }
                   10435:                 } else {
                   10436:                     $by_username{$udom}{$uname} = 1;
                   10437:                     $userdoms{$udom} = 1;
1.1227    raeburn  10438:                     if (ref($inst_results) eq 'HASH') {
                   10439:                         $inst_results->{$uname.':'.$udom} = {};
                   10440:                     }
1.1226    raeburn  10441:                 }
                   10442:             }
                   10443:             foreach my $udom (keys(%userdoms)) {
                   10444:                 if (!$got_rules->{$udom}) {
                   10445:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10446:                                                              ['usercreation'],$udom);
                   10447:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10448:                         foreach my $item ('username','id') {
                   10449:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10450:                                 $$curr_rules{$udom}{$item} =
                   10451:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10452:                             }
                   10453:                         }
                   10454:                     }
                   10455:                     $got_rules->{$udom} = 1;
                   10456:                 }
1.612     raeburn  10457:             }
1.1226    raeburn  10458:             if ($checkid) {
                   10459:                 foreach my $udom (keys(%by_id)) {
                   10460:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10461:                     if ($outcome eq 'ok') {
1.1227    raeburn  10462:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10463:                             my $uname = $by_id{$udom}{$id};
                   10464:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10465:                         }
1.1226    raeburn  10466:                         if (ref($results) eq 'HASH') {
                   10467:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  10468:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10469:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10470:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10471:                                 }
1.1226    raeburn  10472:                             }
                   10473:                         }
                   10474:                     }
1.612     raeburn  10475:                 }
1.615     raeburn  10476:             } else {
1.1226    raeburn  10477:                 foreach my $udom (keys(%by_username)) {
                   10478:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10479:                     if ($outcome eq 'ok') {
1.1227    raeburn  10480:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10481:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10482:                         }
1.1226    raeburn  10483:                         if (ref($results) eq 'HASH') {
                   10484:                             foreach my $uname (keys(%{$results})) {
                   10485:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10486:                             }
                   10487:                         }
                   10488:                     }
                   10489:                 }
1.612     raeburn  10490:             }
1.1226    raeburn  10491:         } elsif (keys(%{$usershash}) == 1) {
                   10492:             my $user = (keys(%{$usershash}))[0];
                   10493:             my ($uname,$udom) = split(/:/,$user);
                   10494:             if (($udom ne '') && ($uname ne '')) {
                   10495:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10496:                     if (ref($checks) eq 'HASH') {
                   10497:                         if (defined($checks->{'username'})) {
                   10498:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   10499:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10500:                         } elsif (defined($checks->{'id'})) {
                   10501:                             if ($usershash->{$user}->{'id'} ne '') {
                   10502:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10503:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10504:                                                                   $usershash->{$user}->{'id'});
                   10505:                             } else {
                   10506:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10507:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10508:                             }
1.585     raeburn  10509:                         }
1.1226    raeburn  10510:                     } else {
                   10511:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10512:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10513:                        return;
                   10514:                     }
                   10515:                     if (!$got_rules->{$udom}) {
                   10516:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10517:                                                                  ['usercreation'],$udom);
                   10518:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10519:                             foreach my $item ('username','id') {
                   10520:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10521:                                    $$curr_rules{$udom}{$item} = 
                   10522:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10523:                                 }
                   10524:                             }
                   10525:                         }
                   10526:                         $got_rules->{$udom} = 1;
1.585     raeburn  10527:                     }
                   10528:                 }
1.1226    raeburn  10529:             } else {
                   10530:                 return;
                   10531:             }
                   10532:         } else {
                   10533:             return;
                   10534:         }
                   10535:         foreach my $user (keys(%{$usershash})) {
                   10536:             my ($uname,$udom) = split(/:/,$user);
                   10537:             next if (($udom eq '') || ($uname eq ''));
                   10538:             my $id;
1.1227    raeburn  10539:             if (ref($inst_results) eq 'HASH') {
                   10540:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10541:                     $id = $inst_results->{$user}->{'id'};
                   10542:                 }
                   10543:             }
                   10544:             if ($id eq '') { 
                   10545:                 if (ref($usershash->{$user})) {
                   10546:                     $id = $usershash->{$user}->{'id'};
                   10547:                 }
1.585     raeburn  10548:             }
1.612     raeburn  10549:             foreach my $item (keys(%{$checks})) {
                   10550:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10551:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10552:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10553:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10554:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10555:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10556:                                 if ($rule_check{$rule}) {
                   10557:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10558:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10559:                                         if (ref($inst_results) eq 'HASH') {
                   10560:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10561:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10562:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10563:                                                 } elsif ($item eq 'id') {
                   10564:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10565:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10566:                                                     }
1.615     raeburn  10567:                                                 }
1.612     raeburn  10568:                                             }
                   10569:                                         }
1.615     raeburn  10570:                                     }
                   10571:                                     last;
1.585     raeburn  10572:                                 }
                   10573:                             }
                   10574:                         }
                   10575:                     }
                   10576:                 }
                   10577:             }
                   10578:         }
                   10579:     }
1.612     raeburn  10580:     return;
                   10581: }
                   10582: 
                   10583: sub user_rule_formats {
                   10584:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10585:     my %text = ( 
                   10586:                  'username' => 'Usernames',
                   10587:                  'id'       => 'IDs',
                   10588:                );
                   10589:     my $output;
                   10590:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10591:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10592:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10593:             $output = '<br />'.
                   10594:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10595:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10596:                       ' <ul>';
1.612     raeburn  10597:             foreach my $rule (@{$ruleorder}) {
                   10598:                 if (ref($curr_rules) eq 'ARRAY') {
                   10599:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10600:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10601:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10602:                                         $rules->{$rule}{'desc'}.'</li>';
                   10603:                         }
                   10604:                     }
                   10605:                 }
                   10606:             }
                   10607:             $output .= '</ul>';
                   10608:         }
                   10609:     }
                   10610:     return $output;
                   10611: }
                   10612: 
                   10613: sub instrule_disallow_msg {
1.615     raeburn  10614:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10615:     my $response;
                   10616:     my %text = (
                   10617:                   item   => 'username',
                   10618:                   items  => 'usernames',
                   10619:                   match  => 'matches',
                   10620:                   do     => 'does',
                   10621:                   action => 'a username',
                   10622:                   one    => 'one',
                   10623:                );
                   10624:     if ($count > 1) {
                   10625:         $text{'item'} = 'usernames';
                   10626:         $text{'match'} ='match';
                   10627:         $text{'do'} = 'do';
                   10628:         $text{'action'} = 'usernames',
                   10629:         $text{'one'} = 'ones';
                   10630:     }
                   10631:     if ($checkitem eq 'id') {
                   10632:         $text{'items'} = 'IDs';
                   10633:         $text{'item'} = 'ID';
                   10634:         $text{'action'} = 'an ID';
1.615     raeburn  10635:         if ($count > 1) {
                   10636:             $text{'item'} = 'IDs';
                   10637:             $text{'action'} = 'IDs';
                   10638:         }
1.612     raeburn  10639:     }
1.674     bisitz   10640:     $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  10641:     if ($mode eq 'upload') {
                   10642:         if ($checkitem eq 'username') {
                   10643:             $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'}.");
                   10644:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10645:             $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  10646:         }
1.669     raeburn  10647:     } elsif ($mode eq 'selfcreate') {
                   10648:         if ($checkitem eq 'id') {
                   10649:             $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.");
                   10650:         }
1.615     raeburn  10651:     } else {
                   10652:         if ($checkitem eq 'username') {
                   10653:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10654:         } elsif ($checkitem eq 'id') {
                   10655:             $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.");
                   10656:         }
1.612     raeburn  10657:     }
                   10658:     return $response;
1.585     raeburn  10659: }
                   10660: 
1.624     raeburn  10661: sub personal_data_fieldtitles {
                   10662:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10663:                         id => 'Student/Employee ID',
                   10664:                         permanentemail => 'E-mail address',
                   10665:                         lastname => 'Last Name',
                   10666:                         firstname => 'First Name',
                   10667:                         middlename => 'Middle Name',
                   10668:                         generation => 'Generation',
                   10669:                         gen => 'Generation',
1.765     raeburn  10670:                         inststatus => 'Affiliation',
1.624     raeburn  10671:                    );
                   10672:     return %fieldtitles;
                   10673: }
                   10674: 
1.642     raeburn  10675: sub sorted_inst_types {
                   10676:     my ($dom) = @_;
1.1185    raeburn  10677:     my ($usertypes,$order);
                   10678:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10679:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10680:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10681:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10682:     } else {
                   10683:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10684:     }
1.642     raeburn  10685:     my $othertitle = &mt('All users');
                   10686:     if ($env{'request.course.id'}) {
1.668     raeburn  10687:         $othertitle  = &mt('Any users');
1.642     raeburn  10688:     }
                   10689:     my @types;
                   10690:     if (ref($order) eq 'ARRAY') {
                   10691:         @types = @{$order};
                   10692:     }
                   10693:     if (@types == 0) {
                   10694:         if (ref($usertypes) eq 'HASH') {
                   10695:             @types = sort(keys(%{$usertypes}));
                   10696:         }
                   10697:     }
                   10698:     if (keys(%{$usertypes}) > 0) {
                   10699:         $othertitle = &mt('Other users');
                   10700:     }
                   10701:     return ($othertitle,$usertypes,\@types);
                   10702: }
                   10703: 
1.645     raeburn  10704: sub get_institutional_codes {
                   10705:     my ($settings,$allcourses,$LC_code) = @_;
                   10706: # Get complete list of course sections to update
                   10707:     my @currsections = ();
                   10708:     my @currxlists = ();
                   10709:     my $coursecode = $$settings{'internal.coursecode'};
                   10710: 
                   10711:     if ($$settings{'internal.sectionnums'} ne '') {
                   10712:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10713:     }
                   10714: 
                   10715:     if ($$settings{'internal.crosslistings'} ne '') {
                   10716:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10717:     }
                   10718: 
                   10719:     if (@currxlists > 0) {
                   10720:         foreach (@currxlists) {
                   10721:             if (m/^([^:]+):(\w*)$/) {
                   10722:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  10723:                     push(@{$allcourses},$1);
1.645     raeburn  10724:                     $$LC_code{$1} = $2;
                   10725:                 }
                   10726:             }
                   10727:         }
                   10728:     }
                   10729:  
                   10730:     if (@currsections > 0) {
                   10731:         foreach (@currsections) {
                   10732:             if (m/^(\w+):(\w*)$/) {
                   10733:                 my $sec = $coursecode.$1;
                   10734:                 my $lc_sec = $2;
                   10735:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1263    raeburn  10736:                     push(@{$allcourses},$sec);
1.645     raeburn  10737:                     $$LC_code{$sec} = $lc_sec;
                   10738:                 }
                   10739:             }
                   10740:         }
                   10741:     }
                   10742:     return;
                   10743: }
                   10744: 
1.971     raeburn  10745: sub get_standard_codeitems {
                   10746:     return ('Year','Semester','Department','Number','Section');
                   10747: }
                   10748: 
1.112     bowersj2 10749: =pod
                   10750: 
1.780     raeburn  10751: =head1 Slot Helpers
                   10752: 
                   10753: =over 4
                   10754: 
                   10755: =item * sorted_slots()
                   10756: 
1.1040    raeburn  10757: Sorts an array of slot names in order of an optional sort key,
                   10758: default sort is by slot start time (earliest first). 
1.780     raeburn  10759: 
                   10760: Inputs:
                   10761: 
                   10762: =over 4
                   10763: 
                   10764: slotsarr  - Reference to array of unsorted slot names.
                   10765: 
                   10766: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10767: 
1.1040    raeburn  10768: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10769: 
1.549     albertel 10770: =back
                   10771: 
1.780     raeburn  10772: Returns:
                   10773: 
                   10774: =over 4
                   10775: 
1.1040    raeburn  10776: sorted   - An array of slot names sorted by a specified sort key 
                   10777:            (default sort key is start time of the slot).
1.780     raeburn  10778: 
                   10779: =back
                   10780: 
                   10781: =cut
                   10782: 
                   10783: 
                   10784: sub sorted_slots {
1.1040    raeburn  10785:     my ($slotsarr,$slots,$sortkey) = @_;
                   10786:     if ($sortkey eq '') {
                   10787:         $sortkey = 'starttime';
                   10788:     }
1.780     raeburn  10789:     my @sorted;
                   10790:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10791:         @sorted =
                   10792:             sort {
                   10793:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10794:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10795:                      }
                   10796:                      if (ref($slots->{$a})) { return -1;}
                   10797:                      if (ref($slots->{$b})) { return 1;}
                   10798:                      return 0;
                   10799:                  } @{$slotsarr};
                   10800:     }
                   10801:     return @sorted;
                   10802: }
                   10803: 
1.1040    raeburn  10804: =pod
                   10805: 
                   10806: =item * get_future_slots()
                   10807: 
                   10808: Inputs:
                   10809: 
                   10810: =over 4
                   10811: 
                   10812: cnum - course number
                   10813: 
                   10814: cdom - course domain
                   10815: 
                   10816: now - current UNIX time
                   10817: 
                   10818: symb - optional symb
                   10819: 
                   10820: =back
                   10821: 
                   10822: Returns:
                   10823: 
                   10824: =over 4
                   10825: 
                   10826: sorted_reservable - ref to array of student_schedulable slots currently 
                   10827:                     reservable, ordered by end date of reservation period.
                   10828: 
                   10829: reservable_now - ref to hash of student_schedulable slots currently
                   10830:                  reservable.
                   10831: 
                   10832:     Keys in inner hash are:
                   10833:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10834:     (b) endreserve: end date of reservation period.
                   10835:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10836:         selected.
1.1040    raeburn  10837: 
                   10838: sorted_future - ref to array of student_schedulable slots reservable in
                   10839:                 the future, ordered by start date of reservation period.
                   10840: 
                   10841: future_reservable - ref to hash of student_schedulable slots reservable
                   10842:                     in the future.
                   10843: 
                   10844:     Keys in inner hash are:
                   10845:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10846:     (b) startreserve: start date of reservation period.
                   10847:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10848:         selected.
1.1040    raeburn  10849: 
                   10850: =back
                   10851: 
                   10852: =cut
                   10853: 
                   10854: sub get_future_slots {
                   10855:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  10856:     my $map;
                   10857:     if ($symb) {
                   10858:         ($map) = &Apache::lonnet::decode_symb($symb);
                   10859:     }
1.1040    raeburn  10860:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10861:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10862:     foreach my $slot (keys(%slots)) {
                   10863:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10864:         if ($symb) {
1.1229    raeburn  10865:             if ($slots{$slot}->{'symb'} ne '') {
                   10866:                 my $canuse;
                   10867:                 my %oksymbs;
                   10868:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   10869:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   10870:                 if ($oksymbs{$symb}) {
                   10871:                     $canuse = 1;
                   10872:                 } else {
                   10873:                     foreach my $item (@slotsymbs) {
                   10874:                         if ($item =~ /\.(page|sequence)$/) {
                   10875:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   10876:                             if (($map ne '') && ($map eq $sloturl)) {
                   10877:                                 $canuse = 1;
                   10878:                                 last;
                   10879:                             }
                   10880:                         }
                   10881:                     }
                   10882:                 }
                   10883:                 next unless ($canuse);
                   10884:             }
1.1040    raeburn  10885:         }
                   10886:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10887:             ($slots{$slot}->{'endtime'} > $now)) {
                   10888:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10889:                 my $userallowed = 0;
                   10890:                 if ($slots{$slot}->{'allowedsections'}) {
                   10891:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10892:                     if (!defined($env{'request.role.sec'})
                   10893:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10894:                         $userallowed=1;
                   10895:                     } else {
                   10896:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10897:                             $userallowed=1;
                   10898:                         }
                   10899:                     }
                   10900:                     unless ($userallowed) {
                   10901:                         if (defined($env{'request.course.groups'})) {
                   10902:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10903:                             foreach my $group (@groups) {
                   10904:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10905:                                     $userallowed=1;
                   10906:                                     last;
                   10907:                                 }
                   10908:                             }
                   10909:                         }
                   10910:                     }
                   10911:                 }
                   10912:                 if ($slots{$slot}->{'allowedusers'}) {
                   10913:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10914:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10915:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10916:                         $userallowed = 1;
                   10917:                     }
                   10918:                 }
                   10919:                 next unless($userallowed);
                   10920:             }
                   10921:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10922:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10923:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  10924:             my $uniqueperiod;
                   10925:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10926:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10927:             }
1.1040    raeburn  10928:             if (($startreserve < $now) &&
                   10929:                 (!$endreserve || $endreserve > $now)) {
                   10930:                 my $lastres = $endreserve;
                   10931:                 if (!$lastres) {
                   10932:                     $lastres = $slots{$slot}->{'starttime'};
                   10933:                 }
                   10934:                 $reservable_now{$slot} = {
                   10935:                                            symb       => $symb,
1.1250    raeburn  10936:                                            endreserve => $lastres,
                   10937:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  10938:                                          };
                   10939:             } elsif (($startreserve > $now) &&
                   10940:                      (!$endreserve || $endreserve > $startreserve)) {
                   10941:                 $future_reservable{$slot} = {
                   10942:                                               symb         => $symb,
1.1250    raeburn  10943:                                               startreserve => $startreserve,
                   10944:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10945:                                             };
                   10946:             }
                   10947:         }
                   10948:     }
                   10949:     my @unsorted_reservable = keys(%reservable_now);
                   10950:     if (@unsorted_reservable > 0) {
                   10951:         @sorted_reservable = 
                   10952:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10953:     }
                   10954:     my @unsorted_future = keys(%future_reservable);
                   10955:     if (@unsorted_future > 0) {
                   10956:         @sorted_future =
                   10957:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10958:     }
                   10959:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10960: }
1.780     raeburn  10961: 
                   10962: =pod
                   10963: 
1.1057    foxr     10964: =back
                   10965: 
1.549     albertel 10966: =head1 HTTP Helpers
                   10967: 
                   10968: =over 4
                   10969: 
1.648     raeburn  10970: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10971: 
1.258     albertel 10972: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10973: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10974: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10975: 
                   10976: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10977: $possible_names is an ref to an array of form element names.  As an example:
                   10978: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10979: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10980: 
                   10981: =cut
1.1       albertel 10982: 
1.6       albertel 10983: sub get_unprocessed_cgi {
1.25      albertel 10984:   my ($query,$possible_names)= @_;
1.26      matthew  10985:   # $Apache::lonxml::debug=1;
1.356     albertel 10986:   foreach my $pair (split(/&/,$query)) {
                   10987:     my ($name, $value) = split(/=/,$pair);
1.369     www      10988:     $name = &unescape($name);
1.25      albertel 10989:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10990:       $value =~ tr/+/ /;
                   10991:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10992:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10993:     }
1.16      harris41 10994:   }
1.6       albertel 10995: }
                   10996: 
1.112     bowersj2 10997: =pod
                   10998: 
1.648     raeburn  10999: =item * &cacheheader() 
1.112     bowersj2 11000: 
                   11001: returns cache-controlling header code
                   11002: 
                   11003: =cut
                   11004: 
1.7       albertel 11005: sub cacheheader {
1.258     albertel 11006:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11007:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11008:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11009:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11010:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11011:     return $output;
1.7       albertel 11012: }
                   11013: 
1.112     bowersj2 11014: =pod
                   11015: 
1.648     raeburn  11016: =item * &no_cache($r) 
1.112     bowersj2 11017: 
                   11018: specifies header code to not have cache
                   11019: 
                   11020: =cut
                   11021: 
1.9       albertel 11022: sub no_cache {
1.216     albertel 11023:     my ($r) = @_;
                   11024:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11025: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11026:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11027:     $r->no_cache(1);
                   11028:     $r->header_out("Expires" => $date);
                   11029:     $r->header_out("Pragma" => "no-cache");
1.123     www      11030: }
                   11031: 
                   11032: sub content_type {
1.181     albertel 11033:     my ($r,$type,$charset) = @_;
1.299     foxr     11034:     if ($r) {
                   11035: 	#  Note that printout.pl calls this with undef for $r.
                   11036: 	&no_cache($r);
                   11037:     }
1.258     albertel 11038:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11039:     unless ($charset) {
                   11040: 	$charset=&Apache::lonlocal::current_encoding;
                   11041:     }
                   11042:     if ($charset) { $type.='; charset='.$charset; }
                   11043:     if ($r) {
                   11044: 	$r->content_type($type);
                   11045:     } else {
                   11046: 	print("Content-type: $type\n\n");
                   11047:     }
1.9       albertel 11048: }
1.25      albertel 11049: 
1.112     bowersj2 11050: =pod
                   11051: 
1.648     raeburn  11052: =item * &add_to_env($name,$value) 
1.112     bowersj2 11053: 
1.258     albertel 11054: adds $name to the %env hash with value
1.112     bowersj2 11055: $value, if $name already exists, the entry is converted to an array
                   11056: reference and $value is added to the array.
                   11057: 
                   11058: =cut
                   11059: 
1.25      albertel 11060: sub add_to_env {
                   11061:   my ($name,$value)=@_;
1.258     albertel 11062:   if (defined($env{$name})) {
                   11063:     if (ref($env{$name})) {
1.25      albertel 11064:       #already have multiple values
1.258     albertel 11065:       push(@{ $env{$name} },$value);
1.25      albertel 11066:     } else {
                   11067:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11068:       my $first=$env{$name};
                   11069:       undef($env{$name});
                   11070:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11071:     }
                   11072:   } else {
1.258     albertel 11073:     $env{$name}=$value;
1.25      albertel 11074:   }
1.31      albertel 11075: }
1.149     albertel 11076: 
                   11077: =pod
                   11078: 
1.648     raeburn  11079: =item * &get_env_multiple($name) 
1.149     albertel 11080: 
1.258     albertel 11081: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11082: values may be defined and end up as an array ref.
                   11083: 
                   11084: returns an array of values
                   11085: 
                   11086: =cut
                   11087: 
                   11088: sub get_env_multiple {
                   11089:     my ($name) = @_;
                   11090:     my @values;
1.258     albertel 11091:     if (defined($env{$name})) {
1.149     albertel 11092:         # exists is it an array
1.258     albertel 11093:         if (ref($env{$name})) {
                   11094:             @values=@{ $env{$name} };
1.149     albertel 11095:         } else {
1.258     albertel 11096:             $values[0]=$env{$name};
1.149     albertel 11097:         }
                   11098:     }
                   11099:     return(@values);
                   11100: }
                   11101: 
1.1249    damieng  11102: # Looks at given dependencies, and returns something depending on the context.
                   11103: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11104: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11105: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11106: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11107: # $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.
                   11108: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11109: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11110: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11111: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11112: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11113: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11114: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11115: # @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)
                   11116: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11117: sub ask_for_embedded_content {
1.1249    damieng  11118:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11119:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11120:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11121:         %currsubfile,%unused,$rem);
1.1071    raeburn  11122:     my $counter = 0;
                   11123:     my $numnew = 0;
1.987     raeburn  11124:     my $numremref = 0;
                   11125:     my $numinvalid = 0;
                   11126:     my $numpathchg = 0;
                   11127:     my $numexisting = 0;
1.1071    raeburn  11128:     my $numunused = 0;
                   11129:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11130:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11131:     my $heading = &mt('Upload embedded files');
                   11132:     my $buttontext = &mt('Upload');
                   11133: 
1.1249    damieng  11134:     # fills these variables based on the context:
                   11135:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11136:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11137:     if ($env{'request.course.id'}) {
1.1123    raeburn  11138:         if ($actionurl eq '/adm/dependencies') {
                   11139:             $navmap = Apache::lonnavmaps::navmap->new();
                   11140:         }
                   11141:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11142:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11143:     }
1.1123    raeburn  11144:     if (($actionurl eq '/adm/portfolio') || 
                   11145:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11146:         my $current_path='/';
                   11147:         if ($env{'form.currentpath'}) {
                   11148:             $current_path = $env{'form.currentpath'};
                   11149:         }
                   11150:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11151:             $udom = $cdom;
                   11152:             $uname = $cnum;
1.984     raeburn  11153:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11154:         } else {
                   11155:             $udom = $env{'user.domain'};
                   11156:             $uname = $env{'user.name'};
                   11157:             $url = '/userfiles/portfolio';
                   11158:         }
1.987     raeburn  11159:         $toplevel = $url.'/';
1.984     raeburn  11160:         $url .= $current_path;
                   11161:         $getpropath = 1;
1.987     raeburn  11162:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11163:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11164:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11165:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11166:         $toplevel = $url;
1.984     raeburn  11167:         if ($rest ne '') {
1.987     raeburn  11168:             $url .= $rest;
                   11169:         }
                   11170:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11171:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11172:             $url = $args->{'docs_url'};
                   11173:             $toplevel = $url;
1.1084    raeburn  11174:             if ($args->{'context'} eq 'paste') {
                   11175:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11176:                 ($path) = 
                   11177:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11178:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11179:                 $fileloc =~ s{^/}{};
                   11180:             }
1.1071    raeburn  11181:         }
1.1084    raeburn  11182:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11183:         if ($env{'request.course.id'} ne '') {
                   11184:             if (ref($args) eq 'HASH') {
                   11185:                 $url = $args->{'docs_url'};
                   11186:                 $title = $args->{'docs_title'};
1.1126    raeburn  11187:                 $toplevel = $url; 
                   11188:                 unless ($toplevel =~ m{^/}) {
                   11189:                     $toplevel = "/$url";
                   11190:                 }
1.1085    raeburn  11191:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11192:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11193:                     $path = $1;
                   11194:                 } else {
                   11195:                     ($path) =
                   11196:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11197:                 }
1.1195    raeburn  11198:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11199:                     $fileloc = $toplevel;
                   11200:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11201:                     my ($udom,$uname,$fname) =
                   11202:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11203:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11204:                 } else {
                   11205:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11206:                 }
1.1071    raeburn  11207:                 $fileloc =~ s{^/}{};
                   11208:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11209:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11210:             }
1.987     raeburn  11211:         }
1.1123    raeburn  11212:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11213:         $udom = $cdom;
                   11214:         $uname = $cnum;
                   11215:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11216:         $toplevel = $url;
                   11217:         $path = $url;
                   11218:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11219:         $fileloc =~ s{^/}{};
1.987     raeburn  11220:     }
1.1249    damieng  11221:     
                   11222:     # parses the dependency paths to get some info
                   11223:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11224:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11225:     # (will be completed later)
                   11226:     # $mapping:
                   11227:     #   for external URLs: external URL -> external URL
                   11228:     #   for relative paths: clean path -> original path
                   11229:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11230:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11231:     foreach my $file (keys(%{$allfiles})) {
                   11232:         my $embed_file;
                   11233:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11234:             $embed_file = $1;
                   11235:         } else {
                   11236:             $embed_file = $file;
                   11237:         }
1.1158    raeburn  11238:         my ($absolutepath,$cleaned_file);
                   11239:         if ($embed_file =~ m{^\w+://}) {
                   11240:             $cleaned_file = $embed_file;
1.1147    raeburn  11241:             $newfiles{$cleaned_file} = 1;
                   11242:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11243:         } else {
1.1158    raeburn  11244:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11245:             if ($embed_file =~ m{^/}) {
                   11246:                 $absolutepath = $embed_file;
                   11247:             }
1.1147    raeburn  11248:             if ($cleaned_file =~ m{/}) {
                   11249:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11250:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11251:                 my $item = $fname;
                   11252:                 if ($path ne '') {
                   11253:                     $item = $path.'/'.$fname;
                   11254:                     $subdependencies{$path}{$fname} = 1;
                   11255:                 } else {
                   11256:                     $dependencies{$item} = 1;
                   11257:                 }
                   11258:                 if ($absolutepath) {
                   11259:                     $mapping{$item} = $absolutepath;
                   11260:                 } else {
                   11261:                     $mapping{$item} = $embed_file;
                   11262:                 }
                   11263:             } else {
                   11264:                 $dependencies{$embed_file} = 1;
                   11265:                 if ($absolutepath) {
1.1147    raeburn  11266:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11267:                 } else {
1.1147    raeburn  11268:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11269:                 }
                   11270:             }
1.984     raeburn  11271:         }
                   11272:     }
1.1249    damieng  11273:     
                   11274:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11275:     # and lists
                   11276:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11277:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11278:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11279:     #                                    the path had to be cleaned up
                   11280:     # $existing: hash clean path -> 1 if the file exists
                   11281:     # $numexisting: number of keys in $existing
                   11282:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11283:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11284:     #                                      dependency subdirectories that are
                   11285:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11286:     my $dirptr = 16384;
1.984     raeburn  11287:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11288:         $currsubfile{$path} = {};
1.1123    raeburn  11289:         if (($actionurl eq '/adm/portfolio') || 
                   11290:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11291:             my ($sublistref,$listerror) =
                   11292:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11293:             if (ref($sublistref) eq 'ARRAY') {
                   11294:                 foreach my $line (@{$sublistref}) {
                   11295:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11296:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11297:                 }
1.984     raeburn  11298:             }
1.987     raeburn  11299:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11300:             if (opendir(my $dir,$url.'/'.$path)) {
                   11301:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11302:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11303:             }
1.1084    raeburn  11304:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11305:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11306:                   ($args->{'context'} eq 'paste')) ||
                   11307:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11308:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11309:                 my $dir;
                   11310:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11311:                     $dir = $fileloc;
                   11312:                 } else {
                   11313:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11314:                 }
1.1071    raeburn  11315:                 if ($dir ne '') {
                   11316:                     my ($sublistref,$listerror) =
                   11317:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11318:                     if (ref($sublistref) eq 'ARRAY') {
                   11319:                         foreach my $line (@{$sublistref}) {
                   11320:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11321:                                 undef,$mtime)=split(/\&/,$line,12);
                   11322:                             unless (($testdir&$dirptr) ||
                   11323:                                     ($file_name =~ /^\.\.?$/)) {
                   11324:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11325:                             }
                   11326:                         }
                   11327:                     }
                   11328:                 }
1.984     raeburn  11329:             }
                   11330:         }
                   11331:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11332:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11333:                 my $item = $path.'/'.$file;
                   11334:                 unless ($mapping{$item} eq $item) {
                   11335:                     $pathchanges{$item} = 1;
                   11336:                 }
                   11337:                 $existing{$item} = 1;
                   11338:                 $numexisting ++;
                   11339:             } else {
                   11340:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11341:             }
                   11342:         }
1.1071    raeburn  11343:         if ($actionurl eq '/adm/dependencies') {
                   11344:             foreach my $path (keys(%currsubfile)) {
                   11345:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11346:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11347:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11348:                              next if (($rem ne '') &&
                   11349:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11350:                                        (ref($navmap) &&
                   11351:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11352:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11353:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11354:                              $unused{$path.'/'.$file} = 1; 
                   11355:                          }
                   11356:                     }
                   11357:                 }
                   11358:             }
                   11359:         }
1.984     raeburn  11360:     }
1.1249    damieng  11361:     
                   11362:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11363:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11364:     my %currfile;
1.1123    raeburn  11365:     if (($actionurl eq '/adm/portfolio') ||
                   11366:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11367:         my ($dirlistref,$listerror) =
                   11368:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11369:         if (ref($dirlistref) eq 'ARRAY') {
                   11370:             foreach my $line (@{$dirlistref}) {
                   11371:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11372:                 $currfile{$file_name} = 1;
                   11373:             }
1.984     raeburn  11374:         }
1.987     raeburn  11375:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11376:         if (opendir(my $dir,$url)) {
1.987     raeburn  11377:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11378:             map {$currfile{$_} = 1;} @dir_list;
                   11379:         }
1.1084    raeburn  11380:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11381:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11382:               ($args->{'context'} eq 'paste')) ||
                   11383:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11384:         if ($env{'request.course.id'} ne '') {
                   11385:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11386:             if ($dir ne '') {
                   11387:                 my ($dirlistref,$listerror) =
                   11388:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11389:                 if (ref($dirlistref) eq 'ARRAY') {
                   11390:                     foreach my $line (@{$dirlistref}) {
                   11391:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11392:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11393:                         unless (($testdir&$dirptr) ||
                   11394:                                 ($file_name =~ /^\.\.?$/)) {
                   11395:                             $currfile{$file_name} = [$size,$mtime];
                   11396:                         }
                   11397:                     }
                   11398:                 }
                   11399:             }
                   11400:         }
1.984     raeburn  11401:     }
1.1249    damieng  11402:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11403:     # are not in subdirectories, using $currfile
1.984     raeburn  11404:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11405:         if (exists($currfile{$file})) {
1.987     raeburn  11406:             unless ($mapping{$file} eq $file) {
                   11407:                 $pathchanges{$file} = 1;
                   11408:             }
                   11409:             $existing{$file} = 1;
                   11410:             $numexisting ++;
                   11411:         } else {
1.984     raeburn  11412:             $newfiles{$file} = 1;
                   11413:         }
                   11414:     }
1.1071    raeburn  11415:     foreach my $file (keys(%currfile)) {
                   11416:         unless (($file eq $filename) ||
                   11417:                 ($file eq $filename.'.bak') ||
                   11418:                 ($dependencies{$file})) {
1.1085    raeburn  11419:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11420:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11421:                     next if (($rem ne '') &&
                   11422:                              (($env{"httpref.$rem".$file} ne '') ||
                   11423:                               (ref($navmap) &&
                   11424:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11425:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11426:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11427:                 }
1.1085    raeburn  11428:             }
1.1071    raeburn  11429:             $unused{$file} = 1;
                   11430:         }
                   11431:     }
1.1249    damieng  11432:     
                   11433:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11434:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11435:         ($args->{'context'} eq 'paste')) {
                   11436:         $counter = scalar(keys(%existing));
                   11437:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11438:         return ($output,$counter,$numpathchg,\%existing);
                   11439:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11440:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11441:         $counter = scalar(keys(%existing));
                   11442:         $numpathchg = scalar(keys(%pathchanges));
                   11443:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  11444:     }
1.1249    damieng  11445:     
                   11446:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   11447:     
                   11448:     # $upload_output: missing dependencies (with upload form)
                   11449:     # $modify_output: uploaded dependencies (in use)
                   11450:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  11451:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11452:         if ($actionurl eq '/adm/dependencies') {
                   11453:             next if ($embed_file =~ m{^\w+://});
                   11454:         }
1.660     raeburn  11455:         $upload_output .= &start_data_table_row().
1.1123    raeburn  11456:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11457:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11458:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  11459:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11460:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11461:         }
1.1123    raeburn  11462:         $upload_output .= '</td>';
1.1071    raeburn  11463:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  11464:             $upload_output.='<td align="right">'.
                   11465:                             '<span class="LC_info LC_fontsize_medium">'.
                   11466:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11467:             $numremref++;
1.660     raeburn  11468:         } elsif ($args->{'error_on_invalid_names'}
                   11469:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  11470:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11471:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11472:             $numinvalid++;
1.660     raeburn  11473:         } else {
1.1123    raeburn  11474:             $upload_output .= '<td>'.
                   11475:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11476:                                                      $embed_file,\%mapping,
1.1071    raeburn  11477:                                                      $allfiles,$codebase,'upload');
                   11478:             $counter ++;
                   11479:             $numnew ++;
1.987     raeburn  11480:         }
                   11481:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11482:     }
                   11483:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11484:         if ($actionurl eq '/adm/dependencies') {
                   11485:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11486:             $modify_output .= &start_data_table_row().
                   11487:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11488:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11489:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11490:                               '<td>'.$size.'</td>'.
                   11491:                               '<td>'.$mtime.'</td>'.
                   11492:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11493:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11494:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11495:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11496:                               &embedded_file_element('upload_embedded',$counter,
                   11497:                                                      $embed_file,\%mapping,
                   11498:                                                      $allfiles,$codebase,'modify').
                   11499:                               '</div></td>'.
                   11500:                               &end_data_table_row()."\n";
                   11501:             $counter ++;
                   11502:         } else {
                   11503:             $upload_output .= &start_data_table_row().
1.1123    raeburn  11504:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11505:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11506:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11507:                               &Apache::loncommon::end_data_table_row()."\n";
                   11508:         }
                   11509:     }
                   11510:     my $delidx = $counter;
                   11511:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11512:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11513:         $delete_output .= &start_data_table_row().
                   11514:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11515:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11516:                           '<td>'.$size.'</td>'.
                   11517:                           '<td>'.$mtime.'</td>'.
                   11518:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11519:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11520:                           &embedded_file_element('upload_embedded',$delidx,
                   11521:                                                  $oldfile,\%mapping,$allfiles,
                   11522:                                                  $codebase,'delete').'</td>'.
                   11523:                           &end_data_table_row()."\n"; 
                   11524:         $numunused ++;
                   11525:         $delidx ++;
1.987     raeburn  11526:     }
                   11527:     if ($upload_output) {
                   11528:         $upload_output = &start_data_table().
                   11529:                          $upload_output.
                   11530:                          &end_data_table()."\n";
                   11531:     }
1.1071    raeburn  11532:     if ($modify_output) {
                   11533:         $modify_output = &start_data_table().
                   11534:                          &start_data_table_header_row().
                   11535:                          '<th>'.&mt('File').'</th>'.
                   11536:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11537:                          '<th>'.&mt('Modified').'</th>'.
                   11538:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11539:                          &end_data_table_header_row().
                   11540:                          $modify_output.
                   11541:                          &end_data_table()."\n";
                   11542:     }
                   11543:     if ($delete_output) {
                   11544:         $delete_output = &start_data_table().
                   11545:                          &start_data_table_header_row().
                   11546:                          '<th>'.&mt('File').'</th>'.
                   11547:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11548:                          '<th>'.&mt('Modified').'</th>'.
                   11549:                          '<th>'.&mt('Delete?').'</th>'.
                   11550:                          &end_data_table_header_row().
                   11551:                          $delete_output.
                   11552:                          &end_data_table()."\n";
                   11553:     }
1.987     raeburn  11554:     my $applies = 0;
                   11555:     if ($numremref) {
                   11556:         $applies ++;
                   11557:     }
                   11558:     if ($numinvalid) {
                   11559:         $applies ++;
                   11560:     }
                   11561:     if ($numexisting) {
                   11562:         $applies ++;
                   11563:     }
1.1071    raeburn  11564:     if ($counter || $numunused) {
1.987     raeburn  11565:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11566:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11567:                   $state.'<h3>'.$heading.'</h3>'; 
                   11568:         if ($actionurl eq '/adm/dependencies') {
                   11569:             if ($numnew) {
                   11570:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11571:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11572:                            $upload_output.'<br />'."\n";
                   11573:             }
                   11574:             if ($numexisting) {
                   11575:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11576:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11577:                            $modify_output.'<br />'."\n";
                   11578:                            $buttontext = &mt('Save changes');
                   11579:             }
                   11580:             if ($numunused) {
                   11581:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11582:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11583:                            $delete_output.'<br />'."\n";
                   11584:                            $buttontext = &mt('Save changes');
                   11585:             }
                   11586:         } else {
                   11587:             $output .= $upload_output.'<br />'."\n";
                   11588:         }
                   11589:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11590:                    $counter.'" />'."\n";
                   11591:         if ($actionurl eq '/adm/dependencies') { 
                   11592:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11593:                        $numnew.'" />'."\n";
                   11594:         } elsif ($actionurl eq '') {
1.987     raeburn  11595:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11596:         }
                   11597:     } elsif ($applies) {
                   11598:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11599:         if ($applies > 1) {
                   11600:             $output .=  
1.1123    raeburn  11601:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11602:             if ($numremref) {
                   11603:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11604:             }
                   11605:             if ($numinvalid) {
                   11606:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11607:             }
                   11608:             if ($numexisting) {
                   11609:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11610:             }
                   11611:             $output .= '</ul><br />';
                   11612:         } elsif ($numremref) {
                   11613:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11614:         } elsif ($numinvalid) {
                   11615:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11616:         } elsif ($numexisting) {
                   11617:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11618:         }
                   11619:         $output .= $upload_output.'<br />';
                   11620:     }
                   11621:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11622:     $chgcount = $counter;
1.987     raeburn  11623:     if (keys(%pathchanges) > 0) {
                   11624:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11625:             if ($counter) {
1.987     raeburn  11626:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11627:                                                   $embed_file,\%mapping,
1.1071    raeburn  11628:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11629:             } else {
                   11630:                 $pathchange_output .= 
                   11631:                     &start_data_table_row().
                   11632:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11633:                     $chgcount.'" checked="checked" /></td>'.
                   11634:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11635:                     '<td>'.$embed_file.
                   11636:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11637:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11638:                     '</td>'.&end_data_table_row();
1.660     raeburn  11639:             }
1.987     raeburn  11640:             $numpathchg ++;
                   11641:             $chgcount ++;
1.660     raeburn  11642:         }
                   11643:     }
1.1127    raeburn  11644:     if (($counter) || ($numunused)) {
1.987     raeburn  11645:         if ($numpathchg) {
                   11646:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11647:                        $numpathchg.'" />'."\n";
                   11648:         }
                   11649:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11650:             ($actionurl eq '/adm/imsimport')) {
                   11651:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11652:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11653:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11654:         } elsif ($actionurl eq '/adm/dependencies') {
                   11655:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11656:         }
1.1123    raeburn  11657:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11658:     } elsif ($numpathchg) {
                   11659:         my %pathchange = ();
                   11660:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11661:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11662:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11663:         }
1.987     raeburn  11664:     }
1.1071    raeburn  11665:     return ($output,$counter,$numpathchg);
1.987     raeburn  11666: }
                   11667: 
1.1147    raeburn  11668: =pod
                   11669: 
                   11670: =item * clean_path($name)
                   11671: 
                   11672: Performs clean-up of directories, subdirectories and filename in an
                   11673: embedded object, referenced in an HTML file which is being uploaded
                   11674: to a course or portfolio, where 
                   11675: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11676: checked.
                   11677: 
                   11678: Clean-up is similar to replacements in lonnet::clean_filename()
                   11679: except each / between sub-directory and next level is preserved.
                   11680: 
                   11681: =cut
                   11682: 
                   11683: sub clean_path {
                   11684:     my ($embed_file) = @_;
                   11685:     $embed_file =~s{^/+}{};
                   11686:     my @contents;
                   11687:     if ($embed_file =~ m{/}) {
                   11688:         @contents = split(/\//,$embed_file);
                   11689:     } else {
                   11690:         @contents = ($embed_file);
                   11691:     }
                   11692:     my $lastidx = scalar(@contents)-1;
                   11693:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11694:         $contents[$i]=~s{\\}{/}g;
                   11695:         $contents[$i]=~s/\s+/\_/g;
                   11696:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11697:         if ($i == $lastidx) {
                   11698:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11699:         }
                   11700:     }
                   11701:     if ($lastidx > 0) {
                   11702:         return join('/',@contents);
                   11703:     } else {
                   11704:         return $contents[0];
                   11705:     }
                   11706: }
                   11707: 
1.987     raeburn  11708: sub embedded_file_element {
1.1071    raeburn  11709:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11710:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11711:                    (ref($codebase) eq 'HASH'));
                   11712:     my $output;
1.1071    raeburn  11713:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11714:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11715:     }
                   11716:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11717:                &escape($embed_file).'" />';
                   11718:     unless (($context eq 'upload_embedded') && 
                   11719:             ($mapping->{$embed_file} eq $embed_file)) {
                   11720:         $output .='
                   11721:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11722:     }
                   11723:     my $attrib;
                   11724:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11725:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11726:     }
                   11727:     $output .=
                   11728:         "\n\t\t".
                   11729:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11730:         $attrib.'" />';
                   11731:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11732:         $output .=
                   11733:             "\n\t\t".
                   11734:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11735:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11736:     }
1.987     raeburn  11737:     return $output;
1.660     raeburn  11738: }
                   11739: 
1.1071    raeburn  11740: sub get_dependency_details {
                   11741:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11742:     my ($size,$mtime,$showsize,$showmtime);
                   11743:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11744:         if ($embed_file =~ m{/}) {
                   11745:             my ($path,$fname) = split(/\//,$embed_file);
                   11746:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11747:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11748:             }
                   11749:         } else {
                   11750:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11751:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11752:             }
                   11753:         }
                   11754:         $showsize = $size/1024.0;
                   11755:         $showsize = sprintf("%.1f",$showsize);
                   11756:         if ($mtime > 0) {
                   11757:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11758:         }
                   11759:     }
                   11760:     return ($showsize,$showmtime);
                   11761: }
                   11762: 
                   11763: sub ask_embedded_js {
                   11764:     return <<"END";
                   11765: <script type="text/javascript"">
                   11766: // <![CDATA[
                   11767: function toggleBrowse(counter) {
                   11768:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11769:     var fileid = document.getElementById('embedded_item_'+counter);
                   11770:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11771:     if (chkboxid.checked == true) {
                   11772:         uploaddivid.style.display='block';
                   11773:     } else {
                   11774:         uploaddivid.style.display='none';
                   11775:         fileid.value = '';
                   11776:     }
                   11777: }
                   11778: // ]]>
                   11779: </script>
                   11780: 
                   11781: END
                   11782: }
                   11783: 
1.661     raeburn  11784: sub upload_embedded {
                   11785:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11786:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11787:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11788:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11789:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11790:         my $orig_uploaded_filename =
                   11791:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11792:         foreach my $type ('orig','ref','attrib','codebase') {
                   11793:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11794:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11795:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11796:             }
                   11797:         }
1.661     raeburn  11798:         my ($path,$fname) =
                   11799:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11800:         # no path, whole string is fname
                   11801:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11802:         $fname = &Apache::lonnet::clean_filename($fname);
                   11803:         # See if there is anything left
                   11804:         next if ($fname eq '');
                   11805: 
                   11806:         # Check if file already exists as a file or directory.
                   11807:         my ($state,$msg);
                   11808:         if ($context eq 'portfolio') {
                   11809:             my $port_path = $dirpath;
                   11810:             if ($group ne '') {
                   11811:                 $port_path = "groups/$group/$port_path";
                   11812:             }
1.987     raeburn  11813:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11814:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11815:                                               $dir_root,$port_path,$disk_quota,
                   11816:                                               $current_disk_usage,$uname,$udom);
                   11817:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11818:                 || $state eq 'file_locked') {
1.661     raeburn  11819:                 $output .= $msg;
                   11820:                 next;
                   11821:             }
                   11822:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11823:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11824:             if ($state eq 'exists') {
                   11825:                 $output .= $msg;
                   11826:                 next;
                   11827:             }
                   11828:         }
                   11829:         # Check if extension is valid
                   11830:         if (($fname =~ /\.(\w+)$/) &&
                   11831:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   11832:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11833:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11834:             next;
                   11835:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11836:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11837:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11838:             next;
                   11839:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   11840:             $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  11841:             next;
                   11842:         }
                   11843:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  11844:         my $subdir = $path;
                   11845:         $subdir =~ s{/+$}{};
1.661     raeburn  11846:         if ($context eq 'portfolio') {
1.984     raeburn  11847:             my $result;
                   11848:             if ($state eq 'existingfile') {
                   11849:                 $result=
                   11850:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  11851:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11852:             } else {
1.984     raeburn  11853:                 $result=
                   11854:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11855:                                                     $dirpath.
1.1123    raeburn  11856:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11857:                 if ($result !~ m|^/uploaded/|) {
                   11858:                     $output .= '<span class="LC_error">'
                   11859:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11860:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11861:                                .'</span><br />';
                   11862:                     next;
                   11863:                 } else {
1.987     raeburn  11864:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11865:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11866:                 }
1.661     raeburn  11867:             }
1.1123    raeburn  11868:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  11869:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11870:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11871:             my $result =
1.1126    raeburn  11872:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11873:             if ($result !~ m|^/uploaded/|) {
                   11874:                 $output .= '<span class="LC_error">'
                   11875:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11876:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11877:                            .'</span><br />';
                   11878:                     next;
                   11879:             } else {
                   11880:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11881:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11882:                 if ($context eq 'syllabus') {
                   11883:                     &Apache::lonnet::make_public_indefinitely($result);
                   11884:                 }
1.987     raeburn  11885:             }
1.661     raeburn  11886:         } else {
                   11887: # Save the file
                   11888:             my $target = $env{'form.embedded_item_'.$i};
                   11889:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11890:             my $dest = $fullpath.$fname;
                   11891:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11892:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11893:             my $count;
                   11894:             my $filepath = $dir_root;
1.1027    raeburn  11895:             foreach my $subdir (@parts) {
                   11896:                 $filepath .= "/$subdir";
                   11897:                 if (!-e $filepath) {
1.661     raeburn  11898:                     mkdir($filepath,0770);
                   11899:                 }
                   11900:             }
                   11901:             my $fh;
                   11902:             if (!open($fh,'>'.$dest)) {
                   11903:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11904:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11905:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11906:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11907:                            '</span><br />';
                   11908:             } else {
                   11909:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11910:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11911:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11912:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11913:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11914:                               '</span><br />';
                   11915:                 } else {
1.987     raeburn  11916:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11917:                                $url.'</span>').'<br />';
                   11918:                     unless ($context eq 'testbank') {
                   11919:                         $footer .= &mt('View embedded file: [_1]',
                   11920:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11921:                     }
                   11922:                 }
                   11923:                 close($fh);
                   11924:             }
                   11925:         }
                   11926:         if ($env{'form.embedded_ref_'.$i}) {
                   11927:             $pathchange{$i} = 1;
                   11928:         }
                   11929:     }
                   11930:     if ($output) {
                   11931:         $output = '<p>'.$output.'</p>';
                   11932:     }
                   11933:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11934:     $returnflag = 'ok';
1.1071    raeburn  11935:     my $numpathchgs = scalar(keys(%pathchange));
                   11936:     if ($numpathchgs > 0) {
1.987     raeburn  11937:         if ($context eq 'portfolio') {
                   11938:             $output .= '<p>'.&mt('or').'</p>';
                   11939:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11940:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11941:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11942:             $returnflag = 'modify_orightml';
                   11943:         }
                   11944:     }
1.1071    raeburn  11945:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11946: }
                   11947: 
                   11948: sub modify_html_form {
                   11949:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11950:     my $end = 0;
                   11951:     my $modifyform;
                   11952:     if ($context eq 'upload_embedded') {
                   11953:         return unless (ref($pathchange) eq 'HASH');
                   11954:         if ($env{'form.number_embedded_items'}) {
                   11955:             $end += $env{'form.number_embedded_items'};
                   11956:         }
                   11957:         if ($env{'form.number_pathchange_items'}) {
                   11958:             $end += $env{'form.number_pathchange_items'};
                   11959:         }
                   11960:         if ($end) {
                   11961:             for (my $i=0; $i<$end; $i++) {
                   11962:                 if ($i < $env{'form.number_embedded_items'}) {
                   11963:                     next unless($pathchange->{$i});
                   11964:                 }
                   11965:                 $modifyform .=
                   11966:                     &start_data_table_row().
                   11967:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11968:                     'checked="checked" /></td>'.
                   11969:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11970:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11971:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11972:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11973:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11974:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11975:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11976:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11977:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11978:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11979:                     &end_data_table_row();
1.1071    raeburn  11980:             }
1.987     raeburn  11981:         }
                   11982:     } else {
                   11983:         $modifyform = $pathchgtable;
                   11984:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11985:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11986:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11987:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11988:         }
                   11989:     }
                   11990:     if ($modifyform) {
1.1071    raeburn  11991:         if ($actionurl eq '/adm/dependencies') {
                   11992:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11993:         }
1.987     raeburn  11994:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11995:                '<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".
                   11996:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11997:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11998:                '</ol></p>'."\n".'<p>'.
                   11999:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12000:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12001:                &start_data_table()."\n".
                   12002:                &start_data_table_header_row().
                   12003:                '<th>'.&mt('Change?').'</th>'.
                   12004:                '<th>'.&mt('Current reference').'</th>'.
                   12005:                '<th>'.&mt('Required reference').'</th>'.
                   12006:                &end_data_table_header_row()."\n".
                   12007:                $modifyform.
                   12008:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12009:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12010:                '</form>'."\n";
                   12011:     }
                   12012:     return;
                   12013: }
                   12014: 
                   12015: sub modify_html_refs {
1.1123    raeburn  12016:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12017:     my $container;
                   12018:     if ($context eq 'portfolio') {
                   12019:         $container = $env{'form.container'};
                   12020:     } elsif ($context eq 'coursedoc') {
                   12021:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12022:     } elsif ($context eq 'manage_dependencies') {
                   12023:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12024:         $container = "/$container";
1.1123    raeburn  12025:     } elsif ($context eq 'syllabus') {
                   12026:         $container = $url;
1.987     raeburn  12027:     } else {
1.1027    raeburn  12028:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12029:     }
                   12030:     my (%allfiles,%codebase,$output,$content);
                   12031:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12032:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12033:         if (wantarray) {
                   12034:             return ('',0,0); 
                   12035:         } else {
                   12036:             return;
                   12037:         }
                   12038:     }
                   12039:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12040:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12041:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12042:             if (wantarray) {
                   12043:                 return ('',0,0);
                   12044:             } else {
                   12045:                 return;
                   12046:             }
                   12047:         } 
1.987     raeburn  12048:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12049:         if ($content eq '-1') {
                   12050:             if (wantarray) {
                   12051:                 return ('',0,0);
                   12052:             } else {
                   12053:                 return;
                   12054:             }
                   12055:         }
1.987     raeburn  12056:     } else {
1.1071    raeburn  12057:         unless ($container =~ /^\Q$dir_root\E/) {
                   12058:             if (wantarray) {
                   12059:                 return ('',0,0);
                   12060:             } else {
                   12061:                 return;
                   12062:             }
                   12063:         } 
1.987     raeburn  12064:         if (open(my $fh,"<$container")) {
                   12065:             $content = join('', <$fh>);
                   12066:             close($fh);
                   12067:         } else {
1.1071    raeburn  12068:             if (wantarray) {
                   12069:                 return ('',0,0);
                   12070:             } else {
                   12071:                 return;
                   12072:             }
1.987     raeburn  12073:         }
                   12074:     }
                   12075:     my ($count,$codebasecount) = (0,0);
                   12076:     my $mm = new File::MMagic;
                   12077:     my $mime_type = $mm->checktype_contents($content);
                   12078:     if ($mime_type eq 'text/html') {
                   12079:         my $parse_result = 
                   12080:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12081:                                                     \%codebase,\$content);
                   12082:         if ($parse_result eq 'ok') {
                   12083:             foreach my $i (@changes) {
                   12084:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12085:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12086:                 if ($allfiles{$ref}) {
                   12087:                     my $newname =  $orig;
                   12088:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12089:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12090:                     if ($attrib_regexp =~ /:/) {
                   12091:                         $attrib_regexp =~ s/\:/|/g;
                   12092:                     }
                   12093:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12094:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12095:                         $count += $numchg;
1.1123    raeburn  12096:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12097:                         delete($allfiles{$ref});
1.987     raeburn  12098:                     }
                   12099:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12100:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12101:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12102:                         $codebasecount ++;
                   12103:                     }
                   12104:                 }
                   12105:             }
1.1123    raeburn  12106:             my $skiprewrites;
1.987     raeburn  12107:             if ($count || $codebasecount) {
                   12108:                 my $saveresult;
1.1071    raeburn  12109:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12110:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12111:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12112:                     if ($url eq $container) {
                   12113:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12114:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12115:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12116:                                             $fname.'</span>').'</p>';
1.987     raeburn  12117:                     } else {
                   12118:                          $output = '<p class="LC_error">'.
                   12119:                                    &mt('Error: update failed for: [_1].',
                   12120:                                    '<span class="LC_filename">'.
                   12121:                                    $container.'</span>').'</p>';
                   12122:                     }
1.1123    raeburn  12123:                     if ($context eq 'syllabus') {
                   12124:                         unless ($saveresult eq 'ok') {
                   12125:                             $skiprewrites = 1;
                   12126:                         }
                   12127:                     }
1.987     raeburn  12128:                 } else {
                   12129:                     if (open(my $fh,">$container")) {
                   12130:                         print $fh $content;
                   12131:                         close($fh);
                   12132:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12133:                                   $count,'<span class="LC_filename">'.
                   12134:                                   $container.'</span>').'</p>';
1.661     raeburn  12135:                     } else {
1.987     raeburn  12136:                          $output = '<p class="LC_error">'.
                   12137:                                    &mt('Error: could not update [_1].',
                   12138:                                    '<span class="LC_filename">'.
                   12139:                                    $container.'</span>').'</p>';
1.661     raeburn  12140:                     }
                   12141:                 }
                   12142:             }
1.1123    raeburn  12143:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12144:                 my ($actionurl,$state);
                   12145:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12146:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12147:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12148:                                               \%codebase,
                   12149:                                               {'context' => 'rewrites',
                   12150:                                                'ignore_remote_references' => 1,});
                   12151:                 if (ref($mapping) eq 'HASH') {
                   12152:                     my $rewrites = 0;
                   12153:                     foreach my $key (keys(%{$mapping})) {
                   12154:                         next if ($key =~ m{^https?://});
                   12155:                         my $ref = $mapping->{$key};
                   12156:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12157:                         my $attrib;
                   12158:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12159:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12160:                         }
                   12161:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12162:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12163:                             $rewrites += $numchg;
                   12164:                         }
                   12165:                     }
                   12166:                     if ($rewrites) {
                   12167:                         my $saveresult; 
                   12168:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12169:                         if ($url eq $container) {
                   12170:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12171:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12172:                                             $count,'<span class="LC_filename">'.
                   12173:                                             $fname.'</span>').'</p>';
                   12174:                         } else {
                   12175:                             $output .= '<p class="LC_error">'.
                   12176:                                        &mt('Error: could not update links in [_1].',
                   12177:                                        '<span class="LC_filename">'.
                   12178:                                        $container.'</span>').'</p>';
                   12179: 
                   12180:                         }
                   12181:                     }
                   12182:                 }
                   12183:             }
1.987     raeburn  12184:         } else {
                   12185:             &logthis('Failed to parse '.$container.
                   12186:                      ' to modify references: '.$parse_result);
1.661     raeburn  12187:         }
                   12188:     }
1.1071    raeburn  12189:     if (wantarray) {
                   12190:         return ($output,$count,$codebasecount);
                   12191:     } else {
                   12192:         return $output;
                   12193:     }
1.661     raeburn  12194: }
                   12195: 
                   12196: sub check_for_existing {
                   12197:     my ($path,$fname,$element) = @_;
                   12198:     my ($state,$msg);
                   12199:     if (-d $path.'/'.$fname) {
                   12200:         $state = 'exists';
                   12201:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12202:     } elsif (-e $path.'/'.$fname) {
                   12203:         $state = 'exists';
                   12204:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12205:     }
                   12206:     if ($state eq 'exists') {
                   12207:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12208:     }
                   12209:     return ($state,$msg);
                   12210: }
                   12211: 
                   12212: sub check_for_upload {
                   12213:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12214:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12215:     my $filesize = length($env{'form.'.$element});
                   12216:     if (!$filesize) {
                   12217:         my $msg = '<span class="LC_error">'.
                   12218:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12219:                       '<span class="LC_filename">'.$fname.'</span>',
                   12220:                       $filesize).'<br />'.
1.1007    raeburn  12221:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12222:                   '</span>';
                   12223:         return ('zero_bytes',$msg);
                   12224:     }
                   12225:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12226:     my $getpropath = 1;
1.1021    raeburn  12227:     my ($dirlistref,$listerror) =
                   12228:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12229:     my $found_file = 0;
                   12230:     my $locked_file = 0;
1.991     raeburn  12231:     my @lockers;
                   12232:     my $navmap;
                   12233:     if ($env{'request.course.id'}) {
                   12234:         $navmap = Apache::lonnavmaps::navmap->new();
                   12235:     }
1.1021    raeburn  12236:     if (ref($dirlistref) eq 'ARRAY') {
                   12237:         foreach my $line (@{$dirlistref}) {
                   12238:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12239:             if ($file_name eq $fname){
                   12240:                 $file_name = $path.$file_name;
                   12241:                 if ($group ne '') {
                   12242:                     $file_name = $group.$file_name;
                   12243:                 }
                   12244:                 $found_file = 1;
                   12245:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12246:                     foreach my $lock (@lockers) {
                   12247:                         if (ref($lock) eq 'ARRAY') {
                   12248:                             my ($symb,$crsid) = @{$lock};
                   12249:                             if ($crsid eq $env{'request.course.id'}) {
                   12250:                                 if (ref($navmap)) {
                   12251:                                     my $res = $navmap->getBySymb($symb);
                   12252:                                     foreach my $part (@{$res->parts()}) { 
                   12253:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12254:                                         unless (($slot_status == $res->RESERVED) ||
                   12255:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12256:                                             $locked_file = 1;
                   12257:                                         }
1.991     raeburn  12258:                                     }
1.1021    raeburn  12259:                                 } else {
                   12260:                                     $locked_file = 1;
1.991     raeburn  12261:                                 }
                   12262:                             } else {
                   12263:                                 $locked_file = 1;
                   12264:                             }
                   12265:                         }
1.1021    raeburn  12266:                    }
                   12267:                 } else {
                   12268:                     my @info = split(/\&/,$rest);
                   12269:                     my $currsize = $info[6]/1000;
                   12270:                     if ($currsize < $filesize) {
                   12271:                         my $extra = $filesize - $currsize;
                   12272:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12273:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12274:                                       &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   12275:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12276:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12277:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12278:                             return ('will_exceed_quota',$msg);
                   12279:                         }
1.984     raeburn  12280:                     }
                   12281:                 }
1.661     raeburn  12282:             }
                   12283:         }
                   12284:     }
                   12285:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12286:         my $msg = '<p class="LC_warning">'.
                   12287:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12288:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12289:         return ('will_exceed_quota',$msg);
                   12290:     } elsif ($found_file) {
                   12291:         if ($locked_file) {
1.1179    bisitz   12292:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12293:             $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   12294:             $msg .= '</p>';
1.661     raeburn  12295:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12296:             return ('file_locked',$msg);
                   12297:         } else {
1.1179    bisitz   12298:             my $msg = '<p class="LC_error">';
1.984     raeburn  12299:             $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   12300:             $msg .= '</p>';
1.984     raeburn  12301:             return ('existingfile',$msg);
1.661     raeburn  12302:         }
                   12303:     }
                   12304: }
                   12305: 
1.987     raeburn  12306: sub check_for_traversal {
                   12307:     my ($path,$url,$toplevel) = @_;
                   12308:     my @parts=split(/\//,$path);
                   12309:     my $cleanpath;
                   12310:     my $fullpath = $url;
                   12311:     for (my $i=0;$i<@parts;$i++) {
                   12312:         next if ($parts[$i] eq '.');
                   12313:         if ($parts[$i] eq '..') {
                   12314:             $fullpath =~ s{([^/]+/)$}{};
                   12315:         } else {
                   12316:             $fullpath .= $parts[$i].'/';
                   12317:         }
                   12318:     }
                   12319:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12320:         $cleanpath = $1;
                   12321:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12322:         my $curr_toprel = $1;
                   12323:         my @parts = split(/\//,$curr_toprel);
                   12324:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12325:         my @urlparts = split(/\//,$url_toprel);
                   12326:         my $doubledots;
                   12327:         my $startdiff = -1;
                   12328:         for (my $i=0; $i<@urlparts; $i++) {
                   12329:             if ($startdiff == -1) {
                   12330:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12331:                     $startdiff = $i;
                   12332:                     $doubledots .= '../';
                   12333:                 }
                   12334:             } else {
                   12335:                 $doubledots .= '../';
                   12336:             }
                   12337:         }
                   12338:         if ($startdiff > -1) {
                   12339:             $cleanpath = $doubledots;
                   12340:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12341:                 $cleanpath .= $parts[$i].'/';
                   12342:             }
                   12343:         }
                   12344:     }
                   12345:     $cleanpath =~ s{(/)$}{};
                   12346:     return $cleanpath;
                   12347: }
1.31      albertel 12348: 
1.1053    raeburn  12349: sub is_archive_file {
                   12350:     my ($mimetype) = @_;
                   12351:     if (($mimetype eq 'application/octet-stream') ||
                   12352:         ($mimetype eq 'application/x-stuffit') ||
                   12353:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12354:         return 1;
                   12355:     }
                   12356:     return;
                   12357: }
                   12358: 
                   12359: sub decompress_form {
1.1065    raeburn  12360:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12361:     my %lt = &Apache::lonlocal::texthash (
                   12362:         this => 'This file is an archive file.',
1.1067    raeburn  12363:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12364:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12365:         youm => 'You may wish to extract its contents.',
                   12366:         extr => 'Extract contents',
1.1067    raeburn  12367:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12368:         proa => 'Process automatically?',
1.1053    raeburn  12369:         yes  => 'Yes',
                   12370:         no   => 'No',
1.1067    raeburn  12371:         fold => 'Title for folder containing movie',
                   12372:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12373:     );
1.1065    raeburn  12374:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12375:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12376:     my $info = &list_archive_contents($fileloc,\@paths);
                   12377:     if (@paths) {
                   12378:         foreach my $path (@paths) {
                   12379:             $path =~ s{^/}{};
1.1067    raeburn  12380:             if ($path =~ m{^([^/]+)/$}) {
                   12381:                 $topdir = $1;
                   12382:             }
1.1065    raeburn  12383:             if ($path =~ m{^([^/]+)/}) {
                   12384:                 $toplevel{$1} = $path;
                   12385:             } else {
                   12386:                 $toplevel{$path} = $path;
                   12387:             }
                   12388:         }
                   12389:     }
1.1067    raeburn  12390:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12391:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12392:                         "$topdir/media/",
                   12393:                         "$topdir/media/$topdir.mp4",
                   12394:                         "$topdir/media/FirstFrame.png",
                   12395:                         "$topdir/media/player.swf",
                   12396:                         "$topdir/media/swfobject.js",
                   12397:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12398:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12399:                          "$topdir/$topdir.mp4",
                   12400:                          "$topdir/$topdir\_config.xml",
                   12401:                          "$topdir/$topdir\_controller.swf",
                   12402:                          "$topdir/$topdir\_embed.css",
                   12403:                          "$topdir/$topdir\_First_Frame.png",
                   12404:                          "$topdir/$topdir\_player.html",
                   12405:                          "$topdir/$topdir\_Thumbnails.png",
                   12406:                          "$topdir/playerProductInstall.swf",
                   12407:                          "$topdir/scripts/",
                   12408:                          "$topdir/scripts/config_xml.js",
                   12409:                          "$topdir/scripts/handlebars.js",
                   12410:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12411:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12412:                          "$topdir/scripts/modernizr.js",
                   12413:                          "$topdir/scripts/player-min.js",
                   12414:                          "$topdir/scripts/swfobject.js",
                   12415:                          "$topdir/skins/",
                   12416:                          "$topdir/skins/configuration_express.xml",
                   12417:                          "$topdir/skins/express_show/",
                   12418:                          "$topdir/skins/express_show/player-min.css",
                   12419:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12420:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12421:                          "$topdir/$topdir.mp4",
                   12422:                          "$topdir/$topdir\_config.xml",
                   12423:                          "$topdir/$topdir\_controller.swf",
                   12424:                          "$topdir/$topdir\_embed.css",
                   12425:                          "$topdir/$topdir\_First_Frame.png",
                   12426:                          "$topdir/$topdir\_player.html",
                   12427:                          "$topdir/$topdir\_Thumbnails.png",
                   12428:                          "$topdir/playerProductInstall.swf",
                   12429:                          "$topdir/scripts/",
                   12430:                          "$topdir/scripts/config_xml.js",
                   12431:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12432:                          "$topdir/skins/",
                   12433:                          "$topdir/skins/configuration_express.xml",
                   12434:                          "$topdir/skins/express_show/",
                   12435:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12436:                          "$topdir/skins/express_show/spritesheet.png",
                   12437:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12438:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12439:         if (@diffs == 0) {
1.1164    raeburn  12440:             $is_camtasia = 6;
                   12441:         } else {
1.1197    raeburn  12442:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12443:             if (@diffs == 0) {
                   12444:                 $is_camtasia = 8;
1.1197    raeburn  12445:             } else {
                   12446:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12447:                 if (@diffs == 0) {
                   12448:                     $is_camtasia = 8;
                   12449:                 }
1.1164    raeburn  12450:             }
1.1067    raeburn  12451:         }
                   12452:     }
                   12453:     my $output;
                   12454:     if ($is_camtasia) {
                   12455:         $output = <<"ENDCAM";
                   12456: <script type="text/javascript" language="Javascript">
                   12457: // <![CDATA[
                   12458: 
                   12459: function camtasiaToggle() {
                   12460:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12461:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  12462:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12463:                 document.getElementById('camtasia_titles').style.display='block';
                   12464:             } else {
                   12465:                 document.getElementById('camtasia_titles').style.display='none';
                   12466:             }
                   12467:         }
                   12468:     }
                   12469:     return;
                   12470: }
                   12471: 
                   12472: // ]]>
                   12473: </script>
                   12474: <p>$lt{'camt'}</p>
                   12475: ENDCAM
1.1065    raeburn  12476:     } else {
1.1067    raeburn  12477:         $output = '<p>'.$lt{'this'};
                   12478:         if ($info eq '') {
                   12479:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12480:         } else {
                   12481:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12482:                        '<div><pre>'.$info.'</pre></div>';
                   12483:         }
1.1065    raeburn  12484:     }
1.1067    raeburn  12485:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12486:     my $duplicates;
                   12487:     my $num = 0;
                   12488:     if (ref($dirlist) eq 'ARRAY') {
                   12489:         foreach my $item (@{$dirlist}) {
                   12490:             if (ref($item) eq 'ARRAY') {
                   12491:                 if (exists($toplevel{$item->[0]})) {
                   12492:                     $duplicates .= 
                   12493:                         &start_data_table_row().
                   12494:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12495:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12496:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12497:                         'value="1" />'.&mt('Yes').'</label>'.
                   12498:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12499:                         '<td>'.$item->[0].'</td>';
                   12500:                     if ($item->[2]) {
                   12501:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12502:                     } else {
                   12503:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12504:                     }
                   12505:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12506:                                    '<td>'.
                   12507:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12508:                                    '</td>'.
                   12509:                                    &end_data_table_row();
                   12510:                     $num ++;
                   12511:                 }
                   12512:             }
                   12513:         }
                   12514:     }
                   12515:     my $itemcount;
                   12516:     if (@paths > 0) {
                   12517:         $itemcount = scalar(@paths);
                   12518:     } else {
                   12519:         $itemcount = 1;
                   12520:     }
1.1067    raeburn  12521:     if ($is_camtasia) {
                   12522:         $output .= $lt{'auto'}.'<br />'.
                   12523:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  12524:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12525:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12526:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12527:                    $lt{'no'}.'</label></span><br />'.
                   12528:                    '<div id="camtasia_titles" style="display:block">'.
                   12529:                    &Apache::lonhtmlcommon::start_pick_box().
                   12530:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12531:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12532:                    &Apache::lonhtmlcommon::row_closure().
                   12533:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12534:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12535:                    &Apache::lonhtmlcommon::row_closure(1).
                   12536:                    &Apache::lonhtmlcommon::end_pick_box().
                   12537:                    '</div>';
                   12538:     }
1.1065    raeburn  12539:     $output .= 
                   12540:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12541:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12542:         "\n";
1.1065    raeburn  12543:     if ($duplicates ne '') {
                   12544:         $output .= '<p><span class="LC_warning">'.
                   12545:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12546:                    &start_data_table().
                   12547:                    &start_data_table_header_row().
                   12548:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12549:                    '<th>'.&mt('Name').'</th>'.
                   12550:                    '<th>'.&mt('Type').'</th>'.
                   12551:                    '<th>'.&mt('Size').'</th>'.
                   12552:                    '<th>'.&mt('Last modified').'</th>'.
                   12553:                    &end_data_table_header_row().
                   12554:                    $duplicates.
                   12555:                    &end_data_table().
                   12556:                    '</p>';
                   12557:     }
1.1067    raeburn  12558:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12559:     if (ref($hiddenelements) eq 'HASH') {
                   12560:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12561:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12562:         }
                   12563:     }
                   12564:     $output .= <<"END";
1.1067    raeburn  12565: <br />
1.1053    raeburn  12566: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12567: </form>
                   12568: $noextract
                   12569: END
                   12570:     return $output;
                   12571: }
                   12572: 
1.1065    raeburn  12573: sub decompression_utility {
                   12574:     my ($program) = @_;
                   12575:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12576:     my $location;
                   12577:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12578:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12579:                          '/usr/sbin/') {
                   12580:             if (-x $dir.$program) {
                   12581:                 $location = $dir.$program;
                   12582:                 last;
                   12583:             }
                   12584:         }
                   12585:     }
                   12586:     return $location;
                   12587: }
                   12588: 
                   12589: sub list_archive_contents {
                   12590:     my ($file,$pathsref) = @_;
                   12591:     my (@cmd,$output);
                   12592:     my $needsregexp;
                   12593:     if ($file =~ /\.zip$/) {
                   12594:         @cmd = (&decompression_utility('unzip'),"-l");
                   12595:         $needsregexp = 1;
                   12596:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12597:              ($file =~ /\.tgz$/)) {
                   12598:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12599:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12600:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12601:     } elsif ($file =~ m|\.tar$|) {
                   12602:         @cmd = (&decompression_utility('tar'),"-tf");
                   12603:     }
                   12604:     if (@cmd) {
                   12605:         undef($!);
                   12606:         undef($@);
                   12607:         if (open(my $fh,"-|", @cmd, $file)) {
                   12608:             while (my $line = <$fh>) {
                   12609:                 $output .= $line;
                   12610:                 chomp($line);
                   12611:                 my $item;
                   12612:                 if ($needsregexp) {
                   12613:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12614:                 } else {
                   12615:                     $item = $line;
                   12616:                 }
                   12617:                 if ($item ne '') {
                   12618:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12619:                         push(@{$pathsref},$item);
                   12620:                     } 
                   12621:                 }
                   12622:             }
                   12623:             close($fh);
                   12624:         }
                   12625:     }
                   12626:     return $output;
                   12627: }
                   12628: 
1.1053    raeburn  12629: sub decompress_uploaded_file {
                   12630:     my ($file,$dir) = @_;
                   12631:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12632:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12633:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12634:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12635:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12636:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12637:     my $decompressed = $env{'cgi.decompressed'};
                   12638:     &Apache::lonnet::delenv('cgi.file');
                   12639:     &Apache::lonnet::delenv('cgi.dir');
                   12640:     &Apache::lonnet::delenv('cgi.decompressed');
                   12641:     return ($decompressed,$result);
                   12642: }
                   12643: 
1.1055    raeburn  12644: sub process_decompression {
                   12645:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  12646:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12647:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12648:                &mt('Unexpected file path.').'</p>'."\n";
                   12649:     }
                   12650:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12651:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12652:                &mt('Unexpected course context.').'</p>'."\n";
                   12653:     }
1.1293    raeburn  12654:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  12655:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12656:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12657:     }
1.1055    raeburn  12658:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12659:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12660:         $error = &mt('Filename not a supported archive file type.').
                   12661:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12662:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12663:     } else {
                   12664:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12665:         if ($docuhome eq 'no_host') {
                   12666:             $error = &mt('Could not determine home server for course.');
                   12667:         } else {
                   12668:             my @ids=&Apache::lonnet::current_machine_ids();
                   12669:             my $currdir = "$dir_root/$destination";
                   12670:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12671:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12672:                        "$dir_root/$destination";
                   12673:             } else {
                   12674:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12675:                        "$dir_root/$docudom/$docuname/$destination";
                   12676:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12677:                     $error = &mt('Archive file not found.');
                   12678:                 }
                   12679:             }
1.1065    raeburn  12680:             my (@to_overwrite,@to_skip);
                   12681:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12682:                 my $total = $env{'form.archive_overwrite_total'};
                   12683:                 for (my $i=0; $i<$total; $i++) {
                   12684:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12685:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12686:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12687:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12688:                     }
                   12689:                 }
                   12690:             }
                   12691:             my $numskip = scalar(@to_skip);
1.1292    raeburn  12692:             my $numoverwrite = scalar(@to_overwrite);
                   12693:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  12694:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12695:             } elsif ($dir eq '') {
1.1055    raeburn  12696:                 $error = &mt('Directory containing archive file unavailable.');
                   12697:             } elsif (!$error) {
1.1065    raeburn  12698:                 my ($decompressed,$display);
1.1292    raeburn  12699:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12700:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12701:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  12702:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12703:                         ($decompressed,$display) = 
                   12704:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12705:                         foreach my $item (@to_skip) {
                   12706:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12707:                                 if (-f "$dir/$tempdir/$item") { 
                   12708:                                     unlink("$dir/$tempdir/$item");
                   12709:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  12710:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  12711:                                 }
                   12712:                             }
                   12713:                         }
                   12714:                         foreach my $item (@to_overwrite) {
                   12715:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12716:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12717:                                     if (-f "$dir/$item") {
                   12718:                                         unlink("$dir/$item");
                   12719:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  12720:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  12721:                                     }
                   12722:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12723:                                 }
1.1065    raeburn  12724:                             }
                   12725:                         }
1.1292    raeburn  12726:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  12727:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  12728:                         }
1.1065    raeburn  12729:                     }
                   12730:                 } else {
                   12731:                     ($decompressed,$display) = 
                   12732:                         &decompress_uploaded_file($file,$dir);
                   12733:                 }
1.1055    raeburn  12734:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12735:                     $output = '<p class="LC_info">'.
                   12736:                               &mt('Files extracted successfully from archive.').
                   12737:                               '</p>'."\n";
1.1055    raeburn  12738:                     my ($warning,$result,@contents);
                   12739:                     my ($newdirlistref,$newlisterror) =
                   12740:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12741:                                                  $docuname,1);
                   12742:                     my (%is_dir,%changes,@newitems);
                   12743:                     my $dirptr = 16384;
1.1065    raeburn  12744:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12745:                         foreach my $dir_line (@{$newdirlistref}) {
                   12746:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  12747:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  12748:                                 push(@newitems,$item);
                   12749:                                 if ($dirptr&$testdir) {
                   12750:                                     $is_dir{$item} = 1;
                   12751:                                 }
                   12752:                                 $changes{$item} = 1;
                   12753:                             }
                   12754:                         }
                   12755:                     }
                   12756:                     if (keys(%changes) > 0) {
                   12757:                         foreach my $item (sort(@newitems)) {
                   12758:                             if ($changes{$item}) {
                   12759:                                 push(@contents,$item);
                   12760:                             }
                   12761:                         }
                   12762:                     }
                   12763:                     if (@contents > 0) {
1.1067    raeburn  12764:                         my $wantform;
                   12765:                         unless ($env{'form.autoextract_camtasia'}) {
                   12766:                             $wantform = 1;
                   12767:                         }
1.1056    raeburn  12768:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12769:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12770:                                                                 $currdir,\%is_dir,
                   12771:                                                                 \%children,\%parent,
1.1056    raeburn  12772:                                                                 \@contents,\%dirorder,
                   12773:                                                                 \%titles,$wantform);
1.1055    raeburn  12774:                         if ($datatable ne '') {
                   12775:                             $output .= &archive_options_form('decompressed',$datatable,
                   12776:                                                              $count,$hiddenelem);
1.1065    raeburn  12777:                             my $startcount = 6;
1.1055    raeburn  12778:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12779:                                                            \%titles,\%children);
1.1055    raeburn  12780:                         }
1.1067    raeburn  12781:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  12782:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12783:                             my %displayed;
                   12784:                             my $total = 1;
                   12785:                             $env{'form.archive_directory'} = [];
                   12786:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12787:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12788:                                 $path =~ s{/$}{};
                   12789:                                 my $item;
                   12790:                                 if ($path ne '') {
                   12791:                                     $item = "$path/$titles{$i}";
                   12792:                                 } else {
                   12793:                                     $item = $titles{$i};
                   12794:                                 }
                   12795:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12796:                                 if ($item eq $contents[0]) {
                   12797:                                     push(@{$env{'form.archive_directory'}},$i);
                   12798:                                     $env{'form.archive_'.$i} = 'display';
                   12799:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12800:                                     $displayed{'folder'} = $i;
1.1164    raeburn  12801:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12802:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  12803:                                     $env{'form.archive_'.$i} = 'display';
                   12804:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12805:                                     $displayed{'web'} = $i;
                   12806:                                 } else {
1.1164    raeburn  12807:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12808:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12809:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12810:                                         push(@{$env{'form.archive_directory'}},$i);
                   12811:                                     }
                   12812:                                     $env{'form.archive_'.$i} = 'dependency';
                   12813:                                 }
                   12814:                                 $total ++;
                   12815:                             }
                   12816:                             for (my $i=1; $i<$total; $i++) {
                   12817:                                 next if ($i == $displayed{'web'});
                   12818:                                 next if ($i == $displayed{'folder'});
                   12819:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12820:                             }
                   12821:                             $env{'form.phase'} = 'decompress_cleanup';
                   12822:                             $env{'form.archivedelete'} = 1;
                   12823:                             $env{'form.archive_count'} = $total-1;
                   12824:                             $output .=
                   12825:                                 &process_extracted_files('coursedocs',$docudom,
                   12826:                                                          $docuname,$destination,
                   12827:                                                          $dir_root,$hiddenelem);
                   12828:                         }
1.1055    raeburn  12829:                     } else {
                   12830:                         $warning = &mt('No new items extracted from archive file.');
                   12831:                     }
                   12832:                 } else {
                   12833:                     $output = $display;
                   12834:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12835:                 }
                   12836:             }
                   12837:         }
                   12838:     }
                   12839:     if ($error) {
                   12840:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12841:                    $error.'</p>'."\n";
                   12842:     }
                   12843:     if ($warning) {
                   12844:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12845:     }
                   12846:     return $output;
                   12847: }
                   12848: 
                   12849: sub get_extracted {
1.1056    raeburn  12850:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12851:         $titles,$wantform) = @_;
1.1055    raeburn  12852:     my $count = 0;
                   12853:     my $depth = 0;
                   12854:     my $datatable;
1.1056    raeburn  12855:     my @hierarchy;
1.1055    raeburn  12856:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12857:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12858:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12859:     foreach my $item (@{$contents}) {
                   12860:         $count ++;
1.1056    raeburn  12861:         @{$dirorder->{$count}} = @hierarchy;
                   12862:         $titles->{$count} = $item;
1.1055    raeburn  12863:         &archive_hierarchy($depth,$count,$parent,$children);
                   12864:         if ($wantform) {
                   12865:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12866:                                        $currdir,$depth,$count);
                   12867:         }
                   12868:         if ($is_dir->{$item}) {
                   12869:             $depth ++;
1.1056    raeburn  12870:             push(@hierarchy,$count);
                   12871:             $parent->{$depth} = $count;
1.1055    raeburn  12872:             $datatable .=
                   12873:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12874:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12875:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12876:             $depth --;
1.1056    raeburn  12877:             pop(@hierarchy);
1.1055    raeburn  12878:         }
                   12879:     }
                   12880:     return ($count,$datatable);
                   12881: }
                   12882: 
                   12883: sub recurse_extracted_archive {
1.1056    raeburn  12884:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12885:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12886:     my $result='';
1.1056    raeburn  12887:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12888:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12889:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12890:         return $result;
                   12891:     }
                   12892:     my $dirptr = 16384;
                   12893:     my ($newdirlistref,$newlisterror) =
                   12894:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12895:     if (ref($newdirlistref) eq 'ARRAY') {
                   12896:         foreach my $dir_line (@{$newdirlistref}) {
                   12897:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12898:             unless ($item =~ /^\.+$/) {
                   12899:                 $$count ++;
1.1056    raeburn  12900:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12901:                 $titles->{$$count} = $item;
1.1055    raeburn  12902:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12903: 
1.1055    raeburn  12904:                 my $is_dir;
                   12905:                 if ($dirptr&$testdir) {
                   12906:                     $is_dir = 1;
                   12907:                 }
                   12908:                 if ($wantform) {
                   12909:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12910:                 }
                   12911:                 if ($is_dir) {
                   12912:                     $$depth ++;
1.1056    raeburn  12913:                     push(@{$hierarchy},$$count);
                   12914:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12915:                     $result .=
                   12916:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12917:                                                    $docuname,$depth,$count,
1.1056    raeburn  12918:                                                    $hierarchy,$dirorder,$children,
                   12919:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12920:                     $$depth --;
1.1056    raeburn  12921:                     pop(@{$hierarchy});
1.1055    raeburn  12922:                 }
                   12923:             }
                   12924:         }
                   12925:     }
                   12926:     return $result;
                   12927: }
                   12928: 
                   12929: sub archive_hierarchy {
                   12930:     my ($depth,$count,$parent,$children) =@_;
                   12931:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12932:         if (exists($parent->{$depth})) {
                   12933:              $children->{$parent->{$depth}} .= $count.':';
                   12934:         }
                   12935:     }
                   12936:     return;
                   12937: }
                   12938: 
                   12939: sub archive_row {
                   12940:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12941:     my ($name) = ($item =~ m{([^/]+)$});
                   12942:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12943:                                        'display'    => 'Add as file',
1.1055    raeburn  12944:                                        'dependency' => 'Include as dependency',
                   12945:                                        'discard'    => 'Discard',
                   12946:                                       );
                   12947:     if ($is_dir) {
1.1059    raeburn  12948:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12949:     }
1.1056    raeburn  12950:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12951:     my $offset = 0;
1.1055    raeburn  12952:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12953:         $offset ++;
1.1065    raeburn  12954:         if ($action ne 'display') {
                   12955:             $offset ++;
                   12956:         }  
1.1055    raeburn  12957:         $output .= '<td><span class="LC_nobreak">'.
                   12958:                    '<label><input type="radio" name="archive_'.$count.
                   12959:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12960:         my $text = $choices{$action};
                   12961:         if ($is_dir) {
                   12962:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12963:             if ($action eq 'display') {
1.1059    raeburn  12964:                 $text = &mt('Add as folder');
1.1055    raeburn  12965:             }
1.1056    raeburn  12966:         } else {
                   12967:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12968: 
                   12969:         }
                   12970:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12971:         if ($action eq 'dependency') {
                   12972:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12973:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12974:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12975:                        '<option value=""></option>'."\n".
                   12976:                        '</select>'."\n".
                   12977:                        '</div>';
1.1059    raeburn  12978:         } elsif ($action eq 'display') {
                   12979:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12980:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12981:                        '</div>';
1.1055    raeburn  12982:         }
1.1056    raeburn  12983:         $output .= '</td>';
1.1055    raeburn  12984:     }
                   12985:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12986:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12987:     for (my $i=0; $i<$depth; $i++) {
                   12988:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12989:     }
                   12990:     if ($is_dir) {
                   12991:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12992:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12993:     } else {
                   12994:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12995:     }
                   12996:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12997:                &end_data_table_row();
                   12998:     return $output;
                   12999: }
                   13000: 
                   13001: sub archive_options_form {
1.1065    raeburn  13002:     my ($form,$display,$count,$hiddenelem) = @_;
                   13003:     my %lt = &Apache::lonlocal::texthash(
                   13004:                perm => 'Permanently remove archive file?',
                   13005:                hows => 'How should each extracted item be incorporated in the course?',
                   13006:                cont => 'Content actions for all',
                   13007:                addf => 'Add as folder/file',
                   13008:                incd => 'Include as dependency for a displayed file',
                   13009:                disc => 'Discard',
                   13010:                no   => 'No',
                   13011:                yes  => 'Yes',
                   13012:                save => 'Save',
                   13013:     );
                   13014:     my $output = <<"END";
                   13015: <form name="$form" method="post" action="">
                   13016: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13017: <label>
                   13018:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13019: </label>
                   13020: &nbsp;
                   13021: <label>
                   13022:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13023: </span>
                   13024: </p>
                   13025: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13026: <br />$lt{'hows'}
                   13027: <div class="LC_columnSection">
                   13028:   <fieldset>
                   13029:     <legend>$lt{'cont'}</legend>
                   13030:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13031:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13032:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13033:   </fieldset>
                   13034: </div>
                   13035: END
                   13036:     return $output.
1.1055    raeburn  13037:            &start_data_table()."\n".
1.1065    raeburn  13038:            $display."\n".
1.1055    raeburn  13039:            &end_data_table()."\n".
                   13040:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13041:            $hiddenelem.
1.1065    raeburn  13042:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13043:            '</form>';
                   13044: }
                   13045: 
                   13046: sub archive_javascript {
1.1056    raeburn  13047:     my ($startcount,$numitems,$titles,$children) = @_;
                   13048:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13049:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13050:     my $scripttag = <<START;
                   13051: <script type="text/javascript">
                   13052: // <![CDATA[
                   13053: 
                   13054: function checkAll(form,prefix) {
                   13055:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13056:     for (var i=0; i < form.elements.length; i++) {
                   13057:         var id = form.elements[i].id;
                   13058:         if ((id != '') && (id != undefined)) {
                   13059:             if (idstr.test(id)) {
                   13060:                 if (form.elements[i].type == 'radio') {
                   13061:                     form.elements[i].checked = true;
1.1056    raeburn  13062:                     var nostart = i-$startcount;
1.1059    raeburn  13063:                     var offset = nostart%7;
                   13064:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13065:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13066:                 }
                   13067:             }
                   13068:         }
                   13069:     }
                   13070: }
                   13071: 
                   13072: function propagateCheck(form,count) {
                   13073:     if (count > 0) {
1.1059    raeburn  13074:         var startelement = $startcount + ((count-1) * 7);
                   13075:         for (var j=1; j<6; j++) {
                   13076:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13077:                 var item = startelement + j; 
                   13078:                 if (form.elements[item].type == 'radio') {
                   13079:                     if (form.elements[item].checked) {
                   13080:                         containerCheck(form,count,j);
                   13081:                         break;
                   13082:                     }
1.1055    raeburn  13083:                 }
                   13084:             }
                   13085:         }
                   13086:     }
                   13087: }
                   13088: 
                   13089: numitems = $numitems
1.1056    raeburn  13090: var titles = new Array(numitems);
                   13091: var parents = new Array(numitems);
1.1055    raeburn  13092: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13093:     parents[i] = new Array;
1.1055    raeburn  13094: }
1.1059    raeburn  13095: var maintitle = '$maintitle';
1.1055    raeburn  13096: 
                   13097: START
                   13098: 
1.1056    raeburn  13099:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13100:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13101:         for (my $i=0; $i<@contents; $i ++) {
                   13102:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13103:         }
                   13104:     }
                   13105: 
1.1056    raeburn  13106:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13107:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13108:     }
                   13109: 
1.1055    raeburn  13110:     $scripttag .= <<END;
                   13111: 
                   13112: function containerCheck(form,count,offset) {
                   13113:     if (count > 0) {
1.1056    raeburn  13114:         dependencyCheck(form,count,offset);
1.1059    raeburn  13115:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13116:         form.elements[item].checked = true;
                   13117:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13118:             if (parents[count].length > 0) {
                   13119:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13120:                     containerCheck(form,parents[count][j],offset);
                   13121:                 }
                   13122:             }
                   13123:         }
                   13124:     }
                   13125: }
                   13126: 
                   13127: function dependencyCheck(form,count,offset) {
                   13128:     if (count > 0) {
1.1059    raeburn  13129:         var chosen = (offset+$startcount)+7*(count-1);
                   13130:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13131:         var currtype = form.elements[depitem].type;
                   13132:         if (form.elements[chosen].value == 'dependency') {
                   13133:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13134:             form.elements[depitem].options.length = 0;
                   13135:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13136:             for (var i=1; i<=numitems; i++) {
                   13137:                 if (i == count) {
                   13138:                     continue;
                   13139:                 }
1.1059    raeburn  13140:                 var startelement = $startcount + (i-1) * 7;
                   13141:                 for (var j=1; j<6; j++) {
                   13142:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13143:                         var item = startelement + j;
                   13144:                         if (form.elements[item].type == 'radio') {
                   13145:                             if (form.elements[item].checked) {
                   13146:                                 if (form.elements[item].value == 'display') {
                   13147:                                     var n = form.elements[depitem].options.length;
                   13148:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13149:                                 }
                   13150:                             }
                   13151:                         }
                   13152:                     }
                   13153:                 }
                   13154:             }
                   13155:         } else {
                   13156:             document.getElementById('arc_depon_'+count).style.display='none';
                   13157:             form.elements[depitem].options.length = 0;
                   13158:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13159:         }
1.1059    raeburn  13160:         titleCheck(form,count,offset);
1.1056    raeburn  13161:     }
                   13162: }
                   13163: 
                   13164: function propagateSelect(form,count,offset) {
                   13165:     if (count > 0) {
1.1065    raeburn  13166:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13167:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13168:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13169:             if (parents[count].length > 0) {
                   13170:                 for (var j=0; j<parents[count].length; j++) {
                   13171:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13172:                 }
                   13173:             }
                   13174:         }
                   13175:     }
                   13176: }
1.1056    raeburn  13177: 
                   13178: function containerSelect(form,count,offset,picked) {
                   13179:     if (count > 0) {
1.1065    raeburn  13180:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13181:         if (form.elements[item].type == 'radio') {
                   13182:             if (form.elements[item].value == 'dependency') {
                   13183:                 if (form.elements[item+1].type == 'select-one') {
                   13184:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13185:                         if (form.elements[item+1].options[i].value == picked) {
                   13186:                             form.elements[item+1].selectedIndex = i;
                   13187:                             break;
                   13188:                         }
                   13189:                     }
                   13190:                 }
                   13191:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13192:                     if (parents[count].length > 0) {
                   13193:                         for (var j=0; j<parents[count].length; j++) {
                   13194:                             containerSelect(form,parents[count][j],offset,picked);
                   13195:                         }
                   13196:                     }
                   13197:                 }
                   13198:             }
                   13199:         }
                   13200:     }
                   13201: }
                   13202: 
1.1059    raeburn  13203: function titleCheck(form,count,offset) {
                   13204:     if (count > 0) {
                   13205:         var chosen = (offset+$startcount)+7*(count-1);
                   13206:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13207:         var currtype = form.elements[depitem].type;
                   13208:         if (form.elements[chosen].value == 'display') {
                   13209:             document.getElementById('arc_title_'+count).style.display='block';
                   13210:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13211:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13212:             }
                   13213:         } else {
                   13214:             document.getElementById('arc_title_'+count).style.display='none';
                   13215:             if (currtype == 'text') { 
                   13216:                 document.getElementById('archive_title_'+count).value='';
                   13217:             }
                   13218:         }
                   13219:     }
                   13220:     return;
                   13221: }
                   13222: 
1.1055    raeburn  13223: // ]]>
                   13224: </script>
                   13225: END
                   13226:     return $scripttag;
                   13227: }
                   13228: 
                   13229: sub process_extracted_files {
1.1067    raeburn  13230:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13231:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  13232:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13233:     my @ids=&Apache::lonnet::current_machine_ids();
                   13234:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13235:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13236:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13237:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13238:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13239:         $pathtocheck = "$dir_root/$destination";
                   13240:         $dir = $dir_root;
                   13241:         $ishome = 1;
                   13242:     } else {
                   13243:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13244:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  13245:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13246:     }
                   13247:     my $currdir = "$dir_root/$destination";
                   13248:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13249:     if ($env{'form.folderpath'}) {
                   13250:         my @items = split('&',$env{'form.folderpath'});
                   13251:         $folders{'0'} = $items[-2];
1.1099    raeburn  13252:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13253:             $containers{'0'}='page';
                   13254:         } else {  
                   13255:             $containers{'0'}='sequence';
                   13256:         }
1.1055    raeburn  13257:     }
                   13258:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13259:     if ($numitems) {
                   13260:         for (my $i=1; $i<=$numitems; $i++) {
                   13261:             my $path = $env{'form.archive_content_'.$i};
                   13262:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13263:                 my $item = $1;
                   13264:                 $toplevelitems{$item} = $i;
                   13265:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13266:                     $is_dir{$item} = 1;
                   13267:                 }
                   13268:             }
                   13269:         }
                   13270:     }
1.1067    raeburn  13271:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13272:     if (keys(%toplevelitems) > 0) {
                   13273:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13274:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13275:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13276:     }
1.1066    raeburn  13277:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13278:     if ($numitems) {
                   13279:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13280:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13281:             my $path = $env{'form.archive_content_'.$i};
                   13282:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13283:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13284:                     if ($prefix ne '' && $path ne '') {
                   13285:                         if (-e $prefix.$path) {
1.1066    raeburn  13286:                             if ((@archdirs > 0) && 
                   13287:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13288:                                 $todeletedir{$prefix.$path} = 1;
                   13289:                             } else {
                   13290:                                 $todelete{$prefix.$path} = 1;
                   13291:                             }
1.1055    raeburn  13292:                         }
                   13293:                     }
                   13294:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13295:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13296:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13297:                     $docstitle = $env{'form.archive_title_'.$i};
                   13298:                     if ($docstitle eq '') {
                   13299:                         $docstitle = $title;
                   13300:                     }
1.1055    raeburn  13301:                     $outer = 0;
1.1056    raeburn  13302:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13303:                         if (@{$dirorder{$i}} > 0) {
                   13304:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13305:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13306:                                     $outer = $item;
                   13307:                                     last;
                   13308:                                 }
                   13309:                             }
                   13310:                         }
                   13311:                     }
                   13312:                     my ($errtext,$fatal) = 
                   13313:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13314:                                                '/'.$folders{$outer}.'.'.
                   13315:                                                $containers{$outer});
                   13316:                     next if ($fatal);
                   13317:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13318:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13319:                             $mapinner{$i} = time;
1.1055    raeburn  13320:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13321:                             $containers{$i} = 'sequence';
                   13322:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13323:                                       $folders{$i}.'.'.$containers{$i};
                   13324:                             my $newidx = &LONCAPA::map::getresidx();
                   13325:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13326:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13327:                             push(@LONCAPA::map::order,$newidx);
                   13328:                             my ($outtext,$errtext) =
                   13329:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13330:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13331:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13332:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13333:                             unless ($errtext) {
1.1294    raeburn  13334:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13335:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   13336:                                             '</li>'."\n";
1.1067    raeburn  13337:                             }
1.1055    raeburn  13338:                         }
                   13339:                     } else {
                   13340:                         if ($context eq 'coursedocs') {
                   13341:                             my $newidx=&LONCAPA::map::getresidx();
                   13342:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13343:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13344:                                       $title;
1.1294    raeburn  13345:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13346:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13347:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13348:                                 }
                   13349:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13350:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13351:                                 }
                   13352:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13353:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13354:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13355:                                         unless ($ishome) {
                   13356:                                             my $fetch = "$newdest{$i}/$title";
                   13357:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13358:                                             $prompttofetch{$fetch} = 1;
                   13359:                                         }
1.1292    raeburn  13360:                                     }
1.1067    raeburn  13361:                                 }
1.1294    raeburn  13362:                                 $LONCAPA::map::resources[$newidx]=
                   13363:                                     $docstitle.':'.$url.':false:normal:res';
                   13364:                                 push(@LONCAPA::map::order, $newidx);
                   13365:                                 my ($outtext,$errtext)=
                   13366:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13367:                                                             $docuname.'/'.$folders{$outer}.
                   13368:                                                             '.'.$containers{$outer},1,1);
                   13369:                                 unless ($errtext) {
                   13370:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13371:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13372:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13373:                                                    '</li>'."\n";
                   13374:                                     }
1.1067    raeburn  13375:                                 }
1.1294    raeburn  13376:                             } else {
                   13377:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13378:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  13379:                             }
1.1055    raeburn  13380:                         }
                   13381:                     }
1.1086    raeburn  13382:                 }
                   13383:             } else {
1.1294    raeburn  13384:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13385:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  13386:             }
                   13387:         }
                   13388:         for (my $i=1; $i<=$numitems; $i++) {
                   13389:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13390:             my $path = $env{'form.archive_content_'.$i};
                   13391:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13392:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13393:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13394:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13395:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13396:                         my ($itemidx,$fullpath,$relpath);
                   13397:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13398:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13399:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13400:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13401:                                     $itemidx = $j;
1.1056    raeburn  13402:                                 }
                   13403:                             }
1.1086    raeburn  13404:                         }
                   13405:                         if ($itemidx eq '') {
                   13406:                             $itemidx =  0;
                   13407:                         } 
                   13408:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13409:                             if ($mapinner{$referrer{$i}}) {
                   13410:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13411:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13412:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13413:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13414:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13415:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13416:                                             if (!-e $fullpath) {
                   13417:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13418:                                             }
                   13419:                                         }
1.1086    raeburn  13420:                                     } else {
                   13421:                                         last;
1.1056    raeburn  13422:                                     }
1.1086    raeburn  13423:                                 }
                   13424:                             }
                   13425:                         } elsif ($newdest{$referrer{$i}}) {
                   13426:                             $fullpath = $newdest{$referrer{$i}};
                   13427:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13428:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13429:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13430:                                     last;
                   13431:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13432:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13433:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13434:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13435:                                         if (!-e $fullpath) {
                   13436:                                             mkdir($fullpath,0755);
1.1056    raeburn  13437:                                         }
                   13438:                                     }
1.1086    raeburn  13439:                                 } else {
                   13440:                                     last;
1.1056    raeburn  13441:                                 }
1.1055    raeburn  13442:                             }
                   13443:                         }
1.1086    raeburn  13444:                         if ($fullpath ne '') {
                   13445:                             if (-e "$prefix$path") {
1.1292    raeburn  13446:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13447:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13448:                                 }
1.1086    raeburn  13449:                             }
                   13450:                             if (-e "$fullpath/$title") {
                   13451:                                 my $showpath;
                   13452:                                 if ($relpath ne '') {
                   13453:                                     $showpath = "$relpath/$title";
                   13454:                                 } else {
                   13455:                                     $showpath = "/$title";
                   13456:                                 } 
1.1294    raeburn  13457:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13458:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13459:                                            '</li>'."\n";
1.1292    raeburn  13460:                                 unless ($ishome) {
                   13461:                                     my $fetch = "$fullpath/$title";
                   13462:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   13463:                                     $prompttofetch{$fetch} = 1;
                   13464:                                 }
1.1086    raeburn  13465:                             }
                   13466:                         }
1.1055    raeburn  13467:                     }
1.1086    raeburn  13468:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13469:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  13470:                                     &HTML::Entities::encode($path,'<>&"'),
                   13471:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13472:                                 '<br />';
1.1055    raeburn  13473:                 }
                   13474:             } else {
1.1294    raeburn  13475:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  13476:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13477:             }
                   13478:         }
                   13479:         if (keys(%todelete)) {
                   13480:             foreach my $key (keys(%todelete)) {
                   13481:                 unlink($key);
1.1066    raeburn  13482:             }
                   13483:         }
                   13484:         if (keys(%todeletedir)) {
                   13485:             foreach my $key (keys(%todeletedir)) {
                   13486:                 rmdir($key);
                   13487:             }
                   13488:         }
                   13489:         foreach my $dir (sort(keys(%is_dir))) {
                   13490:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13491:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13492:             }
                   13493:         }
1.1067    raeburn  13494:         if ($result ne '') {
                   13495:             $output .= '<ul>'."\n".
                   13496:                        $result."\n".
                   13497:                        '</ul>';
                   13498:         }
                   13499:         unless ($ishome) {
                   13500:             my $replicationfail;
                   13501:             foreach my $item (keys(%prompttofetch)) {
                   13502:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13503:                 unless ($fetchresult eq 'ok') {
                   13504:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13505:                 }
                   13506:             }
                   13507:             if ($replicationfail) {
                   13508:                 $output .= '<p class="LC_error">'.
                   13509:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13510:                            $replicationfail.
                   13511:                            '</ul></p>';
                   13512:             }
                   13513:         }
1.1055    raeburn  13514:     } else {
                   13515:         $warning = &mt('No items found in archive.');
                   13516:     }
                   13517:     if ($error) {
                   13518:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13519:                    $error.'</p>'."\n";
                   13520:     }
                   13521:     if ($warning) {
                   13522:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13523:     }
                   13524:     return $output;
                   13525: }
                   13526: 
1.1066    raeburn  13527: sub cleanup_empty_dirs {
                   13528:     my ($path) = @_;
                   13529:     if (($path ne '') && (-d $path)) {
                   13530:         if (opendir(my $dirh,$path)) {
                   13531:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13532:             my $numitems = 0;
                   13533:             foreach my $item (@dircontents) {
                   13534:                 if (-d "$path/$item") {
1.1111    raeburn  13535:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13536:                     if (-e "$path/$item") {
                   13537:                         $numitems ++;
                   13538:                     }
                   13539:                 } else {
                   13540:                     $numitems ++;
                   13541:                 }
                   13542:             }
                   13543:             if ($numitems == 0) {
                   13544:                 rmdir($path);
                   13545:             }
                   13546:             closedir($dirh);
                   13547:         }
                   13548:     }
                   13549:     return;
                   13550: }
                   13551: 
1.41      ng       13552: =pod
1.45      matthew  13553: 
1.1162    raeburn  13554: =item * &get_folder_hierarchy()
1.1068    raeburn  13555: 
                   13556: Provides hierarchy of names of folders/sub-folders containing the current
                   13557: item,
                   13558: 
                   13559: Inputs: 3
                   13560:      - $navmap - navmaps object
                   13561: 
                   13562:      - $map - url for map (either the trigger itself, or map containing
                   13563:                            the resource, which is the trigger).
                   13564: 
                   13565:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13566: 
                   13567: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13568: 
                   13569: =cut
                   13570: 
                   13571: sub get_folder_hierarchy {
                   13572:     my ($navmap,$map,$showitem) = @_;
                   13573:     my @pathitems;
                   13574:     if (ref($navmap)) {
                   13575:         my $mapres = $navmap->getResourceByUrl($map);
                   13576:         if (ref($mapres)) {
                   13577:             my $pcslist = $mapres->map_hierarchy();
                   13578:             if ($pcslist ne '') {
                   13579:                 my @pcs = split(/,/,$pcslist);
                   13580:                 foreach my $pc (@pcs) {
                   13581:                     if ($pc == 1) {
1.1129    raeburn  13582:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13583:                     } else {
                   13584:                         my $res = $navmap->getByMapPc($pc);
                   13585:                         if (ref($res)) {
                   13586:                             my $title = $res->compTitle();
                   13587:                             $title =~ s/\W+/_/g;
                   13588:                             if ($title ne '') {
                   13589:                                 push(@pathitems,$title);
                   13590:                             }
                   13591:                         }
                   13592:                     }
                   13593:                 }
                   13594:             }
1.1071    raeburn  13595:             if ($showitem) {
                   13596:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  13597:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13598:                 } else {
                   13599:                     my $maptitle = $mapres->compTitle();
                   13600:                     $maptitle =~ s/\W+/_/g;
                   13601:                     if ($maptitle ne '') {
                   13602:                         push(@pathitems,$maptitle);
                   13603:                     }
1.1068    raeburn  13604:                 }
                   13605:             }
                   13606:         }
                   13607:     }
                   13608:     return @pathitems;
                   13609: }
                   13610: 
                   13611: =pod
                   13612: 
1.1015    raeburn  13613: =item * &get_turnedin_filepath()
                   13614: 
                   13615: Determines path in a user's portfolio file for storage of files uploaded
                   13616: to a specific essayresponse or dropbox item.
                   13617: 
                   13618: Inputs: 3 required + 1 optional.
                   13619: $symb is symb for resource, $uname and $udom are for current user (required).
                   13620: $caller is optional (can be "submission", if routine is called when storing
                   13621: an upoaded file when "Submit Answer" button was pressed).
                   13622: 
                   13623: Returns array containing $path and $multiresp. 
                   13624: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13625: than one file upload item.  Callers of routine should append partid as a 
                   13626: subdirectory to $path in cases where $multiresp is 1.
                   13627: 
                   13628: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13629: 
                   13630: =cut
                   13631: 
                   13632: sub get_turnedin_filepath {
                   13633:     my ($symb,$uname,$udom,$caller) = @_;
                   13634:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13635:     my $turnindir;
                   13636:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13637:     $turnindir = $userhash{'turnindir'};
                   13638:     my ($path,$multiresp);
                   13639:     if ($turnindir eq '') {
                   13640:         if ($caller eq 'submission') {
                   13641:             $turnindir = &mt('turned in');
                   13642:             $turnindir =~ s/\W+/_/g;
                   13643:             my %newhash = (
                   13644:                             'turnindir' => $turnindir,
                   13645:                           );
                   13646:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13647:         }
                   13648:     }
                   13649:     if ($turnindir ne '') {
                   13650:         $path = '/'.$turnindir.'/';
                   13651:         my ($multipart,$turnin,@pathitems);
                   13652:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13653:         if (defined($navmap)) {
                   13654:             my $mapres = $navmap->getResourceByUrl($map);
                   13655:             if (ref($mapres)) {
                   13656:                 my $pcslist = $mapres->map_hierarchy();
                   13657:                 if ($pcslist ne '') {
                   13658:                     foreach my $pc (split(/,/,$pcslist)) {
                   13659:                         my $res = $navmap->getByMapPc($pc);
                   13660:                         if (ref($res)) {
                   13661:                             my $title = $res->compTitle();
                   13662:                             $title =~ s/\W+/_/g;
                   13663:                             if ($title ne '') {
1.1149    raeburn  13664:                                 if (($pc > 1) && (length($title) > 12)) {
                   13665:                                     $title = substr($title,0,12);
                   13666:                                 }
1.1015    raeburn  13667:                                 push(@pathitems,$title);
                   13668:                             }
                   13669:                         }
                   13670:                     }
                   13671:                 }
                   13672:                 my $maptitle = $mapres->compTitle();
                   13673:                 $maptitle =~ s/\W+/_/g;
                   13674:                 if ($maptitle ne '') {
1.1149    raeburn  13675:                     if (length($maptitle) > 12) {
                   13676:                         $maptitle = substr($maptitle,0,12);
                   13677:                     }
1.1015    raeburn  13678:                     push(@pathitems,$maptitle);
                   13679:                 }
                   13680:                 unless ($env{'request.state'} eq 'construct') {
                   13681:                     my $res = $navmap->getBySymb($symb);
                   13682:                     if (ref($res)) {
                   13683:                         my $partlist = $res->parts();
                   13684:                         my $totaluploads = 0;
                   13685:                         if (ref($partlist) eq 'ARRAY') {
                   13686:                             foreach my $part (@{$partlist}) {
                   13687:                                 my @types = $res->responseType($part);
                   13688:                                 my @ids = $res->responseIds($part);
                   13689:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13690:                                     if ($types[$i] eq 'essay') {
                   13691:                                         my $partid = $part.'_'.$ids[$i];
                   13692:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13693:                                             $totaluploads ++;
                   13694:                                         }
                   13695:                                     }
                   13696:                                 }
                   13697:                             }
                   13698:                             if ($totaluploads > 1) {
                   13699:                                 $multiresp = 1;
                   13700:                             }
                   13701:                         }
                   13702:                     }
                   13703:                 }
                   13704:             } else {
                   13705:                 return;
                   13706:             }
                   13707:         } else {
                   13708:             return;
                   13709:         }
                   13710:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13711:         $restitle =~ s/\W+/_/g;
                   13712:         if ($restitle eq '') {
                   13713:             $restitle = ($resurl =~ m{/[^/]+$});
                   13714:             if ($restitle eq '') {
                   13715:                 $restitle = time;
                   13716:             }
                   13717:         }
1.1149    raeburn  13718:         if (length($restitle) > 12) {
                   13719:             $restitle = substr($restitle,0,12);
                   13720:         }
1.1015    raeburn  13721:         push(@pathitems,$restitle);
                   13722:         $path .= join('/',@pathitems);
                   13723:     }
                   13724:     return ($path,$multiresp);
                   13725: }
                   13726: 
                   13727: =pod
                   13728: 
1.464     albertel 13729: =back
1.41      ng       13730: 
1.112     bowersj2 13731: =head1 CSV Upload/Handling functions
1.38      albertel 13732: 
1.41      ng       13733: =over 4
                   13734: 
1.648     raeburn  13735: =item * &upfile_store($r)
1.41      ng       13736: 
                   13737: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13738: needs $env{'form.upfile'}
1.41      ng       13739: returns $datatoken to be put into hidden field
                   13740: 
                   13741: =cut
1.31      albertel 13742: 
                   13743: sub upfile_store {
                   13744:     my $r=shift;
1.258     albertel 13745:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13746:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13747:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13748:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13749: 
1.1299    raeburn  13750:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13751:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13752:                                      time.'_'.$$);
                   13753:     return if ($datatoken eq '');
                   13754: 
1.31      albertel 13755:     {
1.158     raeburn  13756:         my $datafile = $r->dir_config('lonDaemons').
                   13757:                            '/tmp/'.$datatoken.'.tmp';
                   13758:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13759:             print $fh $env{'form.upfile'};
1.158     raeburn  13760:             close($fh);
                   13761:         }
1.31      albertel 13762:     }
                   13763:     return $datatoken;
                   13764: }
                   13765: 
1.56      matthew  13766: =pod
                   13767: 
1.1290    raeburn  13768: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13769: 
                   13770: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  13771: $datatoken is the name to assign to the temporary file.
1.258     albertel 13772: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13773: 
                   13774: =cut
1.31      albertel 13775: 
                   13776: sub load_tmp_file {
1.1290    raeburn  13777:     my ($r,$datatoken) = @_;
                   13778:     return if ($datatoken eq '');
1.31      albertel 13779:     my @studentdata=();
                   13780:     {
1.158     raeburn  13781:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  13782:                               '/tmp/'.$datatoken.'.tmp';
1.158     raeburn  13783:         if ( open(my $fh,"<$studentfile") ) {
                   13784:             @studentdata=<$fh>;
                   13785:             close($fh);
                   13786:         }
1.31      albertel 13787:     }
1.258     albertel 13788:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13789: }
                   13790: 
1.1290    raeburn  13791: sub valid_datatoken {
                   13792:     my ($datatoken) = @_;
1.1291    raeburn  13793:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_$match_domain\_$match_courseid\_\d+_\d+$/) {
1.1290    raeburn  13794:         return $datatoken;
                   13795:     }
                   13796:     return;
                   13797: }
                   13798: 
1.56      matthew  13799: =pod
                   13800: 
1.648     raeburn  13801: =item * &upfile_record_sep()
1.41      ng       13802: 
                   13803: Separate uploaded file into records
                   13804: returns array of records,
1.258     albertel 13805: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13806: 
                   13807: =cut
1.31      albertel 13808: 
                   13809: sub upfile_record_sep {
1.258     albertel 13810:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13811:     } else {
1.248     albertel 13812: 	my @records;
1.258     albertel 13813: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13814: 	    if ($line=~/^\s*$/) { next; }
                   13815: 	    push(@records,$line);
                   13816: 	}
                   13817: 	return @records;
1.31      albertel 13818:     }
                   13819: }
                   13820: 
1.56      matthew  13821: =pod
                   13822: 
1.648     raeburn  13823: =item * &record_sep($record)
1.41      ng       13824: 
1.258     albertel 13825: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13826: 
                   13827: =cut
                   13828: 
1.263     www      13829: sub takeleft {
                   13830:     my $index=shift;
                   13831:     return substr('0000'.$index,-4,4);
                   13832: }
                   13833: 
1.31      albertel 13834: sub record_sep {
                   13835:     my $record=shift;
                   13836:     my %components=();
1.258     albertel 13837:     if ($env{'form.upfiletype'} eq 'xml') {
                   13838:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13839:         my $i=0;
1.356     albertel 13840:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13841:             $field=~s/^(\"|\')//;
                   13842:             $field=~s/(\"|\')$//;
1.263     www      13843:             $components{&takeleft($i)}=$field;
1.31      albertel 13844:             $i++;
                   13845:         }
1.258     albertel 13846:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13847:         my $i=0;
1.356     albertel 13848:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13849:             $field=~s/^(\"|\')//;
                   13850:             $field=~s/(\"|\')$//;
1.263     www      13851:             $components{&takeleft($i)}=$field;
1.31      albertel 13852:             $i++;
                   13853:         }
                   13854:     } else {
1.561     www      13855:         my $separator=',';
1.480     banghart 13856:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13857:             $separator=';';
1.480     banghart 13858:         }
1.31      albertel 13859:         my $i=0;
1.561     www      13860: # the character we are looking for to indicate the end of a quote or a record 
                   13861:         my $looking_for=$separator;
                   13862: # do not add the characters to the fields
                   13863:         my $ignore=0;
                   13864: # we just encountered a separator (or the beginning of the record)
                   13865:         my $just_found_separator=1;
                   13866: # store the field we are working on here
                   13867:         my $field='';
                   13868: # work our way through all characters in record
                   13869:         foreach my $character ($record=~/(.)/g) {
                   13870:             if ($character eq $looking_for) {
                   13871:                if ($character ne $separator) {
                   13872: # Found the end of a quote, again looking for separator
                   13873:                   $looking_for=$separator;
                   13874:                   $ignore=1;
                   13875:                } else {
                   13876: # Found a separator, store away what we got
                   13877:                   $components{&takeleft($i)}=$field;
                   13878: 	          $i++;
                   13879:                   $just_found_separator=1;
                   13880:                   $ignore=0;
                   13881:                   $field='';
                   13882:                }
                   13883:                next;
                   13884:             }
                   13885: # single or double quotation marks after a separator indicate beginning of a quote
                   13886: # we are now looking for the end of the quote and need to ignore separators
                   13887:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13888:                $looking_for=$character;
                   13889:                next;
                   13890:             }
                   13891: # ignore would be true after we reached the end of a quote
                   13892:             if ($ignore) { next; }
                   13893:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13894:             $field.=$character;
                   13895:             $just_found_separator=0; 
1.31      albertel 13896:         }
1.561     www      13897: # catch the very last entry, since we never encountered the separator
                   13898:         $components{&takeleft($i)}=$field;
1.31      albertel 13899:     }
                   13900:     return %components;
                   13901: }
                   13902: 
1.144     matthew  13903: ######################################################
                   13904: ######################################################
                   13905: 
1.56      matthew  13906: =pod
                   13907: 
1.648     raeburn  13908: =item * &upfile_select_html()
1.41      ng       13909: 
1.144     matthew  13910: Return HTML code to select a file from the users machine and specify 
                   13911: the file type.
1.41      ng       13912: 
                   13913: =cut
                   13914: 
1.144     matthew  13915: ######################################################
                   13916: ######################################################
1.31      albertel 13917: sub upfile_select_html {
1.144     matthew  13918:     my %Types = (
                   13919:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13920:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13921:                  space => &mt('Space separated'),
                   13922:                  tab   => &mt('Tabulator separated'),
                   13923: #                 xml   => &mt('HTML/XML'),
                   13924:                  );
                   13925:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13926:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13927:     foreach my $type (sort(keys(%Types))) {
                   13928:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13929:     }
                   13930:     $Str .= "</select>\n";
                   13931:     return $Str;
1.31      albertel 13932: }
                   13933: 
1.301     albertel 13934: sub get_samples {
                   13935:     my ($records,$toget) = @_;
                   13936:     my @samples=({});
                   13937:     my $got=0;
                   13938:     foreach my $rec (@$records) {
                   13939: 	my %temp = &record_sep($rec);
                   13940: 	if (! grep(/\S/, values(%temp))) { next; }
                   13941: 	if (%temp) {
                   13942: 	    $samples[$got]=\%temp;
                   13943: 	    $got++;
                   13944: 	    if ($got == $toget) { last; }
                   13945: 	}
                   13946:     }
                   13947:     return \@samples;
                   13948: }
                   13949: 
1.144     matthew  13950: ######################################################
                   13951: ######################################################
                   13952: 
1.56      matthew  13953: =pod
                   13954: 
1.648     raeburn  13955: =item * &csv_print_samples($r,$records)
1.41      ng       13956: 
                   13957: Prints a table of sample values from each column uploaded $r is an
                   13958: Apache Request ref, $records is an arrayref from
                   13959: &Apache::loncommon::upfile_record_sep
                   13960: 
                   13961: =cut
                   13962: 
1.144     matthew  13963: ######################################################
                   13964: ######################################################
1.31      albertel 13965: sub csv_print_samples {
                   13966:     my ($r,$records) = @_;
1.662     bisitz   13967:     my $samples = &get_samples($records,5);
1.301     albertel 13968: 
1.594     raeburn  13969:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13970:               &start_data_table_header_row());
1.356     albertel 13971:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13972:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13973:     $r->print(&end_data_table_header_row());
1.301     albertel 13974:     foreach my $hash (@$samples) {
1.594     raeburn  13975: 	$r->print(&start_data_table_row());
1.356     albertel 13976: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13977: 	    $r->print('<td>');
1.356     albertel 13978: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13979: 	    $r->print('</td>');
                   13980: 	}
1.594     raeburn  13981: 	$r->print(&end_data_table_row());
1.31      albertel 13982:     }
1.594     raeburn  13983:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13984: }
                   13985: 
1.144     matthew  13986: ######################################################
                   13987: ######################################################
                   13988: 
1.56      matthew  13989: =pod
                   13990: 
1.648     raeburn  13991: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13992: 
                   13993: Prints a table to create associations between values and table columns.
1.144     matthew  13994: 
1.41      ng       13995: $r is an Apache Request ref,
                   13996: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13997: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13998: 
                   13999: =cut
                   14000: 
1.144     matthew  14001: ######################################################
                   14002: ######################################################
1.31      albertel 14003: sub csv_print_select_table {
                   14004:     my ($r,$records,$d) = @_;
1.301     albertel 14005:     my $i=0;
                   14006:     my $samples = &get_samples($records,1);
1.144     matthew  14007:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14008: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14009:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14010:               '<th>'.&mt('Column').'</th>'.
                   14011:               &end_data_table_header_row()."\n");
1.356     albertel 14012:     foreach my $array_ref (@$d) {
                   14013: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14014: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14015: 
1.875     bisitz   14016: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14017: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14018: 	$r->print('<option value="none"></option>');
1.356     albertel 14019: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14020: 	    $r->print('<option value="'.$sample.'"'.
                   14021:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14022:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14023: 	}
1.594     raeburn  14024: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14025: 	$i++;
                   14026:     }
1.594     raeburn  14027:     $r->print(&end_data_table());
1.31      albertel 14028:     $i--;
                   14029:     return $i;
                   14030: }
1.56      matthew  14031: 
1.144     matthew  14032: ######################################################
                   14033: ######################################################
                   14034: 
1.56      matthew  14035: =pod
1.31      albertel 14036: 
1.648     raeburn  14037: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14038: 
                   14039: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14040: 
                   14041: $r is an Apache Request ref,
                   14042: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14043: $d is an array of 2 element arrays (internal name, displayed name)
                   14044: 
                   14045: =cut
                   14046: 
1.144     matthew  14047: ######################################################
                   14048: ######################################################
1.31      albertel 14049: sub csv_samples_select_table {
                   14050:     my ($r,$records,$d) = @_;
                   14051:     my $i=0;
1.144     matthew  14052:     #
1.662     bisitz   14053:     my $max_samples = 5;
                   14054:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14055:     $r->print(&start_data_table().
                   14056:               &start_data_table_header_row().'<th>'.
                   14057:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14058:               &end_data_table_header_row());
1.301     albertel 14059: 
                   14060:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14061: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14062: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14063: 	foreach my $option (@$d) {
                   14064: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14065: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14066:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14067:                       $display.'</option>');
1.31      albertel 14068: 	}
                   14069: 	$r->print('</select></td><td>');
1.662     bisitz   14070: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14071: 	    if (defined($samples->[$line]{$key})) { 
                   14072: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14073: 	    }
                   14074: 	}
1.594     raeburn  14075: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14076: 	$i++;
                   14077:     }
1.594     raeburn  14078:     $r->print(&end_data_table());
1.31      albertel 14079:     $i--;
                   14080:     return($i);
1.115     matthew  14081: }
                   14082: 
1.144     matthew  14083: ######################################################
                   14084: ######################################################
                   14085: 
1.115     matthew  14086: =pod
                   14087: 
1.648     raeburn  14088: =item * &clean_excel_name($name)
1.115     matthew  14089: 
                   14090: Returns a replacement for $name which does not contain any illegal characters.
                   14091: 
                   14092: =cut
                   14093: 
1.144     matthew  14094: ######################################################
                   14095: ######################################################
1.115     matthew  14096: sub clean_excel_name {
                   14097:     my ($name) = @_;
                   14098:     $name =~ s/[:\*\?\/\\]//g;
                   14099:     if (length($name) > 31) {
                   14100:         $name = substr($name,0,31);
                   14101:     }
                   14102:     return $name;
1.25      albertel 14103: }
1.84      albertel 14104: 
1.85      albertel 14105: =pod
                   14106: 
1.648     raeburn  14107: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14108: 
                   14109: Returns either 1 or undef
                   14110: 
                   14111: 1 if the part is to be hidden, undef if it is to be shown
                   14112: 
                   14113: Arguments are:
                   14114: 
                   14115: $id the id of the part to be checked
                   14116: $symb, optional the symb of the resource to check
                   14117: $udom, optional the domain of the user to check for
                   14118: $uname, optional the username of the user to check for
                   14119: 
                   14120: =cut
1.84      albertel 14121: 
                   14122: sub check_if_partid_hidden {
                   14123:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14124:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14125: 					 $symb,$udom,$uname);
1.141     albertel 14126:     my $truth=1;
                   14127:     #if the string starts with !, then the list is the list to show not hide
                   14128:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14129:     my @hiddenlist=split(/,/,$hiddenparts);
                   14130:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14131: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14132:     }
1.141     albertel 14133:     return !$truth;
1.84      albertel 14134: }
1.127     matthew  14135: 
1.138     matthew  14136: 
                   14137: ############################################################
                   14138: ############################################################
                   14139: 
                   14140: =pod
                   14141: 
1.157     matthew  14142: =back 
                   14143: 
1.138     matthew  14144: =head1 cgi-bin script and graphing routines
                   14145: 
1.157     matthew  14146: =over 4
                   14147: 
1.648     raeburn  14148: =item * &get_cgi_id()
1.138     matthew  14149: 
                   14150: Inputs: none
                   14151: 
                   14152: Returns an id which can be used to pass environment variables
                   14153: to various cgi-bin scripts.  These environment variables will
                   14154: be removed from the users environment after a given time by
                   14155: the routine &Apache::lonnet::transfer_profile_to_env.
                   14156: 
                   14157: =cut
                   14158: 
                   14159: ############################################################
                   14160: ############################################################
1.152     albertel 14161: my $uniq=0;
1.136     matthew  14162: sub get_cgi_id {
1.154     albertel 14163:     $uniq=($uniq+1)%100000;
1.280     albertel 14164:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14165: }
                   14166: 
1.127     matthew  14167: ############################################################
                   14168: ############################################################
                   14169: 
                   14170: =pod
                   14171: 
1.648     raeburn  14172: =item * &DrawBarGraph()
1.127     matthew  14173: 
1.138     matthew  14174: Facilitates the plotting of data in a (stacked) bar graph.
                   14175: Puts plot definition data into the users environment in order for 
                   14176: graph.png to plot it.  Returns an <img> tag for the plot.
                   14177: The bars on the plot are labeled '1','2',...,'n'.
                   14178: 
                   14179: Inputs:
                   14180: 
                   14181: =over 4
                   14182: 
                   14183: =item $Title: string, the title of the plot
                   14184: 
                   14185: =item $xlabel: string, text describing the X-axis of the plot
                   14186: 
                   14187: =item $ylabel: string, text describing the Y-axis of the plot
                   14188: 
                   14189: =item $Max: scalar, the maximum Y value to use in the plot
                   14190: If $Max is < any data point, the graph will not be rendered.
                   14191: 
1.140     matthew  14192: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14193: they are plotted.  If undefined, default values will be used.
                   14194: 
1.178     matthew  14195: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14196: 
1.138     matthew  14197: =item @Values: An array of array references.  Each array reference holds data
                   14198: to be plotted in a stacked bar chart.
                   14199: 
1.239     matthew  14200: =item If the final element of @Values is a hash reference the key/value
                   14201: pairs will be added to the graph definition.
                   14202: 
1.138     matthew  14203: =back
                   14204: 
                   14205: Returns:
                   14206: 
                   14207: An <img> tag which references graph.png and the appropriate identifying
                   14208: information for the plot.
                   14209: 
1.127     matthew  14210: =cut
                   14211: 
                   14212: ############################################################
                   14213: ############################################################
1.134     matthew  14214: sub DrawBarGraph {
1.178     matthew  14215:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14216:     #
                   14217:     if (! defined($colors)) {
                   14218:         $colors = ['#33ff00', 
                   14219:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14220:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14221:                   ]; 
                   14222:     }
1.228     matthew  14223:     my $extra_settings = {};
                   14224:     if (ref($Values[-1]) eq 'HASH') {
                   14225:         $extra_settings = pop(@Values);
                   14226:     }
1.127     matthew  14227:     #
1.136     matthew  14228:     my $identifier = &get_cgi_id();
                   14229:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14230:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14231:         return '';
                   14232:     }
1.225     matthew  14233:     #
                   14234:     my @Labels;
                   14235:     if (defined($labels)) {
                   14236:         @Labels = @$labels;
                   14237:     } else {
                   14238:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14239:             push(@Labels,$i+1);
1.225     matthew  14240:         }
                   14241:     }
                   14242:     #
1.129     matthew  14243:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14244:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14245:     my %ValuesHash;
                   14246:     my $NumSets=1;
                   14247:     foreach my $array (@Values) {
                   14248:         next if (! ref($array));
1.136     matthew  14249:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14250:             join(',',@$array);
1.129     matthew  14251:     }
1.127     matthew  14252:     #
1.136     matthew  14253:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14254:     if ($NumBars < 3) {
                   14255:         $width = 120+$NumBars*32;
1.220     matthew  14256:         $xskip = 1;
1.225     matthew  14257:         $bar_width = 30;
                   14258:     } elsif ($NumBars < 5) {
                   14259:         $width = 120+$NumBars*20;
                   14260:         $xskip = 1;
                   14261:         $bar_width = 20;
1.220     matthew  14262:     } elsif ($NumBars < 10) {
1.136     matthew  14263:         $width = 120+$NumBars*15;
                   14264:         $xskip = 1;
                   14265:         $bar_width = 15;
                   14266:     } elsif ($NumBars <= 25) {
                   14267:         $width = 120+$NumBars*11;
                   14268:         $xskip = 5;
                   14269:         $bar_width = 8;
                   14270:     } elsif ($NumBars <= 50) {
                   14271:         $width = 120+$NumBars*8;
                   14272:         $xskip = 5;
                   14273:         $bar_width = 4;
                   14274:     } else {
                   14275:         $width = 120+$NumBars*8;
                   14276:         $xskip = 5;
                   14277:         $bar_width = 4;
                   14278:     }
                   14279:     #
1.137     matthew  14280:     $Max = 1 if ($Max < 1);
                   14281:     if ( int($Max) < $Max ) {
                   14282:         $Max++;
                   14283:         $Max = int($Max);
                   14284:     }
1.127     matthew  14285:     $Title  = '' if (! defined($Title));
                   14286:     $xlabel = '' if (! defined($xlabel));
                   14287:     $ylabel = '' if (! defined($ylabel));
1.369     www      14288:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14289:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14290:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14291:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14292:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14293:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14294:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14295:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14296:     $ValuesHash{$id.'.height'}   = $height;
                   14297:     $ValuesHash{$id.'.width'}    = $width;
                   14298:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14299:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14300:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14301:     #
1.228     matthew  14302:     # Deal with other parameters
                   14303:     while (my ($key,$value) = each(%$extra_settings)) {
                   14304:         $ValuesHash{$id.'.'.$key} = $value;
                   14305:     }
                   14306:     #
1.646     raeburn  14307:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14308:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14309: }
                   14310: 
                   14311: ############################################################
                   14312: ############################################################
                   14313: 
                   14314: =pod
                   14315: 
1.648     raeburn  14316: =item * &DrawXYGraph()
1.137     matthew  14317: 
1.138     matthew  14318: Facilitates the plotting of data in an XY graph.
                   14319: Puts plot definition data into the users environment in order for 
                   14320: graph.png to plot it.  Returns an <img> tag for the plot.
                   14321: 
                   14322: Inputs:
                   14323: 
                   14324: =over 4
                   14325: 
                   14326: =item $Title: string, the title of the plot
                   14327: 
                   14328: =item $xlabel: string, text describing the X-axis of the plot
                   14329: 
                   14330: =item $ylabel: string, text describing the Y-axis of the plot
                   14331: 
                   14332: =item $Max: scalar, the maximum Y value to use in the plot
                   14333: If $Max is < any data point, the graph will not be rendered.
                   14334: 
                   14335: =item $colors: Array ref containing the hex color codes for the data to be 
                   14336: plotted in.  If undefined, default values will be used.
                   14337: 
                   14338: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14339: 
                   14340: =item $Ydata: Array ref containing Array refs.  
1.185     www      14341: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14342: 
                   14343: =item %Values: hash indicating or overriding any default values which are 
                   14344: passed to graph.png.  
                   14345: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14346: 
                   14347: =back
                   14348: 
                   14349: Returns:
                   14350: 
                   14351: An <img> tag which references graph.png and the appropriate identifying
                   14352: information for the plot.
                   14353: 
1.137     matthew  14354: =cut
                   14355: 
                   14356: ############################################################
                   14357: ############################################################
                   14358: sub DrawXYGraph {
                   14359:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14360:     #
                   14361:     # Create the identifier for the graph
                   14362:     my $identifier = &get_cgi_id();
                   14363:     my $id = 'cgi.'.$identifier;
                   14364:     #
                   14365:     $Title  = '' if (! defined($Title));
                   14366:     $xlabel = '' if (! defined($xlabel));
                   14367:     $ylabel = '' if (! defined($ylabel));
                   14368:     my %ValuesHash = 
                   14369:         (
1.369     www      14370:          $id.'.title'  => &escape($Title),
                   14371:          $id.'.xlabel' => &escape($xlabel),
                   14372:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14373:          $id.'.y_max_value'=> $Max,
                   14374:          $id.'.labels'     => join(',',@$Xlabels),
                   14375:          $id.'.PlotType'   => 'XY',
                   14376:          );
                   14377:     #
                   14378:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14379:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14380:     }
                   14381:     #
                   14382:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14383:         return '';
                   14384:     }
                   14385:     my $NumSets=1;
1.138     matthew  14386:     foreach my $array (@{$Ydata}){
1.137     matthew  14387:         next if (! ref($array));
                   14388:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14389:     }
1.138     matthew  14390:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14391:     #
                   14392:     # Deal with other parameters
                   14393:     while (my ($key,$value) = each(%Values)) {
                   14394:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14395:     }
                   14396:     #
1.646     raeburn  14397:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14398:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14399: }
                   14400: 
                   14401: ############################################################
                   14402: ############################################################
                   14403: 
                   14404: =pod
                   14405: 
1.648     raeburn  14406: =item * &DrawXYYGraph()
1.138     matthew  14407: 
                   14408: Facilitates the plotting of data in an XY graph with two Y axes.
                   14409: Puts plot definition data into the users environment in order for 
                   14410: graph.png to plot it.  Returns an <img> tag for the plot.
                   14411: 
                   14412: Inputs:
                   14413: 
                   14414: =over 4
                   14415: 
                   14416: =item $Title: string, the title of the plot
                   14417: 
                   14418: =item $xlabel: string, text describing the X-axis of the plot
                   14419: 
                   14420: =item $ylabel: string, text describing the Y-axis of the plot
                   14421: 
                   14422: =item $colors: Array ref containing the hex color codes for the data to be 
                   14423: plotted in.  If undefined, default values will be used.
                   14424: 
                   14425: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14426: 
                   14427: =item $Ydata1: The first data set
                   14428: 
                   14429: =item $Min1: The minimum value of the left Y-axis
                   14430: 
                   14431: =item $Max1: The maximum value of the left Y-axis
                   14432: 
                   14433: =item $Ydata2: The second data set
                   14434: 
                   14435: =item $Min2: The minimum value of the right Y-axis
                   14436: 
                   14437: =item $Max2: The maximum value of the left Y-axis
                   14438: 
                   14439: =item %Values: hash indicating or overriding any default values which are 
                   14440: passed to graph.png.  
                   14441: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14442: 
                   14443: =back
                   14444: 
                   14445: Returns:
                   14446: 
                   14447: An <img> tag which references graph.png and the appropriate identifying
                   14448: information for the plot.
1.136     matthew  14449: 
                   14450: =cut
                   14451: 
                   14452: ############################################################
                   14453: ############################################################
1.137     matthew  14454: sub DrawXYYGraph {
                   14455:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14456:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14457:     #
                   14458:     # Create the identifier for the graph
                   14459:     my $identifier = &get_cgi_id();
                   14460:     my $id = 'cgi.'.$identifier;
                   14461:     #
                   14462:     $Title  = '' if (! defined($Title));
                   14463:     $xlabel = '' if (! defined($xlabel));
                   14464:     $ylabel = '' if (! defined($ylabel));
                   14465:     my %ValuesHash = 
                   14466:         (
1.369     www      14467:          $id.'.title'  => &escape($Title),
                   14468:          $id.'.xlabel' => &escape($xlabel),
                   14469:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14470:          $id.'.labels' => join(',',@$Xlabels),
                   14471:          $id.'.PlotType' => 'XY',
                   14472:          $id.'.NumSets' => 2,
1.137     matthew  14473:          $id.'.two_axes' => 1,
                   14474:          $id.'.y1_max_value' => $Max1,
                   14475:          $id.'.y1_min_value' => $Min1,
                   14476:          $id.'.y2_max_value' => $Max2,
                   14477:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14478:          );
                   14479:     #
1.137     matthew  14480:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14481:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14482:     }
                   14483:     #
                   14484:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14485:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14486:         return '';
                   14487:     }
                   14488:     my $NumSets=1;
1.137     matthew  14489:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14490:         next if (! ref($array));
                   14491:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14492:     }
                   14493:     #
                   14494:     # Deal with other parameters
                   14495:     while (my ($key,$value) = each(%Values)) {
                   14496:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14497:     }
                   14498:     #
1.646     raeburn  14499:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14500:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14501: }
                   14502: 
                   14503: ############################################################
                   14504: ############################################################
                   14505: 
                   14506: =pod
                   14507: 
1.157     matthew  14508: =back 
                   14509: 
1.139     matthew  14510: =head1 Statistics helper routines?  
                   14511: 
                   14512: Bad place for them but what the hell.
                   14513: 
1.157     matthew  14514: =over 4
                   14515: 
1.648     raeburn  14516: =item * &chartlink()
1.139     matthew  14517: 
                   14518: Returns a link to the chart for a specific student.  
                   14519: 
                   14520: Inputs:
                   14521: 
                   14522: =over 4
                   14523: 
                   14524: =item $linktext: The text of the link
                   14525: 
                   14526: =item $sname: The students username
                   14527: 
                   14528: =item $sdomain: The students domain
                   14529: 
                   14530: =back
                   14531: 
1.157     matthew  14532: =back
                   14533: 
1.139     matthew  14534: =cut
                   14535: 
                   14536: ############################################################
                   14537: ############################################################
                   14538: sub chartlink {
                   14539:     my ($linktext, $sname, $sdomain) = @_;
                   14540:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14541:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14542:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14543:        '">'.$linktext.'</a>';
1.153     matthew  14544: }
                   14545: 
                   14546: #######################################################
                   14547: #######################################################
                   14548: 
                   14549: =pod
                   14550: 
                   14551: =head1 Course Environment Routines
1.157     matthew  14552: 
                   14553: =over 4
1.153     matthew  14554: 
1.648     raeburn  14555: =item * &restore_course_settings()
1.153     matthew  14556: 
1.648     raeburn  14557: =item * &store_course_settings()
1.153     matthew  14558: 
                   14559: Restores/Store indicated form parameters from the course environment.
                   14560: Will not overwrite existing values of the form parameters.
                   14561: 
                   14562: Inputs: 
                   14563: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14564: 
                   14565: a hash ref describing the data to be stored.  For example:
                   14566:    
                   14567: %Save_Parameters = ('Status' => 'scalar',
                   14568:     'chartoutputmode' => 'scalar',
                   14569:     'chartoutputdata' => 'scalar',
                   14570:     'Section' => 'array',
1.373     raeburn  14571:     'Group' => 'array',
1.153     matthew  14572:     'StudentData' => 'array',
                   14573:     'Maps' => 'array');
                   14574: 
                   14575: Returns: both routines return nothing
                   14576: 
1.631     raeburn  14577: =back
                   14578: 
1.153     matthew  14579: =cut
                   14580: 
                   14581: #######################################################
                   14582: #######################################################
                   14583: sub store_course_settings {
1.496     albertel 14584:     return &store_settings($env{'request.course.id'},@_);
                   14585: }
                   14586: 
                   14587: sub store_settings {
1.153     matthew  14588:     # save to the environment
                   14589:     # appenv the same items, just to be safe
1.300     albertel 14590:     my $udom  = $env{'user.domain'};
                   14591:     my $uname = $env{'user.name'};
1.496     albertel 14592:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14593:     my %SaveHash;
                   14594:     my %AppHash;
                   14595:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14596:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14597:         my $envname = 'environment.'.$basename;
1.258     albertel 14598:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14599:             # Save this value away
                   14600:             if ($type eq 'scalar' &&
1.258     albertel 14601:                 (! exists($env{$envname}) || 
                   14602:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14603:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14604:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14605:             } elsif ($type eq 'array') {
                   14606:                 my $stored_form;
1.258     albertel 14607:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14608:                     $stored_form = join(',',
                   14609:                                         map {
1.369     www      14610:                                             &escape($_);
1.258     albertel 14611:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14612:                 } else {
                   14613:                     $stored_form = 
1.369     www      14614:                         &escape($env{'form.'.$setting});
1.153     matthew  14615:                 }
                   14616:                 # Determine if the array contents are the same.
1.258     albertel 14617:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14618:                     $SaveHash{$basename} = $stored_form;
                   14619:                     $AppHash{$envname}   = $stored_form;
                   14620:                 }
                   14621:             }
                   14622:         }
                   14623:     }
                   14624:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14625:                                           $udom,$uname);
1.153     matthew  14626:     if ($put_result !~ /^(ok|delayed)/) {
                   14627:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14628:                                  'got error:'.$put_result);
                   14629:     }
                   14630:     # Make sure these settings stick around in this session, too
1.646     raeburn  14631:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14632:     return;
                   14633: }
                   14634: 
                   14635: sub restore_course_settings {
1.499     albertel 14636:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14637: }
                   14638: 
                   14639: sub restore_settings {
                   14640:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14641:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14642:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14643:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14644:             '.'.$setting;
1.258     albertel 14645:         if (exists($env{$envname})) {
1.153     matthew  14646:             if ($type eq 'scalar') {
1.258     albertel 14647:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14648:             } elsif ($type eq 'array') {
1.258     albertel 14649:                 $env{'form.'.$setting} = [ 
1.153     matthew  14650:                                            map { 
1.369     www      14651:                                                &unescape($_); 
1.258     albertel 14652:                                            } split(',',$env{$envname})
1.153     matthew  14653:                                            ];
                   14654:             }
                   14655:         }
                   14656:     }
1.127     matthew  14657: }
                   14658: 
1.618     raeburn  14659: #######################################################
                   14660: #######################################################
                   14661: 
                   14662: =pod
                   14663: 
                   14664: =head1 Domain E-mail Routines  
                   14665: 
                   14666: =over 4
                   14667: 
1.648     raeburn  14668: =item * &build_recipient_list()
1.618     raeburn  14669: 
1.1144    raeburn  14670: Build recipient lists for following types of e-mail:
1.766     raeburn  14671: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14672: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14673: module change checking, student/employee ID conflict checks, as
                   14674: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14675: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14676: 
                   14677: Inputs:
1.619     raeburn  14678: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14679: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14680: requestsmail, updatesmail, or idconflictsmail).
                   14681: 
1.619     raeburn  14682: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14683: 
1.619     raeburn  14684: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  14685: i.e., predates configuration by DC via domainprefs.pm
                   14686: 
                   14687: $requname username of requester (if mailing type is helpdeskmail)
                   14688: 
                   14689: $requdom domain of requester (if mailing type is helpdeskmail)
                   14690: 
                   14691: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14692: 
1.618     raeburn  14693: 
1.655     raeburn  14694: Returns: comma separated list of addresses to which to send e-mail.
                   14695: 
                   14696: =back
1.618     raeburn  14697: 
                   14698: =cut
                   14699: 
                   14700: ############################################################
                   14701: ############################################################
                   14702: sub build_recipient_list {
1.1297    raeburn  14703:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14704:     my @recipients;
1.1270    raeburn  14705:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14706:     my %domconfig =
1.1270    raeburn  14707:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14708:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14709:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14710:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14711:                 my @contacts = ('adminemail','supportemail');
                   14712:                 foreach my $item (@contacts) {
                   14713:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14714:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14715:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14716:                             push(@recipients,$addr);
                   14717:                         }
1.619     raeburn  14718:                     }
1.1270    raeburn  14719:                 }
                   14720:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14721:                 if ($mailing eq 'helpdeskmail') {
                   14722:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14723:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14724:                         my @ok_bccs;
                   14725:                         foreach my $bcc (@bccs) {
                   14726:                             $bcc =~ s/^\s+//g;
                   14727:                             $bcc =~ s/\s+$//g;
                   14728:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14729:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14730:                                     push(@ok_bccs,$bcc);
                   14731:                                 }
                   14732:                             }
                   14733:                         }
                   14734:                         if (@ok_bccs > 0) {
                   14735:                             $allbcc = join(', ',@ok_bccs);
                   14736:                         }
                   14737:                     }
                   14738:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14739:                 }
                   14740:             }
1.766     raeburn  14741:         } elsif ($origmail ne '') {
1.1270    raeburn  14742:             $lastresort = $origmail;
1.618     raeburn  14743:         }
1.1297    raeburn  14744:         if ($mailing eq 'helpdeskmail') {
                   14745:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14746:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14747:                 my ($inststatus,$inststatus_checked);
                   14748:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14749:                     ($env{'user.domain'} ne 'public')) {
                   14750:                     $inststatus_checked = 1;
                   14751:                     $inststatus = $env{'environment.inststatus'};
                   14752:                 }
                   14753:                 unless ($inststatus_checked) {
                   14754:                     if (($requname ne '') && ($requdom ne '')) {
                   14755:                         if (($requname =~ /^$match_username$/) &&
                   14756:                             ($requdom =~ /^$match_domain$/) &&
                   14757:                             (&Apache::lonnet::domain($requdom))) {
                   14758:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14759:                                                                       $requdom);
                   14760:                             unless ($requhome eq 'no_host') {
                   14761:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14762:                                 $inststatus = $userenv{'inststatus'};
                   14763:                                 $inststatus_checked = 1;
                   14764:                             }
                   14765:                         }
                   14766:                     }
                   14767:                 }
                   14768:                 unless ($inststatus_checked) {
                   14769:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14770:                         my %srch = (srchby     => 'email',
                   14771:                                     srchdomain => $defdom,
                   14772:                                     srchterm   => $reqemail,
                   14773:                                     srchtype   => 'exact');
                   14774:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   14775:                         foreach my $uname (keys(%srch_results)) {
                   14776:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14777:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14778:                                 $inststatus_checked = 1;
                   14779:                                 last;
                   14780:                             }
                   14781:                         }
                   14782:                         unless ($inststatus_checked) {
                   14783:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   14784:                             if ($dirsrchres eq 'ok') {
                   14785:                                 foreach my $uname (keys(%srch_results)) {
                   14786:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14787:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14788:                                         $inststatus_checked = 1;
                   14789:                                         last;
                   14790:                                     }
                   14791:                                 }
                   14792:                             }
                   14793:                         }
                   14794:                     }
                   14795:                 }
                   14796:                 if ($inststatus ne '') {
                   14797:                     foreach my $status (split(/\:/,$inststatus)) {
                   14798:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   14799:                             my @contacts = ('adminemail','supportemail');
                   14800:                             foreach my $item (@contacts) {
                   14801:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   14802:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   14803:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14804:                                         push(@recipients,$addr);
                   14805:                                     }
                   14806:                                 }
                   14807:                             }
                   14808:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   14809:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   14810:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   14811:                                 my @ok_bccs;
                   14812:                                 foreach my $bcc (@bccs) {
                   14813:                                     $bcc =~ s/^\s+//g;
                   14814:                                     $bcc =~ s/\s+$//g;
                   14815:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14816:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14817:                                             push(@ok_bccs,$bcc);
                   14818:                                         }
                   14819:                                     }
                   14820:                                 }
                   14821:                                 if (@ok_bccs > 0) {
                   14822:                                     $allbcc = join(', ',@ok_bccs);
                   14823:                                 }
                   14824:                             }
                   14825:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   14826:                             last;
                   14827:                         }
                   14828:                     }
                   14829:                 }
                   14830:             }
                   14831:         }
1.619     raeburn  14832:     } elsif ($origmail ne '') {
1.1270    raeburn  14833:         $lastresort = $origmail;
                   14834:     }
1.1297    raeburn  14835:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  14836:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14837:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14838:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14839:             my %what = (
                   14840:                           perlvar => 1,
                   14841:                        );
                   14842:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14843:             if ($primary) {
                   14844:                 my $gotaddr;
                   14845:                 my ($result,$returnhash) =
                   14846:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14847:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14848:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14849:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14850:                         $gotaddr = 1;
                   14851:                     }
                   14852:                 }
                   14853:                 unless ($gotaddr) {
                   14854:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14855:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14856:                     unless ($uintdom eq $intdom) {
                   14857:                         my %domconfig =
                   14858:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14859:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14860:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14861:                                 my @contacts = ('adminemail','supportemail');
                   14862:                                 foreach my $item (@contacts) {
                   14863:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14864:                                         my $addr = $domconfig{'contacts'}{$item};
                   14865:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14866:                                             push(@recipients,$addr);
                   14867:                                         }
                   14868:                                     }
                   14869:                                 }
                   14870:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14871:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14872:                                 }
                   14873:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14874:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14875:                                     my @ok_bccs;
                   14876:                                     foreach my $bcc (@bccs) {
                   14877:                                         $bcc =~ s/^\s+//g;
                   14878:                                         $bcc =~ s/\s+$//g;
                   14879:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14880:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14881:                                                 push(@ok_bccs,$bcc);
                   14882:                                             }
                   14883:                                         }
                   14884:                                     }
                   14885:                                     if (@ok_bccs > 0) {
                   14886:                                         $allbcc = join(', ',@ok_bccs);
                   14887:                                     }
                   14888:                                 }
                   14889:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14890:                             }
                   14891:                         }
                   14892:                     }
                   14893:                 }
                   14894:             }
                   14895:         }
1.618     raeburn  14896:     }
1.688     raeburn  14897:     if (defined($defmail)) {
                   14898:         if ($defmail ne '') {
                   14899:             push(@recipients,$defmail);
                   14900:         }
1.618     raeburn  14901:     }
                   14902:     if ($otheremails) {
1.619     raeburn  14903:         my @others;
                   14904:         if ($otheremails =~ /,/) {
                   14905:             @others = split(/,/,$otheremails);
1.618     raeburn  14906:         } else {
1.619     raeburn  14907:             push(@others,$otheremails);
                   14908:         }
                   14909:         foreach my $addr (@others) {
                   14910:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14911:                 push(@recipients,$addr);
                   14912:             }
1.618     raeburn  14913:         }
                   14914:     }
1.1298    raeburn  14915:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  14916:         if ((!@recipients) && ($lastresort ne '')) {
                   14917:             push(@recipients,$lastresort);
                   14918:         }
                   14919:     } elsif ($lastresort ne '') {
                   14920:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14921:             push(@recipients,$lastresort);
                   14922:         }
                   14923:     }
1.1271    raeburn  14924:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  14925:     if (wantarray) {
                   14926:         return ($recipientlist,$allbcc,$addtext);
                   14927:     } else {
                   14928:         return $recipientlist;
                   14929:     }
1.618     raeburn  14930: }
                   14931: 
1.127     matthew  14932: ############################################################
                   14933: ############################################################
1.154     albertel 14934: 
1.655     raeburn  14935: =pod
                   14936: 
1.1224    musolffc 14937: =over 4
                   14938: 
1.1223    musolffc 14939: =item * &mime_email()
                   14940: 
                   14941: Sends an email with a possible attachment
                   14942: 
                   14943: Inputs:
                   14944: 
                   14945: =over 4
                   14946: 
                   14947: from -              Sender's email address
                   14948: 
                   14949: to -                Email address of recipient
                   14950: 
                   14951: subject -           Subject of email
                   14952: 
                   14953: body -              Body of email
                   14954: 
                   14955: cc_string -         Carbon copy email address
                   14956: 
                   14957: bcc -               Blind carbon copy email address
                   14958: 
                   14959: type -              File type of attachment
                   14960: 
                   14961: attachment_path -   Path of file to be attached
                   14962: 
                   14963: file_name -         Name of file to be attached
                   14964: 
                   14965: attachment_text -   The body of an attachment of type "TEXT"
                   14966: 
                   14967: =back
                   14968: 
                   14969: =back
                   14970: 
                   14971: =cut
                   14972: 
                   14973: ############################################################
                   14974: ############################################################
                   14975: 
                   14976: sub mime_email {
                   14977:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   14978:         $file_name, $attachment_text) = @_;
                   14979:     my $msg = MIME::Lite->new(
                   14980:              From    => $from,
                   14981:              To      => $to,
                   14982:              Subject => $subject,
                   14983:              Type    =>'TEXT',
                   14984:              Data    => $body,
                   14985:              );
                   14986:     if ($cc_string ne '') {
                   14987:         $msg->add("Cc" => $cc_string);
                   14988:     }
                   14989:     if ($bcc ne '') {
                   14990:         $msg->add("Bcc" => $bcc);
                   14991:     }
                   14992:     $msg->attr("content-type"         => "text/plain");
                   14993:     $msg->attr("content-type.charset" => "UTF-8");
                   14994:     # Attach file if given
                   14995:     if ($attachment_path) {
                   14996:         unless ($file_name) {
                   14997:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   14998:         }
                   14999:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15000:         $msg->attach(Type     => $type,
                   15001:                      Path     => $attachment_path,
                   15002:                      Filename => $file_name
                   15003:                      );
                   15004:     # Otherwise attach text if given
                   15005:     } elsif ($attachment_text) {
                   15006:         $msg->attach(Type => 'TEXT',
                   15007:                      Data => $attachment_text);
                   15008:     }
                   15009:     # Send it
                   15010:     $msg->send('sendmail');
                   15011: }
                   15012: 
                   15013: ############################################################
                   15014: ############################################################
                   15015: 
                   15016: =pod
                   15017: 
1.655     raeburn  15018: =head1 Course Catalog Routines
                   15019: 
                   15020: =over 4
                   15021: 
                   15022: =item * &gather_categories()
                   15023: 
                   15024: Converts category definitions - keys of categories hash stored in  
                   15025: coursecategories in configuration.db on the primary library server in a 
                   15026: domain - to an array.  Also generates javascript and idx hash used to 
                   15027: generate Domain Coordinator interface for editing Course Categories.
                   15028: 
                   15029: Inputs:
1.663     raeburn  15030: 
1.655     raeburn  15031: categories (reference to hash of category definitions).
1.663     raeburn  15032: 
1.655     raeburn  15033: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15034:       categories and subcategories).
1.663     raeburn  15035: 
1.655     raeburn  15036: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15037:       editing Course Categories).
1.663     raeburn  15038: 
1.655     raeburn  15039: jsarray (reference to array of categories used to create Javascript arrays for
                   15040:          Domain Coordinator interface for editing Course Categories).
                   15041: 
                   15042: Returns: nothing
                   15043: 
                   15044: Side effects: populates cats, idx and jsarray. 
                   15045: 
                   15046: =cut
                   15047: 
                   15048: sub gather_categories {
                   15049:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15050:     my %counters;
                   15051:     my $num = 0;
                   15052:     foreach my $item (keys(%{$categories})) {
                   15053:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15054:         if ($container eq '' && $depth == 0) {
                   15055:             $cats->[$depth][$categories->{$item}] = $cat;
                   15056:         } else {
                   15057:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15058:         }
                   15059:         my ($escitem,$tail) = split(/:/,$item,2);
                   15060:         if ($counters{$tail} eq '') {
                   15061:             $counters{$tail} = $num;
                   15062:             $num ++;
                   15063:         }
                   15064:         if (ref($idx) eq 'HASH') {
                   15065:             $idx->{$item} = $counters{$tail};
                   15066:         }
                   15067:         if (ref($jsarray) eq 'ARRAY') {
                   15068:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15069:         }
                   15070:     }
                   15071:     return;
                   15072: }
                   15073: 
                   15074: =pod
                   15075: 
                   15076: =item * &extract_categories()
                   15077: 
                   15078: Used to generate breadcrumb trails for course categories.
                   15079: 
                   15080: Inputs:
1.663     raeburn  15081: 
1.655     raeburn  15082: categories (reference to hash of category definitions).
1.663     raeburn  15083: 
1.655     raeburn  15084: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15085:       categories and subcategories).
1.663     raeburn  15086: 
1.655     raeburn  15087: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15088: 
1.655     raeburn  15089: allitems (reference to hash - key is category key 
                   15090:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15091: 
1.655     raeburn  15092: idx (reference to hash of counters used in Domain Coordinator interface for
                   15093:       editing Course Categories).
1.663     raeburn  15094: 
1.655     raeburn  15095: jsarray (reference to array of categories used to create Javascript arrays for
                   15096:          Domain Coordinator interface for editing Course Categories).
                   15097: 
1.665     raeburn  15098: subcats (reference to hash of arrays containing all subcategories within each 
                   15099:          category, -recursive)
                   15100: 
1.655     raeburn  15101: Returns: nothing
                   15102: 
                   15103: Side effects: populates trails and allitems hash references.
                   15104: 
                   15105: =cut
                   15106: 
                   15107: sub extract_categories {
1.665     raeburn  15108:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  15109:     if (ref($categories) eq 'HASH') {
                   15110:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15111:         if (ref($cats->[0]) eq 'ARRAY') {
                   15112:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15113:                 my $name = $cats->[0][$i];
                   15114:                 my $item = &escape($name).'::0';
                   15115:                 my $trailstr;
                   15116:                 if ($name eq 'instcode') {
                   15117:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15118:                 } elsif ($name eq 'communities') {
                   15119:                     $trailstr = &mt('Communities');
1.1239    raeburn  15120:                 } elsif ($name eq 'placement') {
                   15121:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15122:                 } else {
                   15123:                     $trailstr = $name;
                   15124:                 }
                   15125:                 if ($allitems->{$item} eq '') {
                   15126:                     push(@{$trails},$trailstr);
                   15127:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15128:                 }
                   15129:                 my @parents = ($name);
                   15130:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15131:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15132:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15133:                         if (ref($subcats) eq 'HASH') {
                   15134:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15135:                         }
                   15136:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   15137:                     }
                   15138:                 } else {
                   15139:                     if (ref($subcats) eq 'HASH') {
                   15140:                         $subcats->{$item} = [];
1.655     raeburn  15141:                     }
                   15142:                 }
                   15143:             }
                   15144:         }
                   15145:     }
                   15146:     return;
                   15147: }
                   15148: 
                   15149: =pod
                   15150: 
1.1162    raeburn  15151: =item * &recurse_categories()
1.655     raeburn  15152: 
                   15153: Recursively used to generate breadcrumb trails for course categories.
                   15154: 
                   15155: Inputs:
1.663     raeburn  15156: 
1.655     raeburn  15157: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15158:       categories and subcategories).
1.663     raeburn  15159: 
1.655     raeburn  15160: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15161: 
                   15162: category (current course category, for which breadcrumb trail is being generated).
                   15163: 
                   15164: trails (reference to array of breadcrumb trails for each category).
                   15165: 
1.655     raeburn  15166: allitems (reference to hash - key is category key
                   15167:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15168: 
1.655     raeburn  15169: parents (array containing containers directories for current category, 
                   15170:          back to top level). 
                   15171: 
                   15172: Returns: nothing
                   15173: 
                   15174: Side effects: populates trails and allitems hash references
                   15175: 
                   15176: =cut
                   15177: 
                   15178: sub recurse_categories {
1.665     raeburn  15179:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  15180:     my $shallower = $depth - 1;
                   15181:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15182:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15183:             my $name = $cats->[$depth]{$category}[$k];
                   15184:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   15185:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   15186:             if ($allitems->{$item} eq '') {
                   15187:                 push(@{$trails},$trailstr);
                   15188:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15189:             }
                   15190:             my $deeper = $depth+1;
                   15191:             push(@{$parents},$category);
1.665     raeburn  15192:             if (ref($subcats) eq 'HASH') {
                   15193:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15194:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15195:                     my $higher;
                   15196:                     if ($j > 0) {
                   15197:                         $higher = &escape($parents->[$j]).':'.
                   15198:                                   &escape($parents->[$j-1]).':'.$j;
                   15199:                     } else {
                   15200:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15201:                     }
                   15202:                     push(@{$subcats->{$higher}},$subcat);
                   15203:                 }
                   15204:             }
                   15205:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   15206:                                 $subcats);
1.655     raeburn  15207:             pop(@{$parents});
                   15208:         }
                   15209:     } else {
                   15210:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   15211:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   15212:         if ($allitems->{$item} eq '') {
                   15213:             push(@{$trails},$trailstr);
                   15214:             $allitems->{$item} = scalar(@{$trails})-1;
                   15215:         }
                   15216:     }
                   15217:     return;
                   15218: }
                   15219: 
1.663     raeburn  15220: =pod
                   15221: 
1.1162    raeburn  15222: =item * &assign_categories_table()
1.663     raeburn  15223: 
                   15224: Create a datatable for display of hierarchical categories in a domain,
                   15225: with checkboxes to allow a course to be categorized. 
                   15226: 
                   15227: Inputs:
                   15228: 
                   15229: cathash - reference to hash of categories defined for the domain (from
                   15230:           configuration.db)
                   15231: 
                   15232: currcat - scalar with an & separated list of categories assigned to a course. 
                   15233: 
1.919     raeburn  15234: type    - scalar contains course type (Course or Community).
                   15235: 
1.1260    raeburn  15236: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15237:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15238: 
1.663     raeburn  15239: Returns: $output (markup to be displayed) 
                   15240: 
                   15241: =cut
                   15242: 
                   15243: sub assign_categories_table {
1.1259    raeburn  15244:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15245:     my $output;
                   15246:     if (ref($cathash) eq 'HASH') {
                   15247:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   15248:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   15249:         $maxdepth = scalar(@cats);
                   15250:         if (@cats > 0) {
                   15251:             my $itemcount = 0;
                   15252:             if (ref($cats[0]) eq 'ARRAY') {
                   15253:                 my @currcategories;
                   15254:                 if ($currcat ne '') {
                   15255:                     @currcategories = split('&',$currcat);
                   15256:                 }
1.919     raeburn  15257:                 my $table;
1.663     raeburn  15258:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15259:                     my $parent = $cats[0][$i];
1.919     raeburn  15260:                     next if ($parent eq 'instcode');
                   15261:                     if ($type eq 'Community') {
                   15262:                         next unless ($parent eq 'communities');
1.1239    raeburn  15263:                     } elsif ($type eq 'Placement') {
                   15264:                         next unless ($parent eq 'placement');
1.919     raeburn  15265:                     } else {
1.1239    raeburn  15266:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  15267:                     }
1.663     raeburn  15268:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15269:                     my $item = &escape($parent).'::0';
                   15270:                     my $checked = '';
                   15271:                     if (@currcategories > 0) {
                   15272:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15273:                             $checked = ' checked="checked"';
1.663     raeburn  15274:                         }
                   15275:                     }
1.919     raeburn  15276:                     my $parent_title = $parent;
                   15277:                     if ($parent eq 'communities') {
                   15278:                         $parent_title = &mt('Communities');
1.1239    raeburn  15279:                     } elsif ($parent eq 'placement') {
                   15280:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  15281:                     }
                   15282:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15283:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15284:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15285:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15286:                     my $depth = 1;
                   15287:                     push(@path,$parent);
1.1259    raeburn  15288:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15289:                     pop(@path);
1.919     raeburn  15290:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15291:                     $itemcount ++;
                   15292:                 }
1.919     raeburn  15293:                 if ($itemcount) {
                   15294:                     $output = &Apache::loncommon::start_data_table().
                   15295:                               $table.
                   15296:                               &Apache::loncommon::end_data_table();
                   15297:                 }
1.663     raeburn  15298:             }
                   15299:         }
                   15300:     }
                   15301:     return $output;
                   15302: }
                   15303: 
                   15304: =pod
                   15305: 
1.1162    raeburn  15306: =item * &assign_category_rows()
1.663     raeburn  15307: 
                   15308: Create a datatable row for display of nested categories in a domain,
                   15309: with checkboxes to allow a course to be categorized,called recursively.
                   15310: 
                   15311: Inputs:
                   15312: 
                   15313: itemcount - track row number for alternating colors
                   15314: 
                   15315: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15316:       categories and subcategories.
                   15317: 
                   15318: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15319: 
                   15320: parent - parent of current category item
                   15321: 
                   15322: path - Array containing all categories back up through the hierarchy from the
                   15323:        current category to the top level.
                   15324: 
                   15325: currcategories - reference to array of current categories assigned to the course
                   15326: 
1.1260    raeburn  15327: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15328:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15329: 
1.663     raeburn  15330: Returns: $output (markup to be displayed).
                   15331: 
                   15332: =cut
                   15333: 
                   15334: sub assign_category_rows {
1.1259    raeburn  15335:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15336:     my ($text,$name,$item,$chgstr);
                   15337:     if (ref($cats) eq 'ARRAY') {
                   15338:         my $maxdepth = scalar(@{$cats});
                   15339:         if (ref($cats->[$depth]) eq 'HASH') {
                   15340:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15341:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15342:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  15343:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15344:                 for (my $j=0; $j<$numchildren; $j++) {
                   15345:                     $name = $cats->[$depth]{$parent}[$j];
                   15346:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15347:                     my $deeper = $depth+1;
                   15348:                     my $checked = '';
                   15349:                     if (ref($currcategories) eq 'ARRAY') {
                   15350:                         if (@{$currcategories} > 0) {
                   15351:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15352:                                 $checked = ' checked="checked"';
1.663     raeburn  15353:                             }
                   15354:                         }
                   15355:                     }
1.664     raeburn  15356:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15357:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15358:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15359:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15360:                              '</td><td>';
1.663     raeburn  15361:                     if (ref($path) eq 'ARRAY') {
                   15362:                         push(@{$path},$name);
1.1259    raeburn  15363:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15364:                         pop(@{$path});
                   15365:                     }
                   15366:                     $text .= '</td></tr>';
                   15367:                 }
                   15368:                 $text .= '</table></td>';
                   15369:             }
                   15370:         }
                   15371:     }
                   15372:     return $text;
                   15373: }
                   15374: 
1.1181    raeburn  15375: =pod
                   15376: 
                   15377: =back
                   15378: 
                   15379: =cut
                   15380: 
1.655     raeburn  15381: ############################################################
                   15382: ############################################################
                   15383: 
                   15384: 
1.443     albertel 15385: sub commit_customrole {
1.664     raeburn  15386:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15387:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15388:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15389:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15390:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15391:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15392:                  '</b><br />';
                   15393:     return $output;
                   15394: }
                   15395: 
                   15396: sub commit_standardrole {
1.1116    raeburn  15397:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15398:     my ($output,$logmsg,$linefeed);
                   15399:     if ($context eq 'auto') {
                   15400:         $linefeed = "\n";
                   15401:     } else {
                   15402:         $linefeed = "<br />\n";
                   15403:     }  
1.443     albertel 15404:     if ($three eq 'st') {
1.541     raeburn  15405:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15406:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15407:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15408:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15409:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15410:         } else {
1.541     raeburn  15411:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15412:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15413:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15414:             if ($context eq 'auto') {
                   15415:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15416:             } else {
                   15417:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15418:                &mt('Add to classlist').': <b>ok</b>';
                   15419:             }
                   15420:             $output .= $linefeed;
1.443     albertel 15421:         }
                   15422:     } else {
                   15423:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15424:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15425:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15426:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15427:         if ($context eq 'auto') {
                   15428:             $output .= $result.$linefeed;
                   15429:         } else {
                   15430:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15431:         }
1.443     albertel 15432:     }
                   15433:     return $output;
                   15434: }
                   15435: 
                   15436: sub commit_studentrole {
1.1116    raeburn  15437:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15438:         $credits) = @_;
1.626     raeburn  15439:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15440:     if ($context eq 'auto') {
                   15441:         $linefeed = "\n";
                   15442:     } else {
                   15443:         $linefeed = '<br />'."\n";
                   15444:     }
1.443     albertel 15445:     if (defined($one) && defined($two)) {
                   15446:         my $cid=$one.'_'.$two;
                   15447:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15448:         my $secchange = 0;
                   15449:         my $expire_role_result;
                   15450:         my $modify_section_result;
1.628     raeburn  15451:         if ($oldsec ne '-1') { 
                   15452:             if ($oldsec ne $sec) {
1.443     albertel 15453:                 $secchange = 1;
1.628     raeburn  15454:                 my $now = time;
1.443     albertel 15455:                 my $uurl='/'.$cid;
                   15456:                 $uurl=~s/\_/\//g;
                   15457:                 if ($oldsec) {
                   15458:                     $uurl.='/'.$oldsec;
                   15459:                 }
1.626     raeburn  15460:                 $oldsecurl = $uurl;
1.628     raeburn  15461:                 $expire_role_result = 
1.652     raeburn  15462:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15463:                 if ($env{'request.course.sec'} ne '') { 
                   15464:                     if ($expire_role_result eq 'refused') {
                   15465:                         my @roles = ('st');
                   15466:                         my @statuses = ('previous');
                   15467:                         my @roledoms = ($one);
                   15468:                         my $withsec = 1;
                   15469:                         my %roleshash = 
                   15470:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15471:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15472:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15473:                             my ($oldstart,$oldend) = 
                   15474:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15475:                             if ($oldend > 0 && $oldend <= $now) {
                   15476:                                 $expire_role_result = 'ok';
                   15477:                             }
                   15478:                         }
                   15479:                     }
                   15480:                 }
1.443     albertel 15481:                 $result = $expire_role_result;
                   15482:             }
                   15483:         }
                   15484:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  15485:             $modify_section_result = 
                   15486:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15487:                                                            undef,undef,undef,$sec,
                   15488:                                                            $end,$start,'','',$cid,
                   15489:                                                            '',$context,$credits);
1.443     albertel 15490:             if ($modify_section_result =~ /^ok/) {
                   15491:                 if ($secchange == 1) {
1.628     raeburn  15492:                     if ($sec eq '') {
                   15493:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15494:                     } else {
                   15495:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15496:                     }
1.443     albertel 15497:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15498:                     if ($sec eq '') {
                   15499:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15500:                     } else {
                   15501:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15502:                     }
1.443     albertel 15503:                 } else {
1.628     raeburn  15504:                     if ($sec eq '') {
                   15505:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15506:                     } else {
                   15507:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15508:                     }
1.443     albertel 15509:                 }
                   15510:             } else {
1.1115    raeburn  15511:                 if ($secchange) { 
1.628     raeburn  15512:                     $$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;
                   15513:                 } else {
                   15514:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15515:                 }
1.443     albertel 15516:             }
                   15517:             $result = $modify_section_result;
                   15518:         } elsif ($secchange == 1) {
1.628     raeburn  15519:             if ($oldsec eq '') {
1.1103    raeburn  15520:                 $$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  15521:             } else {
                   15522:                 $$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;
                   15523:             }
1.626     raeburn  15524:             if ($expire_role_result eq 'refused') {
                   15525:                 my $newsecurl = '/'.$cid;
                   15526:                 $newsecurl =~ s/\_/\//g;
                   15527:                 if ($sec ne '') {
                   15528:                     $newsecurl.='/'.$sec;
                   15529:                 }
                   15530:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15531:                     if ($sec eq '') {
                   15532:                         $$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;
                   15533:                     } else {
                   15534:                         $$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;
                   15535:                     }
                   15536:                 }
                   15537:             }
1.443     albertel 15538:         }
                   15539:     } else {
1.626     raeburn  15540:         $$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 15541:         $result = "error: incomplete course id\n";
                   15542:     }
                   15543:     return $result;
                   15544: }
                   15545: 
1.1108    raeburn  15546: sub show_role_extent {
                   15547:     my ($scope,$context,$role) = @_;
                   15548:     $scope =~ s{^/}{};
                   15549:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15550:     push(@courseroles,'co');
                   15551:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15552:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15553:         $scope =~ s{/}{_};
                   15554:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15555:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15556:         my ($audom,$auname) = split(/\//,$scope);
                   15557:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15558:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15559:     } else {
                   15560:         $scope =~ s{/$}{};
                   15561:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15562:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15563:     }
                   15564: }
                   15565: 
1.443     albertel 15566: ############################################################
                   15567: ############################################################
                   15568: 
1.566     albertel 15569: sub check_clone {
1.578     raeburn  15570:     my ($args,$linefeed) = @_;
1.566     albertel 15571:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15572:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15573:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15574:     my $clonemsg;
                   15575:     my $can_clone = 0;
1.944     raeburn  15576:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15577:     if ($lctype ne 'community') {
                   15578:         $lctype = 'course';
                   15579:     }
1.566     albertel 15580:     if ($clonehome eq 'no_host') {
1.944     raeburn  15581:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15582:             $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'});
                   15583:         } else {
                   15584:             $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'});
                   15585:         }     
1.566     albertel 15586:     } else {
                   15587: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15588:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15589:             if ($clonedesc{'type'} ne 'Community') {
1.1262    raeburn  15590:                 $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  15591:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15592:             }
                   15593:         }
1.1262    raeburn  15594: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15595:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15596: 	    $can_clone = 1;
                   15597: 	} else {
1.1221    raeburn  15598: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15599: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  15600:             if ($clonehash{'cloners'} eq '') {
                   15601:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15602:                 if ($domdefs{'canclone'}) {
                   15603:                     unless ($domdefs{'canclone'} eq 'none') {
                   15604:                         if ($domdefs{'canclone'} eq 'domain') {
                   15605:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15606:                                 $can_clone = 1;
                   15607:                             }
                   15608:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15609:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15610:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15611:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15612:                                 $can_clone = 1;
                   15613:                             }
                   15614:                         }
                   15615:                     }
                   15616:                 }
1.578     raeburn  15617:             } else {
1.1221    raeburn  15618: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15619:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15620:                     $can_clone = 1;
1.1221    raeburn  15621:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15622:                     $can_clone = 1;
1.1225    raeburn  15623:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15624:                     $can_clone = 1;
1.1221    raeburn  15625:                 }
                   15626:                 unless ($can_clone) {
1.1225    raeburn  15627:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15628:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  15629:                         my (%gotdomdefaults,%gotcodedefaults);
                   15630:                         foreach my $cloner (@cloners) {
                   15631:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15632:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15633:                                 my (%codedefaults,@code_order);
                   15634:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15635:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15636:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15637:                                     }
                   15638:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15639:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15640:                                     }
                   15641:                                 } else {
                   15642:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15643:                                                                             \%codedefaults,
                   15644:                                                                             \@code_order);
                   15645:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15646:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15647:                                 }
                   15648:                                 if (@code_order > 0) {
                   15649:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15650:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15651:                                                                                 $args->{'crscode'})) {
                   15652:                                         $can_clone = 1;
                   15653:                                         last;
                   15654:                                     }
                   15655:                                 }
                   15656:                             }
                   15657:                         }
                   15658:                     }
1.1225    raeburn  15659:                 }
                   15660:             }
                   15661:             unless ($can_clone) {
                   15662:                 my $ccrole = 'cc';
                   15663:                 if ($args->{'crstype'} eq 'Community') {
                   15664:                     $ccrole = 'co';
                   15665:                 }
                   15666: 	        my %roleshash =
                   15667: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15668: 					          $args->{'ccdomain'},
                   15669:                                                   'userroles',['active'],[$ccrole],
                   15670: 					          [$args->{'clonedomain'}]);
                   15671: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15672:                     $can_clone = 1;
                   15673:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15674:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15675:                     $can_clone = 1;
1.1221    raeburn  15676:                 }
                   15677:             }
                   15678:             unless ($can_clone) {
                   15679:                 if ($args->{'crstype'} eq 'Community') {
                   15680:                     $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  15681:                 } else {
1.1221    raeburn  15682:                     $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'});
                   15683:                 }
1.566     albertel 15684: 	    }
1.578     raeburn  15685:         }
1.566     albertel 15686:     }
                   15687:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15688: }
                   15689: 
1.444     albertel 15690: sub construct_course {
1.1262    raeburn  15691:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15692:         $cnum,$category,$coderef) = @_;
1.444     albertel 15693:     my $outcome;
1.541     raeburn  15694:     my $linefeed =  '<br />'."\n";
                   15695:     if ($context eq 'auto') {
                   15696:         $linefeed = "\n";
                   15697:     }
1.566     albertel 15698: 
                   15699: #
                   15700: # Are we cloning?
                   15701: #
                   15702:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15703:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15704: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15705: 	if ($context ne 'auto') {
1.578     raeburn  15706:             if ($clonemsg ne '') {
                   15707: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15708:             }
1.566     albertel 15709: 	}
                   15710: 	$outcome .= $clonemsg.$linefeed;
                   15711: 
                   15712:         if (!$can_clone) {
                   15713: 	    return (0,$outcome);
                   15714: 	}
                   15715:     }
                   15716: 
1.444     albertel 15717: #
                   15718: # Open course
                   15719: #
1.1239    raeburn  15720:     my $showncrstype;
                   15721:     if ($args->{'crstype'} eq 'Placement') {
                   15722:         $showncrstype = 'placement test'; 
                   15723:     } else {  
                   15724:         $showncrstype = lc($args->{'crstype'});
                   15725:     }
1.444     albertel 15726:     my %cenv=();
                   15727:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15728:                                              $args->{'cdescr'},
                   15729:                                              $args->{'curl'},
                   15730:                                              $args->{'course_home'},
                   15731:                                              $args->{'nonstandard'},
                   15732:                                              $args->{'crscode'},
                   15733:                                              $args->{'ccuname'}.':'.
                   15734:                                              $args->{'ccdomain'},
1.882     raeburn  15735:                                              $args->{'crstype'},
1.885     raeburn  15736:                                              $cnum,$context,$category);
1.444     albertel 15737: 
                   15738:     # Note: The testing routines depend on this being output; see 
                   15739:     # Utils::Course. This needs to at least be output as a comment
                   15740:     # if anyone ever decides to not show this, and Utils::Course::new
                   15741:     # will need to be suitably modified.
1.1239    raeburn  15742:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
1.943     raeburn  15743:     if ($$courseid =~ /^error:/) {
                   15744:         return (0,$outcome);
                   15745:     }
                   15746: 
1.444     albertel 15747: #
                   15748: # Check if created correctly
                   15749: #
1.479     albertel 15750:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15751:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15752:     if ($crsuhome eq 'no_host') {
                   15753:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15754:         return (0,$outcome);
                   15755:     }
1.541     raeburn  15756:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15757: 
1.444     albertel 15758: #
1.566     albertel 15759: # Do the cloning
                   15760: #   
                   15761:     if ($can_clone && $cloneid) {
1.1239    raeburn  15762: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
1.566     albertel 15763: 	if ($context ne 'auto') {
                   15764: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15765: 	}
                   15766: 	$outcome .= $clonemsg.$linefeed;
                   15767: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15768: # Copy all files
1.637     www      15769: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15770: # Restore URL
1.566     albertel 15771: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15772: # Restore title
1.566     albertel 15773: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15774: # Restore creation date, creator and creation context.
                   15775:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15776:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15777:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15778: # Mark as cloned
1.566     albertel 15779: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15780: # Need to clone grading mode
                   15781:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15782:         $cenv{'grading'}=$newenv{'grading'};
                   15783: # Do not clone these environment entries
                   15784:         &Apache::lonnet::del('environment',
                   15785:                   ['default_enrollment_start_date',
                   15786:                    'default_enrollment_end_date',
                   15787:                    'question.email',
                   15788:                    'policy.email',
                   15789:                    'comment.email',
                   15790:                    'pch.users.denied',
1.725     raeburn  15791:                    'plc.users.denied',
                   15792:                    'hidefromcat',
1.1121    raeburn  15793:                    'checkforpriv',
1.1166    raeburn  15794:                    'categories',
                   15795:                    'internal.uniquecode'],
1.638     www      15796:                    $$crsudom,$$crsunum);
1.1170    raeburn  15797:         if ($args->{'textbook'}) {
                   15798:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15799:         }
1.444     albertel 15800:     }
1.566     albertel 15801: 
1.444     albertel 15802: #
                   15803: # Set environment (will override cloned, if existing)
                   15804: #
                   15805:     my @sections = ();
                   15806:     my @xlists = ();
                   15807:     if ($args->{'crstype'}) {
                   15808:         $cenv{'type'}=$args->{'crstype'};
                   15809:     }
                   15810:     if ($args->{'crsid'}) {
                   15811:         $cenv{'courseid'}=$args->{'crsid'};
                   15812:     }
                   15813:     if ($args->{'crscode'}) {
                   15814:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15815:     }
                   15816:     if ($args->{'crsquota'} ne '') {
                   15817:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15818:     } else {
                   15819:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15820:     }
                   15821:     if ($args->{'ccuname'}) {
                   15822:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15823:                                         ':'.$args->{'ccdomain'};
                   15824:     } else {
                   15825:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15826:     }
1.1116    raeburn  15827:     if ($args->{'defaultcredits'}) {
                   15828:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15829:     }
1.444     albertel 15830:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15831:     if ($args->{'crssections'}) {
                   15832:         $cenv{'internal.sectionnums'} = '';
                   15833:         if ($args->{'crssections'} =~ m/,/) {
                   15834:             @sections = split/,/,$args->{'crssections'};
                   15835:         } else {
                   15836:             $sections[0] = $args->{'crssections'};
                   15837:         }
                   15838:         if (@sections > 0) {
                   15839:             foreach my $item (@sections) {
                   15840:                 my ($sec,$gp) = split/:/,$item;
                   15841:                 my $class = $args->{'crscode'}.$sec;
                   15842:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15843:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15844:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15845:                     push(@badclasses,$class);
1.444     albertel 15846:                 }
                   15847:             }
                   15848:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15849:         }
                   15850:     }
                   15851: # do not hide course coordinator from staff listing, 
                   15852: # even if privileged
                   15853:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  15854: # add course coordinator's domain to domains to check for privileged users
                   15855: # if different to course domain
                   15856:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15857:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15858:     }
1.444     albertel 15859: # add crosslistings
                   15860:     if ($args->{'crsxlist'}) {
                   15861:         $cenv{'internal.crosslistings'}='';
                   15862:         if ($args->{'crsxlist'} =~ m/,/) {
                   15863:             @xlists = split/,/,$args->{'crsxlist'};
                   15864:         } else {
                   15865:             $xlists[0] = $args->{'crsxlist'};
                   15866:         }
                   15867:         if (@xlists > 0) {
                   15868:             foreach my $item (@xlists) {
                   15869:                 my ($xl,$gp) = split/:/,$item;
                   15870:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15871:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15872:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15873:                     push(@badclasses,$xl);
1.444     albertel 15874:                 }
                   15875:             }
                   15876:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15877:         }
                   15878:     }
                   15879:     if ($args->{'autoadds'}) {
                   15880:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15881:     }
                   15882:     if ($args->{'autodrops'}) {
                   15883:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15884:     }
                   15885: # check for notification of enrollment changes
                   15886:     my @notified = ();
                   15887:     if ($args->{'notify_owner'}) {
                   15888:         if ($args->{'ccuname'} ne '') {
                   15889:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15890:         }
                   15891:     }
                   15892:     if ($args->{'notify_dc'}) {
                   15893:         if ($uname ne '') { 
1.630     raeburn  15894:             push(@notified,$uname.':'.$udom);
1.444     albertel 15895:         }
                   15896:     }
                   15897:     if (@notified > 0) {
                   15898:         my $notifylist;
                   15899:         if (@notified > 1) {
                   15900:             $notifylist = join(',',@notified);
                   15901:         } else {
                   15902:             $notifylist = $notified[0];
                   15903:         }
                   15904:         $cenv{'internal.notifylist'} = $notifylist;
                   15905:     }
                   15906:     if (@badclasses > 0) {
                   15907:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  15908:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15909:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15910:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15911:         );
1.1264    raeburn  15912:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15913:                            &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  15914:         if ($context eq 'auto') {
                   15915:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  15916:         } else {
1.566     albertel 15917:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  15918:         }
                   15919:         foreach my $item (@badclasses) {
1.541     raeburn  15920:             if ($context eq 'auto') {
1.1261    raeburn  15921:                 $outcome .= " - $item\n";
1.541     raeburn  15922:             } else {
1.1261    raeburn  15923:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15924:             }
1.1261    raeburn  15925:         }
                   15926:         if ($context eq 'auto') {
                   15927:             $outcome .= $linefeed;
                   15928:         } else {
                   15929:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  15930:         } 
1.444     albertel 15931:     }
                   15932:     if ($args->{'no_end_date'}) {
                   15933:         $args->{'endaccess'} = 0;
                   15934:     }
                   15935:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15936:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15937:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15938:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15939:     if ($args->{'showphotos'}) {
                   15940:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15941:     }
                   15942:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15943:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15944:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15945:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15946:             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'); 
                   15947:             if ($context eq 'auto') {
                   15948:                 $outcome .= $krb_msg;
                   15949:             } else {
1.566     albertel 15950:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15951:             }
                   15952:             $outcome .= $linefeed;
1.444     albertel 15953:         }
                   15954:     }
                   15955:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15956:        if ($args->{'setpolicy'}) {
                   15957:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15958:        }
                   15959:        if ($args->{'setcontent'}) {
                   15960:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15961:        }
1.1251    raeburn  15962:        if ($args->{'setcomment'}) {
                   15963:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15964:        }
1.444     albertel 15965:     }
                   15966:     if ($args->{'reshome'}) {
                   15967: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15968: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15969:     }
                   15970: #
                   15971: # course has keyed access
                   15972: #
                   15973:     if ($args->{'setkeys'}) {
                   15974:        $cenv{'keyaccess'}='yes';
                   15975:     }
                   15976: # if specified, key authority is not course, but user
                   15977: # only active if keyaccess is yes
                   15978:     if ($args->{'keyauth'}) {
1.487     albertel 15979: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15980: 	$user = &LONCAPA::clean_username($user);
                   15981: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15982: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15983: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15984: 	}
                   15985:     }
                   15986: 
1.1166    raeburn  15987: #
1.1167    raeburn  15988: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  15989: #
                   15990:     if ($args->{'uniquecode'}) {
                   15991:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15992:         if ($code) {
                   15993:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  15994:             my %crsinfo =
                   15995:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15996:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15997:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15998:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15999:             } 
1.1166    raeburn  16000:             if (ref($coderef)) {
                   16001:                 $$coderef = $code;
                   16002:             }
                   16003:         }
                   16004:     }
                   16005: 
1.444     albertel 16006:     if ($args->{'disresdis'}) {
                   16007:         $cenv{'pch.roles.denied'}='st';
                   16008:     }
                   16009:     if ($args->{'disablechat'}) {
                   16010:         $cenv{'plc.roles.denied'}='st';
                   16011:     }
                   16012: 
                   16013:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16014:     # course
                   16015:     $cenv{'course.helper.not.run'} = 1;
                   16016:     #
                   16017:     # Use new Randomseed
                   16018:     #
                   16019:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16020:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16021:     #
                   16022:     # The encryption code and receipt prefix for this course
                   16023:     #
                   16024:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16025:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16026:     #
                   16027:     # By default, use standard grading
                   16028:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16029: 
1.541     raeburn  16030:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16031:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16032: #
                   16033: # Open all assignments
                   16034: #
                   16035:     if ($args->{'openall'}) {
                   16036:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   16037:        my %storecontent = ($storeunder         => time,
                   16038:                            $storeunder.'.type' => 'date_start');
                   16039:        
                   16040:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  16041:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16042:    }
                   16043: #
                   16044: # Set first page
                   16045: #
                   16046:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16047: 	    || ($cloneid)) {
1.445     albertel 16048: 	use LONCAPA::map;
1.444     albertel 16049: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16050: 
                   16051: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16052:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16053: 
1.444     albertel 16054:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16055:         my $title; my $url;
                   16056:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16057: 	    $title=&mt('Syllabus');
1.444     albertel 16058:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16059:         } else {
1.963     raeburn  16060:             $title=&mt('Table of Contents');
1.444     albertel 16061:             $url='/adm/navmaps';
                   16062:         }
1.445     albertel 16063: 
                   16064:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16065: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16066: 
                   16067: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16068:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16069:     }
1.566     albertel 16070: 
1.1237    raeburn  16071: # 
                   16072: # Set params for Placement Tests
                   16073: #
1.1239    raeburn  16074:     if ($args->{'crstype'} eq 'Placement') {
                   16075:        my %storecontent; 
                   16076:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   16077:        my %defaults = (
                   16078:                         buttonshide   => { value => 'yes',
                   16079:                                            type => 'string_yesno',},
                   16080:                         type          => { value => 'randomizetry',
                   16081:                                            type  => 'string_questiontype',},
                   16082:                         maxtries      => { value => 1,
                   16083:                                            type => 'int_pos',},
                   16084:                         problemstatus => { value => 'no',
                   16085:                                            type  => 'string_problemstatus',},
                   16086:                       );
                   16087:        foreach my $key (keys(%defaults)) {
                   16088:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   16089:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   16090:        }
1.1237    raeburn  16091:        &Apache::lonnet::cput
                   16092:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   16093:     }
                   16094: 
1.566     albertel 16095:     return (1,$outcome);
1.444     albertel 16096: }
                   16097: 
1.1166    raeburn  16098: sub make_unique_code {
                   16099:     my ($cdom,$cnum) = @_;
                   16100:     # get lock on uniquecodes db
                   16101:     my $lockhash = {
                   16102:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16103:                                                   ':'.$env{'user.domain'},
                   16104:                    };
                   16105:     my $tries = 0;
                   16106:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16107:     my ($code,$error);
                   16108:   
                   16109:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16110:         $tries ++;
                   16111:         sleep 1;
                   16112:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16113:     }
                   16114:     if ($gotlock eq 'ok') {
                   16115:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16116:         my $gotcode;
                   16117:         my $attempts = 0;
                   16118:         while ((!$gotcode) && ($attempts < 100)) {
                   16119:             $code = &generate_code();
                   16120:             if (!exists($currcodes{$code})) {
                   16121:                 $gotcode = 1;
                   16122:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16123:                     $error = 'nostore';
                   16124:                 }
                   16125:             }
                   16126:             $attempts ++;
                   16127:         }
                   16128:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16129:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16130:     } else {
                   16131:         $error = 'nolock';
                   16132:     }
                   16133:     return ($code,$error);
                   16134: }
                   16135: 
                   16136: sub generate_code {
                   16137:     my $code;
                   16138:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16139:     for (my $i=0; $i<6; $i++) {
                   16140:         my $lettnum = int (rand 2);
                   16141:         my $item = '';
                   16142:         if ($lettnum) {
                   16143:             $item = $letts[int( rand(18) )];
                   16144:         } else {
                   16145:             $item = 1+int( rand(8) );
                   16146:         }
                   16147:         $code .= $item;
                   16148:     }
                   16149:     return $code;
                   16150: }
                   16151: 
1.444     albertel 16152: ############################################################
                   16153: ############################################################
                   16154: 
1.1237    raeburn  16155: # Community, Course and Placement Test
1.378     raeburn  16156: sub course_type {
                   16157:     my ($cid) = @_;
                   16158:     if (!defined($cid)) {
                   16159:         $cid = $env{'request.course.id'};
                   16160:     }
1.404     albertel 16161:     if (defined($env{'course.'.$cid.'.type'})) {
                   16162:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16163:     } else {
                   16164:         return 'Course';
1.377     raeburn  16165:     }
                   16166: }
1.156     albertel 16167: 
1.406     raeburn  16168: sub group_term {
                   16169:     my $crstype = &course_type();
                   16170:     my %names = (
                   16171:                   'Course' => 'group',
1.865     raeburn  16172:                   'Community' => 'group',
1.1237    raeburn  16173:                   'Placement' => 'group',
1.406     raeburn  16174:                 );
                   16175:     return $names{$crstype};
                   16176: }
                   16177: 
1.902     raeburn  16178: sub course_types {
1.1237    raeburn  16179:     my @types = ('official','unofficial','community','textbook','placement');
1.902     raeburn  16180:     my %typename = (
                   16181:                          official   => 'Official course',
                   16182:                          unofficial => 'Unofficial course',
                   16183:                          community  => 'Community',
1.1165    raeburn  16184:                          textbook   => 'Textbook course',
1.1237    raeburn  16185:                          placement  => 'Placement test',
1.902     raeburn  16186:                    );
                   16187:     return (\@types,\%typename);
                   16188: }
                   16189: 
1.156     albertel 16190: sub icon {
                   16191:     my ($file)=@_;
1.505     albertel 16192:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16193:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16194:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16195:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16196: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16197: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16198: 	            $curfext.".gif") {
                   16199: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16200: 		$curfext.".gif";
                   16201: 	}
                   16202:     }
1.249     albertel 16203:     return &lonhttpdurl($iconname);
1.154     albertel 16204: } 
1.84      albertel 16205: 
1.575     albertel 16206: sub lonhttpdurl {
1.692     www      16207: #
                   16208: # Had been used for "small fry" static images on separate port 8080.
                   16209: # Modify here if lightweight http functionality desired again.
                   16210: # Currently eliminated due to increasing firewall issues.
                   16211: #
1.575     albertel 16212:     my ($url)=@_;
1.692     www      16213:     return $url;
1.215     albertel 16214: }
                   16215: 
1.213     albertel 16216: sub connection_aborted {
                   16217:     my ($r)=@_;
                   16218:     $r->print(" ");$r->rflush();
                   16219:     my $c = $r->connection;
                   16220:     return $c->aborted();
                   16221: }
                   16222: 
1.221     foxr     16223: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16224: #    strings as 'strings'.
                   16225: sub escape_single {
1.221     foxr     16226:     my ($input) = @_;
1.223     albertel 16227:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16228:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16229:     return $input;
                   16230: }
1.223     albertel 16231: 
1.222     foxr     16232: #  Same as escape_single, but escape's "'s  This 
                   16233: #  can be used for  "strings"
                   16234: sub escape_double {
                   16235:     my ($input) = @_;
                   16236:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16237:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16238:     return $input;
                   16239: }
1.223     albertel 16240:  
1.222     foxr     16241: #   Escapes the last element of a full URL.
                   16242: sub escape_url {
                   16243:     my ($url)   = @_;
1.238     raeburn  16244:     my @urlslices = split(/\//, $url,-1);
1.369     www      16245:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  16246:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16247: }
1.462     albertel 16248: 
1.820     raeburn  16249: sub compare_arrays {
                   16250:     my ($arrayref1,$arrayref2) = @_;
                   16251:     my (@difference,%count);
                   16252:     @difference = ();
                   16253:     %count = ();
                   16254:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16255:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16256:         foreach my $element (keys(%count)) {
                   16257:             if ($count{$element} == 1) {
                   16258:                 push(@difference,$element);
                   16259:             }
                   16260:         }
                   16261:     }
                   16262:     return @difference;
                   16263: }
                   16264: 
1.817     bisitz   16265: # -------------------------------------------------------- Initialize user login
1.462     albertel 16266: sub init_user_environment {
1.463     albertel 16267:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16268:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16269: 
                   16270:     my $public=($username eq 'public' && $domain eq 'public');
                   16271: 
1.1062    raeburn  16272:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16273:     my $now=time;
                   16274: 
                   16275:     if ($public) {
                   16276: 	my $max_public=100;
                   16277: 	my $oldest;
                   16278: 	my $oldest_time=0;
                   16279: 	for(my $next=1;$next<=$max_public;$next++) {
                   16280: 	    if (-e $lonids."/publicuser_$next.id") {
                   16281: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16282: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16283: 		    $oldest_time=$mtime;
                   16284: 		    $oldest=$next;
                   16285: 		}
                   16286: 	    } else {
                   16287: 		$cookie="publicuser_$next";
                   16288: 		last;
                   16289: 	    }
                   16290: 	}
                   16291: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16292:     } else {
1.1275    raeburn  16293: 	# See if old ID present, if so, remove if this isn't a robot,
                   16294: 	# killing any existing non-robot sessions
1.463     albertel 16295: 	if (!$args->{'robot'}) {
                   16296: 	    opendir(DIR,$lonids);
                   16297: 	    while ($filename=readdir(DIR)) {
                   16298: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1295    raeburn  16299:                     if ($ENV{'SERVER_PORT'} == 443) {
                   16300:                         my $linkedfile;
                   16301:                         if (tie(my %oldenv,'GDBM_File',"$lonids/$cookie.id",
                   16302:                                 &GDBM_READER(),0640)) {
                   16303:                             if (exists($oldenv{'user.linkedenv'})) {
                   16304:                                 $linkedfile = $oldenv{'user.linkedenv'};
                   16305:                             }
                   16306:                             untie(%oldenv);
                   16307:                         }
                   16308:                         if (unlink($lonids.'/'.$filename)) {
                   16309:                             if ($linkedfile =~ /^[a-f0-9]+_linked\.id$/) {
                   16310:                                 unlink($lonids.'/'.$linkedfile);
                   16311:                             }
                   16312:                         }
                   16313:                     } else {
                   16314:                         unlink($lonids.'/'.$filename);
                   16315:                     }
1.463     albertel 16316: 		}
1.462     albertel 16317: 	    }
1.463     albertel 16318: 	    closedir(DIR);
1.1204    raeburn  16319: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16320:             my $namespace = 'nohist_courseeditor';
                   16321:             my $lockingkey = 'paste'."\0".'locked_num';
                   16322:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16323:                                                 $domain,$username);
                   16324:             if (exists($lockhash{$lockingkey})) {
                   16325:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16326:                 unless ($delresult eq 'ok') {
                   16327:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16328:                 }
                   16329:             }
1.462     albertel 16330: 	}
                   16331: # Give them a new cookie
1.463     albertel 16332: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16333: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16334: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16335:     
                   16336: # Initialize roles
                   16337: 
1.1062    raeburn  16338: 	($userroles,$firstaccenv,$timerintenv) = 
                   16339:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16340:     }
                   16341: # ------------------------------------ Check browser type and MathML capability
                   16342: 
1.1194    raeburn  16343:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16344:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16345: 
                   16346: # ------------------------------------------------------------- Get environment
                   16347: 
                   16348:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16349:     my ($tmp) = keys(%userenv);
1.1275    raeburn  16350:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 16351: 	undef(%userenv);
                   16352:     }
                   16353:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16354: 	$form->{'interface'}=$userenv{'interface'};
                   16355:     }
                   16356:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16357: 
                   16358: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16359:     foreach my $option ('interface','localpath','localres') {
                   16360:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16361:     }
                   16362: # --------------------------------------------------------- Write first profile
                   16363: 
                   16364:     {
                   16365: 	my %initial_env = 
                   16366: 	    ("user.name"          => $username,
                   16367: 	     "user.domain"        => $domain,
                   16368: 	     "user.home"          => $authhost,
                   16369: 	     "browser.type"       => $clientbrowser,
                   16370: 	     "browser.version"    => $clientversion,
                   16371: 	     "browser.mathml"     => $clientmathml,
                   16372: 	     "browser.unicode"    => $clientunicode,
                   16373: 	     "browser.os"         => $clientos,
1.1137    raeburn  16374:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  16375:              "browser.info"       => $clientinfo,
1.1194    raeburn  16376:              "browser.osversion"  => $clientosversion,
1.462     albertel 16377: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16378: 	     "request.course.fn"  => '',
                   16379: 	     "request.course.uri" => '',
                   16380: 	     "request.course.sec" => '',
                   16381: 	     "request.role"       => 'cm',
                   16382: 	     "request.role.adv"   => $env{'user.adv'},
                   16383: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   16384: 
                   16385:         if ($form->{'localpath'}) {
                   16386: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16387: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16388:         }
                   16389: 	
                   16390: 	if ($form->{'interface'}) {
                   16391: 	    $form->{'interface'}=~s/\W//gs;
                   16392: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16393: 	    $env{'browser.interface'}=$form->{'interface'};
                   16394: 	}
                   16395: 
1.1157    raeburn  16396:         if ($form->{'iptoken'}) {
                   16397:             my $lonhost = $r->dir_config('lonHostID');
                   16398:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16399:             $env{'user.noloadbalance'} = $lonhost;
                   16400:         }
                   16401: 
1.1268    raeburn  16402:         if ($form->{'noloadbalance'}) {
                   16403:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16404:             my $hosthere = $form->{'noloadbalance'};
                   16405:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16406:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16407:                 $env{'user.noloadbalance'} = $hosthere;
                   16408:             }
                   16409:         }
                   16410: 
1.1016    raeburn  16411:         unless ($domain eq 'public') {
1.1273    raeburn  16412:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16413:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   16414: 
                   16415:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   16416:                 $userenv{'availabletools.'.$tool} = 
                   16417:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16418:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16419:             }
1.980     raeburn  16420: 
1.1273    raeburn  16421:             foreach my $crstype ('official','unofficial','community','textbook','placement') {
                   16422:                 $userenv{'canrequest.'.$crstype} =
                   16423:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16424:                                                       'reload','requestcourses',
                   16425:                                                       \%userenv,\%domdef,\%is_adv);
                   16426:             }
1.724     raeburn  16427: 
1.1273    raeburn  16428:             $userenv{'canrequest.author'} =
                   16429:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16430:                                                   'reload','requestauthor',
1.980     raeburn  16431:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  16432:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16433:                                                  $domain,$username);
                   16434:             my $reqstatus = $reqauthor{'author_status'};
                   16435:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   16436:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16437:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16438:                                                       $reqauthor{'author'}{'timestamp'};
                   16439:                 }
1.1092    raeburn  16440:             }
1.1287    raeburn  16441:             my ($types,$typename) = &course_types();
                   16442:             if (ref($types) eq 'ARRAY') {
                   16443:                 my @options = ('approval','validate','autolimit');
                   16444:                 my $optregex = join('|',@options);
                   16445:                 my (%willtrust,%trustchecked);
                   16446:                 foreach my $type (@{$types}) {
                   16447:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   16448:                     if ($dom_str ne '') {
                   16449:                         my $updatedstr = '';
                   16450:                         my @possdomains = split(',',$dom_str);
                   16451:                         foreach my $entry (@possdomains) {
                   16452:                             my ($extdom,$extopt) = split(':',$entry);
                   16453:                             unless ($trustchecked{$extdom}) {
                   16454:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   16455:                                 $trustchecked{$extdom} = 1;
                   16456:                             }
                   16457:                             if ($willtrust{$extdom}) {
                   16458:                                 $updatedstr .= $entry.',';
                   16459:                             }
                   16460:                         }
                   16461:                         $updatedstr =~ s/,$//;
                   16462:                         if ($updatedstr) {
                   16463:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   16464:                         } else {
                   16465:                             delete($userenv{'reqcrsotherdom.'.$type});
                   16466:                         }
                   16467:                     }
                   16468:                 }
                   16469:             }
1.1092    raeburn  16470:         }
1.462     albertel 16471: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16472: 
1.462     albertel 16473: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16474: 		 &GDBM_WRCREAT(),0640)) {
                   16475: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16476: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16477: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16478:             if (ref($firstaccenv) eq 'HASH') {
                   16479:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16480:             }
                   16481:             if (ref($timerintenv) eq 'HASH') {
                   16482:                 &_add_to_env(\%disk_env,$timerintenv);
                   16483:             }
1.463     albertel 16484: 	    if (ref($args->{'extra_env'})) {
                   16485: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16486: 	    }
1.462     albertel 16487: 	    untie(%disk_env);
                   16488: 	} else {
1.705     tempelho 16489: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16490: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16491: 	    return 'error: '.$!;
                   16492: 	}
                   16493:     }
                   16494:     $env{'request.role'}='cm';
                   16495:     $env{'request.role.adv'}=$env{'user.adv'};
                   16496:     $env{'browser.type'}=$clientbrowser;
                   16497: 
                   16498:     return $cookie;
                   16499: 
                   16500: }
                   16501: 
                   16502: sub _add_to_env {
                   16503:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16504:     if (ref($env_data) eq 'HASH') {
                   16505:         while (my ($key,$value) = each(%$env_data)) {
                   16506: 	    $idf->{$prefix.$key} = $value;
                   16507: 	    $env{$prefix.$key}   = $value;
                   16508:         }
1.462     albertel 16509:     }
                   16510: }
                   16511: 
1.685     tempelho 16512: # --- Get the symbolic name of a problem and the url
                   16513: sub get_symb {
                   16514:     my ($request,$silent) = @_;
1.726     raeburn  16515:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16516:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16517:     if ($symb eq '') {
                   16518:         if (!$silent) {
1.1071    raeburn  16519:             if (ref($request)) { 
                   16520:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16521:             }
1.685     tempelho 16522:             return ();
                   16523:         }
                   16524:     }
                   16525:     &Apache::lonenc::check_decrypt(\$symb);
                   16526:     return ($symb);
                   16527: }
                   16528: 
                   16529: # --------------------------------------------------------------Get annotation
                   16530: 
                   16531: sub get_annotation {
                   16532:     my ($symb,$enc) = @_;
                   16533: 
                   16534:     my $key = $symb;
                   16535:     if (!$enc) {
                   16536:         $key =
                   16537:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16538:     }
                   16539:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16540:     return $annotation{$key};
                   16541: }
                   16542: 
                   16543: sub clean_symb {
1.731     raeburn  16544:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16545: 
                   16546:     &Apache::lonenc::check_decrypt(\$symb);
                   16547:     my $enc = $env{'request.enc'};
1.731     raeburn  16548:     if ($delete_enc) {
1.730     raeburn  16549:         delete($env{'request.enc'});
                   16550:     }
1.685     tempelho 16551: 
                   16552:     return ($symb,$enc);
                   16553: }
1.462     albertel 16554: 
1.1181    raeburn  16555: ############################################################
                   16556: ############################################################
                   16557: 
                   16558: =pod
                   16559: 
                   16560: =head1 Routines for building display used to search for courses
                   16561: 
                   16562: 
                   16563: =over 4
                   16564: 
                   16565: =item * &build_filters()
                   16566: 
                   16567: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  16568: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16569: and quotacheck.pl
                   16570: 
1.1181    raeburn  16571: 
                   16572: Inputs:
                   16573: 
                   16574: filterlist - anonymous array of fields to include as potential filters 
                   16575: 
                   16576: crstype - course type
                   16577: 
                   16578: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16579:               to pop-open a course selector (will contain "extra element"). 
                   16580: 
                   16581: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16582: 
                   16583: filter - anonymous hash of criteria and their values
                   16584: 
                   16585: action - form action
                   16586: 
                   16587: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16588: 
1.1182    raeburn  16589: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  16590: 
                   16591: cloneruname - username of owner of new course who wants to clone
                   16592: 
                   16593: clonerudom - domain of owner of new course who wants to clone
                   16594: 
                   16595: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   16596: 
                   16597: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16598: 
                   16599: codedom - domain
                   16600: 
                   16601: formname - value of form element named "form". 
                   16602: 
                   16603: fixeddom - domain, if fixed.
                   16604: 
                   16605: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   16606: 
                   16607: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   16608: 
                   16609: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16610: 
                   16611: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16612: 
                   16613: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16614: 
                   16615: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16616: 
                   16617: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16618: 
1.1182    raeburn  16619: 
1.1181    raeburn  16620: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16621: 
1.1182    raeburn  16622: 
1.1181    raeburn  16623: Side Effects: None
                   16624: 
                   16625: =cut
                   16626: 
                   16627: # ---------------------------------------------- search for courses based on last activity etc.
                   16628: 
                   16629: sub build_filters {
                   16630:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16631:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16632:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16633:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16634:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  16635:     my ($list,$jscript);
1.1181    raeburn  16636:     my $onchange = 'javascript:updateFilters(this)';
                   16637:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16638:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16639:         $typeselectform,$instcodetitle);
                   16640:     if ($formname eq '') {
                   16641:         $formname = $caller;
                   16642:     }
                   16643:     foreach my $item (@{$filterlist}) {
                   16644:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16645:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16646:             if ($item eq 'domainfilter') {
                   16647:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16648:             } elsif ($item eq 'coursefilter') {
                   16649:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16650:             } elsif ($item eq 'ownerfilter') {
                   16651:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16652:             } elsif ($item eq 'ownerdomfilter') {
                   16653:                 $filter->{'ownerdomfilter'} =
                   16654:                     &LONCAPA::clean_domain($filter->{$item});
                   16655:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16656:                                                        'ownerdomfilter',1);
                   16657:             } elsif ($item eq 'personfilter') {
                   16658:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16659:             } elsif ($item eq 'persondomfilter') {
                   16660:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16661:                                                         'persondomfilter',1);
                   16662:             } else {
                   16663:                 $filter->{$item} =~ s/\W//g;
                   16664:             }
                   16665:             if (!$filter->{$item}) {
                   16666:                 $filter->{$item} = '';
                   16667:             }
                   16668:         }
                   16669:         if ($item eq 'domainfilter') {
                   16670:             my $allow_blank = 1;
                   16671:             if ($formname eq 'portform') {
                   16672:                 $allow_blank=0;
                   16673:             } elsif ($formname eq 'studentform') {
                   16674:                 $allow_blank=0;
                   16675:             }
                   16676:             if ($fixeddom) {
                   16677:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16678:                                     ' value="'.$codedom.'" />'.
                   16679:                                     &Apache::lonnet::domain($codedom,'description');
                   16680:             } else {
                   16681:                 $domainselectform = &select_dom_form($filter->{$item},
                   16682:                                                      'domainfilter',
                   16683:                                                       $allow_blank,'',$onchange);
                   16684:             }
                   16685:         } else {
                   16686:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16687:         }
                   16688:     }
                   16689: 
                   16690:     # last course activity filter and selection
                   16691:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16692: 
                   16693:     # course created filter and selection
                   16694:     if (exists($filter->{'createdfilter'})) {
                   16695:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16696:     }
                   16697: 
1.1239    raeburn  16698:     my $prefix = $crstype;
                   16699:     if ($crstype eq 'Placement') {
                   16700:         $prefix = 'Placement Test'
                   16701:     }
1.1181    raeburn  16702:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  16703:                 'cac' => "$prefix Activity",
                   16704:                 'ccr' => "$prefix Created",
                   16705:                 'cde' => "$prefix Title",
                   16706:                 'cdo' => "$prefix Domain",
1.1181    raeburn  16707:                 'ins' => 'Institutional Code',
                   16708:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  16709:                 'cow' => "$prefix Owner/Co-owner",
                   16710:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  16711:                 'cog' => 'Type',
                   16712:              );
                   16713: 
                   16714:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16715:         my $typeval = 'Course';
                   16716:         if ($crstype eq 'Community') {
                   16717:             $typeval = 'Community';
1.1239    raeburn  16718:         } elsif ($crstype eq 'Placement') {
                   16719:             $typeval = 'Placement';
1.1181    raeburn  16720:         }
                   16721:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16722:     } else {
                   16723:         $typeselectform =  '<select name="type" size="1"';
                   16724:         if ($onchange) {
                   16725:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16726:         }
                   16727:         $typeselectform .= '>'."\n";
1.1237    raeburn  16728:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  16729:             my $shown;
                   16730:             if ($posstype eq 'Placement') {
                   16731:                 $shown = &mt('Placement Test');
                   16732:             } else {
                   16733:                 $shown = &mt($posstype);
                   16734:             }
1.1181    raeburn  16735:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  16736:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  16737:         }
                   16738:         $typeselectform.="</select>";
                   16739:     }
                   16740: 
                   16741:     my ($cloneableonlyform,$cloneabletitle);
                   16742:     if (exists($filter->{'cloneableonly'})) {
                   16743:         my $cloneableon = '';
                   16744:         my $cloneableoff = ' checked="checked"';
                   16745:         if ($filter->{'cloneableonly'}) {
                   16746:             $cloneableon = $cloneableoff;
                   16747:             $cloneableoff = '';
                   16748:         }
                   16749:         $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>';
                   16750:         if ($formname eq 'ccrs') {
1.1187    bisitz   16751:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  16752:         } else {
                   16753:             $cloneabletitle = &mt('Cloneable by you');
                   16754:         }
                   16755:     }
                   16756:     my $officialjs;
                   16757:     if ($crstype eq 'Course') {
                   16758:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  16759: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16760: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16761:             if ($codedom) { 
1.1181    raeburn  16762:                 $officialjs = 1;
                   16763:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16764:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16765:                                                                   $officialjs,$codetitlesref);
                   16766:                 if ($jscript) {
1.1182    raeburn  16767:                     $jscript = '<script type="text/javascript">'."\n".
                   16768:                                '// <![CDATA['."\n".
                   16769:                                $jscript."\n".
                   16770:                                '// ]]>'."\n".
                   16771:                                '</script>'."\n";
1.1181    raeburn  16772:                 }
                   16773:             }
                   16774:             if ($instcodeform eq '') {
                   16775:                 $instcodeform =
                   16776:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16777:                     $list->{'instcodefilter'}.'" />';
                   16778:                 $instcodetitle = $lt{'ins'};
                   16779:             } else {
                   16780:                 $instcodetitle = $lt{'inc'};
                   16781:             }
                   16782:             if ($fixeddom) {
                   16783:                 $instcodetitle .= '<br />('.$codedom.')';
                   16784:             }
                   16785:         }
                   16786:     }
                   16787:     my $output = qq|
                   16788: <form method="post" name="filterpicker" action="$action">
                   16789: <input type="hidden" name="form" value="$formname" />
                   16790: |;
                   16791:     if ($formname eq 'modifycourse') {
                   16792:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16793:                    '<input type="hidden" name="prevphase" value="'.
                   16794:                    $prevphase.'" />'."\n";
1.1198    musolffc 16795:     } elsif ($formname eq 'quotacheck') {
                   16796:         $output .= qq|
                   16797: <input type="hidden" name="sortby" value="" />
                   16798: <input type="hidden" name="sortorder" value="" />
                   16799: |;
                   16800:     } else {
1.1181    raeburn  16801:         my $name_input;
                   16802:         if ($cnameelement ne '') {
                   16803:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16804:                           $cnameelement.'" />';
                   16805:         }
                   16806:         $output .= qq|
1.1182    raeburn  16807: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16808: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  16809: $name_input
                   16810: $roleelement
                   16811: $multelement
                   16812: $typeelement
                   16813: |;
                   16814:         if ($formname eq 'portform') {
                   16815:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16816:         }
                   16817:     }
                   16818:     if ($fixeddom) {
                   16819:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16820:     }
                   16821:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16822:     if ($sincefilterform) {
                   16823:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16824:                   .$sincefilterform
                   16825:                   .&Apache::lonhtmlcommon::row_closure();
                   16826:     }
                   16827:     if ($createdfilterform) {
                   16828:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16829:                   .$createdfilterform
                   16830:                   .&Apache::lonhtmlcommon::row_closure();
                   16831:     }
                   16832:     if ($domainselectform) {
                   16833:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16834:                   .$domainselectform
                   16835:                   .&Apache::lonhtmlcommon::row_closure();
                   16836:     }
                   16837:     if ($typeselectform) {
                   16838:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16839:             $output .= $typeselectform;
                   16840:         } else {
                   16841:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16842:                       .$typeselectform
                   16843:                       .&Apache::lonhtmlcommon::row_closure();
                   16844:         }
                   16845:     }
                   16846:     if ($instcodeform) {
                   16847:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16848:                   .$instcodeform
                   16849:                   .&Apache::lonhtmlcommon::row_closure();
                   16850:     }
                   16851:     if (exists($filter->{'ownerfilter'})) {
                   16852:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16853:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16854:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16855:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16856:                    $ownerdomselectform.'</td></tr></table>'.
                   16857:                    &Apache::lonhtmlcommon::row_closure();
                   16858:     }
                   16859:     if (exists($filter->{'personfilter'})) {
                   16860:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16861:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16862:                    '<input type="text" name="personfilter" size="20" value="'.
                   16863:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16864:                    $persondomselectform.'</td></tr></table>'.
                   16865:                    &Apache::lonhtmlcommon::row_closure();
                   16866:     }
                   16867:     if (exists($filter->{'coursefilter'})) {
                   16868:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16869:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16870:                   .$list->{'coursefilter'}.'" />'
                   16871:                   .&Apache::lonhtmlcommon::row_closure();
                   16872:     }
                   16873:     if ($cloneableonlyform) {
                   16874:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16875:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16876:     }
                   16877:     if (exists($filter->{'descriptfilter'})) {
                   16878:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16879:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16880:                   .$list->{'descriptfilter'}.'" />'
                   16881:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16882:     }
                   16883:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16884:                '<input type="hidden" name="updater" value="" />'."\n".
                   16885:                '<input type="submit" name="gosearch" value="'.
                   16886:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16887:     return $jscript.$clonewarning.$output;
                   16888: }
                   16889: 
                   16890: =pod 
                   16891: 
                   16892: =item * &timebased_select_form()
                   16893: 
1.1182    raeburn  16894: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  16895: filter e.g., Course Activity, Course Created, when searching for courses
                   16896: or communities
                   16897: 
                   16898: Inputs:
                   16899: 
                   16900: item - name of form element (sincefilter or createdfilter)
                   16901: 
                   16902: filter - anonymous hash of criteria and their values
                   16903: 
                   16904: Returns: HTML for a select box contained a blank, then six time selections,
                   16905:          with value set in incoming form variables currently selected. 
                   16906: 
                   16907: Side Effects: None
                   16908: 
                   16909: =cut
                   16910: 
                   16911: sub timebased_select_form {
                   16912:     my ($item,$filter) = @_;
                   16913:     if (ref($filter) eq 'HASH') {
                   16914:         $filter->{$item} =~ s/[^\d-]//g;
                   16915:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16916:         return &select_form(
                   16917:                             $filter->{$item},
                   16918:                             $item,
                   16919:                             {      '-1' => '',
                   16920:                                 '86400' => &mt('today'),
                   16921:                                '604800' => &mt('last week'),
                   16922:                               '2592000' => &mt('last month'),
                   16923:                               '7776000' => &mt('last three months'),
                   16924:                              '15552000' => &mt('last six months'),
                   16925:                              '31104000' => &mt('last year'),
                   16926:                     'select_form_order' =>
                   16927:                            ['-1','86400','604800','2592000','7776000',
                   16928:                             '15552000','31104000']});
                   16929:     }
                   16930: }
                   16931: 
                   16932: =pod
                   16933: 
                   16934: =item * &js_changer()
                   16935: 
                   16936: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  16937: when course type or domain is changed, and also to hide 'Searching ...' on
                   16938: page load completion for page showing search result.
1.1181    raeburn  16939: 
                   16940: Inputs: None
                   16941: 
1.1183    raeburn  16942: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  16943: 
                   16944: Side Effects: None
                   16945: 
                   16946: =cut
                   16947: 
                   16948: sub js_changer {
                   16949:     return <<ENDJS;
                   16950: <script type="text/javascript">
                   16951: // <![CDATA[
                   16952: function updateFilters(caller) {
                   16953:     if (typeof(caller) != "undefined") {
                   16954:         document.filterpicker.updater.value = caller.name;
                   16955:     }
                   16956:     document.filterpicker.submit();
                   16957: }
1.1183    raeburn  16958: 
                   16959: function hideSearching() {
                   16960:     if (document.getElementById('searching')) {
                   16961:         document.getElementById('searching').style.display = 'none';
                   16962:     }
                   16963:     return;
                   16964: }
                   16965: 
1.1181    raeburn  16966: // ]]>
                   16967: </script>
                   16968: 
                   16969: ENDJS
                   16970: }
                   16971: 
                   16972: =pod
                   16973: 
1.1182    raeburn  16974: =item * &search_courses()
                   16975: 
                   16976: Process selected filters form course search form and pass to lonnet::courseiddump
                   16977: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16978: 
                   16979: Inputs:
                   16980: 
                   16981: dom - domain being searched 
                   16982: 
                   16983: type - course type ('Course' or 'Community' or '.' if any).
                   16984: 
                   16985: filter - anonymous hash of criteria and their values
                   16986: 
                   16987: numtitles - for institutional codes - number of categories
                   16988: 
                   16989: cloneruname - optional username of new course owner
                   16990: 
                   16991: clonerudom - optional domain of new course owner
                   16992: 
1.1221    raeburn  16993: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  16994:             (used when DC is using course creation form)
                   16995: 
                   16996: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16997: 
1.1221    raeburn  16998: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16999:            (and so can clone automatically)
                   17000: 
                   17001: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17002: 
                   17003: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17004:               courses to clone 
1.1182    raeburn  17005: 
                   17006: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17007: 
                   17008: 
                   17009: Side Effects: None
                   17010: 
                   17011: =cut
                   17012: 
                   17013: 
                   17014: sub search_courses {
1.1221    raeburn  17015:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17016:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17017:     my (%courses,%showcourses,$cloner);
                   17018:     if (($filter->{'ownerfilter'} ne '') ||
                   17019:         ($filter->{'ownerdomfilter'} ne '')) {
                   17020:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17021:                                        $filter->{'ownerdomfilter'};
                   17022:     }
                   17023:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17024:         if (!$filter->{$item}) {
                   17025:             $filter->{$item}='.';
                   17026:         }
                   17027:     }
                   17028:     my $now = time;
                   17029:     my $timefilter =
                   17030:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17031:     my ($createdbefore,$createdafter);
                   17032:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17033:         $createdbefore = $now;
                   17034:         $createdafter = $now-$filter->{'createdfilter'};
                   17035:     }
                   17036:     my ($instcodefilter,$regexpok);
                   17037:     if ($numtitles) {
                   17038:         if ($env{'form.official'} eq 'on') {
                   17039:             $instcodefilter =
                   17040:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17041:             $regexpok = 1;
                   17042:         } elsif ($env{'form.official'} eq 'off') {
                   17043:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17044:             unless ($instcodefilter eq '') {
                   17045:                 $regexpok = -1;
                   17046:             }
                   17047:         }
                   17048:     } else {
                   17049:         $instcodefilter = $filter->{'instcodefilter'};
                   17050:     }
                   17051:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17052:     if ($type eq '') { $type = '.'; }
                   17053: 
                   17054:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17055:         $cloner = $cloneruname.':'.$clonerudom;
                   17056:     }
                   17057:     %courses = &Apache::lonnet::courseiddump($dom,
                   17058:                                              $filter->{'descriptfilter'},
                   17059:                                              $timefilter,
                   17060:                                              $instcodefilter,
                   17061:                                              $filter->{'combownerfilter'},
                   17062:                                              $filter->{'coursefilter'},
                   17063:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  17064:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  17065:                                              $filter->{'cloneableonly'},
                   17066:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  17067:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  17068:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17069:         my $ccrole;
                   17070:         if ($type eq 'Community') {
                   17071:             $ccrole = 'co';
                   17072:         } else {
                   17073:             $ccrole = 'cc';
                   17074:         }
                   17075:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17076:                                                      $filter->{'persondomfilter'},
                   17077:                                                      'userroles',undef,
                   17078:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17079:                                                      $dom);
                   17080:         foreach my $role (keys(%rolehash)) {
                   17081:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17082:             my $cid = $cdom.'_'.$cnum;
                   17083:             if (exists($courses{$cid})) {
                   17084:                 if (ref($courses{$cid}) eq 'HASH') {
                   17085:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17086:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  17087:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  17088:                         }
                   17089:                     } else {
                   17090:                         $courses{$cid}{roles} = [$courserole];
                   17091:                     }
                   17092:                     $showcourses{$cid} = $courses{$cid};
                   17093:                 }
                   17094:             }
                   17095:         }
                   17096:         %courses = %showcourses;
                   17097:     }
                   17098:     return %courses;
                   17099: }
                   17100: 
                   17101: =pod
                   17102: 
1.1181    raeburn  17103: =back
                   17104: 
1.1207    raeburn  17105: =head1 Routines for version requirements for current course.
                   17106: 
                   17107: =over 4
                   17108: 
                   17109: =item * &check_release_required()
                   17110: 
                   17111: Compares required LON-CAPA version with version on server, and
                   17112: if required version is newer looks for a server with the required version.
                   17113: 
                   17114: Looks first at servers in user's owen domain; if none suitable, looks at
                   17115: servers in course's domain are permitted to host sessions for user's domain.
                   17116: 
                   17117: Inputs:
                   17118: 
                   17119: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17120: 
                   17121: $courseid - Course ID of current course
                   17122: 
                   17123: $rolecode - User's current role in course (for switchserver query string).
                   17124: 
                   17125: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17126: 
                   17127: 
                   17128: Returns:
                   17129: 
                   17130: $switchserver - query string tp append to /adm/switchserver call (if 
                   17131:                 current server's LON-CAPA version is too old. 
                   17132: 
                   17133: $warning - Message is displayed if no suitable server could be found.
                   17134: 
                   17135: =cut
                   17136: 
                   17137: sub check_release_required {
                   17138:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17139:     my ($switchserver,$warning);
                   17140:     if ($required ne '') {
                   17141:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17142:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17143:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17144:             my $otherserver;
                   17145:             if (($major eq '' && $minor eq '') ||
                   17146:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17147:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17148:                 my $switchlcrev =
                   17149:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17150:                                                            $userdomserver);
                   17151:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17152:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17153:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17154:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17155:                     if ($cdom ne $env{'user.domain'}) {
                   17156:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17157:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17158:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17159:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17160:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17161:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17162:                         my $canhost =
                   17163:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17164:                                                               $coursedomserver,
                   17165:                                                               $remoterev,
                   17166:                                                               $udomdefaults{'remotesessions'},
                   17167:                                                               $defdomdefaults{'hostedsessions'});
                   17168: 
                   17169:                         if ($canhost) {
                   17170:                             $otherserver = $coursedomserver;
                   17171:                         } else {
                   17172:                             $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.");
                   17173:                         }
                   17174:                     } else {
                   17175:                         $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).");
                   17176:                     }
                   17177:                 } else {
                   17178:                     $otherserver = $userdomserver;
                   17179:                 }
                   17180:             }
                   17181:             if ($otherserver ne '') {
                   17182:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17183:             }
                   17184:         }
                   17185:     }
                   17186:     return ($switchserver,$warning);
                   17187: }
                   17188: 
                   17189: =pod
                   17190: 
                   17191: =item * &check_release_result()
                   17192: 
                   17193: Inputs:
                   17194: 
                   17195: $switchwarning - Warning message if no suitable server found to host session.
                   17196: 
                   17197: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17198:                 and current role.
                   17199: 
                   17200: Returns: HTML to display with information about requirement to switch server.
                   17201:          Either displaying warning with link to Roles/Courses screen or
                   17202:          display link to switchserver.
                   17203: 
1.1181    raeburn  17204: =cut
                   17205: 
1.1207    raeburn  17206: sub check_release_result {
                   17207:     my ($switchwarning,$switchserver) = @_;
                   17208:     my $output = &start_page('Selected course unavailable on this server').
                   17209:                  '<p class="LC_warning">';
                   17210:     if ($switchwarning) {
                   17211:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17212:         if (&show_course()) {
                   17213:             $output .= &mt('Display courses');
                   17214:         } else {
                   17215:             $output .= &mt('Display roles');
                   17216:         }
                   17217:         $output .= '</a>';
                   17218:     } elsif ($switchserver) {
                   17219:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17220:                    '<br />'.
                   17221:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17222:                    &mt('Switch Server').
                   17223:                    '</a>';
                   17224:     }
                   17225:     $output .= '</p>'.&end_page();
                   17226:     return $output;
                   17227: }
                   17228: 
                   17229: =pod
                   17230: 
                   17231: =item * &needs_coursereinit()
                   17232: 
                   17233: Determine if course contents stored for user's session needs to be
                   17234: refreshed, because content has changed since "Big Hash" last tied.
                   17235: 
                   17236: Check for change is made if time last checked is more than 10 minutes ago
                   17237: (by default).
                   17238: 
                   17239: Inputs:
                   17240: 
                   17241: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17242: 
                   17243: $interval (optional) - Time which may elapse (in s) between last check for content
                   17244:                        change in current course. (default: 600 s).  
                   17245: 
                   17246: Returns: an array; first element is:
                   17247: 
                   17248: =over 4
                   17249: 
                   17250: 'switch' - if content updates mean user's session
                   17251:            needs to be switched to a server running a newer LON-CAPA version
                   17252:  
                   17253: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17254:            on current server hosting user's session                
                   17255: 
                   17256: ''       - if no action required.
                   17257: 
                   17258: =back
                   17259: 
                   17260: If first item element is 'switch':
                   17261: 
                   17262: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   17263: 
                   17264: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17265:                               and current role. 
                   17266: 
                   17267: otherwise: no other elements returned.
                   17268: 
                   17269: =back
                   17270: 
                   17271: =cut
                   17272: 
                   17273: sub needs_coursereinit {
                   17274:     my ($loncaparev,$interval) = @_;
                   17275:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17276:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17277:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17278:     my $now = time;
                   17279:     if ($interval eq '') {
                   17280:         $interval = 600;
                   17281:     }
                   17282:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  17283:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1283    raeburn  17284:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
1.1282    raeburn  17285:         if ($blocked) {
                   17286:             return ();
                   17287:         }
1.1207    raeburn  17288:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17289:         if ($lastchange > $env{'request.course.tied'}) {
                   17290:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17291:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17292:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17293:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17294:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17295:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   17296:                     my ($switchserver,$switchwarning) =
                   17297:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17298:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17299:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17300:                         return ('switch',$switchwarning,$switchserver);
                   17301:                     }
                   17302:                 }
                   17303:             }
                   17304:             return ('update');
                   17305:         }
                   17306:     }
                   17307:     return ();
                   17308: }
1.1181    raeburn  17309: 
1.1083    raeburn  17310: sub update_content_constraints {
                   17311:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17312:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17313:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   17314:     my %checkresponsetypes;
                   17315:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  17316:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  17317:         if ($item eq 'resourcetag') {
                   17318:             if ($name eq 'responsetype') {
                   17319:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17320:             }
                   17321:         }
                   17322:     }
                   17323:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17324:     if (defined($navmap)) {
                   17325:         my %allresponses;
                   17326:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   17327:             my %responses = $res->responseTypes();
                   17328:             foreach my $key (keys(%responses)) {
                   17329:                 next unless(exists($checkresponsetypes{$key}));
                   17330:                 $allresponses{$key} += $responses{$key};
                   17331:             }
                   17332:         }
                   17333:         foreach my $key (keys(%allresponses)) {
                   17334:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17335:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17336:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17337:             }
                   17338:         }
                   17339:         undef($navmap);
                   17340:     }
                   17341:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17342:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17343:     }
                   17344:     return;
                   17345: }
                   17346: 
1.1110    raeburn  17347: sub allmaps_incourse {
                   17348:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17349:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17350:         $cid = $env{'request.course.id'};
                   17351:         $cdom = $env{'course.'.$cid.'.domain'};
                   17352:         $cnum = $env{'course.'.$cid.'.num'};
                   17353:         $chome = $env{'course.'.$cid.'.home'};
                   17354:     }
                   17355:     my %allmaps = ();
                   17356:     my $lastchange =
                   17357:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17358:     if ($lastchange > $env{'request.course.tied'}) {
                   17359:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17360:         unless ($ferr) {
                   17361:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   17362:         }
                   17363:     }
                   17364:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17365:     if (defined($navmap)) {
                   17366:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17367:             $allmaps{$res->src()} = 1;
                   17368:         }
                   17369:     }
                   17370:     return \%allmaps;
                   17371: }
                   17372: 
1.1083    raeburn  17373: sub parse_supplemental_title {
                   17374:     my ($title) = @_;
                   17375: 
                   17376:     my ($foldertitle,$renametitle);
                   17377:     if ($title =~ /&amp;&amp;&amp;/) {
                   17378:         $title = &HTML::Entites::decode($title);
                   17379:     }
                   17380:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17381:         $renametitle=$4;
                   17382:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17383:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17384:         my $name =  &plainname($uname,$udom);
                   17385:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17386:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17387:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17388:             $name.': <br />'.$foldertitle;
                   17389:     }
                   17390:     if (wantarray) {
                   17391:         return ($title,$foldertitle,$renametitle);
                   17392:     }
                   17393:     return $title;
                   17394: }
                   17395: 
1.1143    raeburn  17396: sub recurse_supplemental {
                   17397:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   17398:     if ($suppmap) {
                   17399:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17400:         if ($fatal) {
                   17401:             $errors ++;
                   17402:         } else {
                   17403:             if ($#LONCAPA::map::resources > 0) {
                   17404:                 foreach my $res (@LONCAPA::map::resources) {
                   17405:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   17406:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  17407:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   17408:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  17409:                         } else {
                   17410:                             $numfiles ++;
                   17411:                         }
                   17412:                     }
                   17413:                 }
                   17414:             }
                   17415:         }
                   17416:     }
                   17417:     return ($numfiles,$errors);
                   17418: }
                   17419: 
1.1101    raeburn  17420: sub symb_to_docspath {
1.1267    raeburn  17421:     my ($symb,$navmapref) = @_;
                   17422:     return unless ($symb && ref($navmapref));
1.1101    raeburn  17423:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17424:     if ($resurl=~/\.(sequence|page)$/) {
                   17425:         $mapurl=$resurl;
                   17426:     } elsif ($resurl eq 'adm/navmaps') {
                   17427:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17428:     }
                   17429:     my $mapresobj;
1.1267    raeburn  17430:     unless (ref($$navmapref)) {
                   17431:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17432:     }
                   17433:     if (ref($$navmapref)) {
                   17434:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  17435:     }
                   17436:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17437:     my $type=$2;
                   17438:     my $path;
                   17439:     if (ref($mapresobj)) {
                   17440:         my $pcslist = $mapresobj->map_hierarchy();
                   17441:         if ($pcslist ne '') {
                   17442:             foreach my $pc (split(/,/,$pcslist)) {
                   17443:                 next if ($pc <= 1);
1.1267    raeburn  17444:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  17445:                 if (ref($res)) {
                   17446:                     my $thisurl = $res->src();
                   17447:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17448:                     my $thistitle = $res->title();
                   17449:                     $path .= '&'.
                   17450:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  17451:                              &escape($thistitle).
1.1101    raeburn  17452:                              ':'.$res->randompick().
                   17453:                              ':'.$res->randomout().
                   17454:                              ':'.$res->encrypted().
                   17455:                              ':'.$res->randomorder().
                   17456:                              ':'.$res->is_page();
                   17457:                 }
                   17458:             }
                   17459:         }
                   17460:         $path =~ s/^\&//;
                   17461:         my $maptitle = $mapresobj->title();
                   17462:         if ($mapurl eq 'default') {
1.1129    raeburn  17463:             $maptitle = 'Main Content';
1.1101    raeburn  17464:         }
                   17465:         $path .= (($path ne '')? '&' : '').
                   17466:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17467:                  &escape($maptitle).
1.1101    raeburn  17468:                  ':'.$mapresobj->randompick().
                   17469:                  ':'.$mapresobj->randomout().
                   17470:                  ':'.$mapresobj->encrypted().
                   17471:                  ':'.$mapresobj->randomorder().
                   17472:                  ':'.$mapresobj->is_page();
                   17473:     } else {
                   17474:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17475:         my $ispage = (($type eq 'page')? 1 : '');
                   17476:         if ($mapurl eq 'default') {
1.1129    raeburn  17477:             $maptitle = 'Main Content';
1.1101    raeburn  17478:         }
                   17479:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17480:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  17481:     }
                   17482:     unless ($mapurl eq 'default') {
                   17483:         $path = 'default&'.
1.1146    raeburn  17484:                 &escape('Main Content').
1.1101    raeburn  17485:                 ':::::&'.$path;
                   17486:     }
                   17487:     return $path;
                   17488: }
                   17489: 
1.1094    raeburn  17490: sub captcha_display {
                   17491:     my ($context,$lonhost) = @_;
                   17492:     my ($output,$error);
1.1234    raeburn  17493:     my ($captcha,$pubkey,$privkey,$version) = 
                   17494:         &get_captcha_config($context,$lonhost);
1.1095    raeburn  17495:     if ($captcha eq 'original') {
1.1094    raeburn  17496:         $output = &create_captcha();
                   17497:         unless ($output) {
1.1172    raeburn  17498:             $error = 'captcha';
1.1094    raeburn  17499:         }
                   17500:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17501:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  17502:         unless ($output) {
1.1172    raeburn  17503:             $error = 'recaptcha';
1.1094    raeburn  17504:         }
                   17505:     }
1.1234    raeburn  17506:     return ($output,$error,$captcha,$version);
1.1094    raeburn  17507: }
                   17508: 
                   17509: sub captcha_response {
                   17510:     my ($context,$lonhost) = @_;
                   17511:     my ($captcha_chk,$captcha_error);
1.1234    raeburn  17512:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  17513:     if ($captcha eq 'original') {
1.1094    raeburn  17514:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17515:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17516:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  17517:     } else {
                   17518:         $captcha_chk = 1;
                   17519:     }
                   17520:     return ($captcha_chk,$captcha_error);
                   17521: }
                   17522: 
                   17523: sub get_captcha_config {
                   17524:     my ($context,$lonhost) = @_;
1.1234    raeburn  17525:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  17526:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17527:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17528:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  17529:     if ($context eq 'usercreation') {
                   17530:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17531:         if (ref($domconfig{$context}) eq 'HASH') {
                   17532:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17533:             if (ref($hashtocheck) eq 'HASH') {
                   17534:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17535:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17536:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17537:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17538:                     }
                   17539:                     if ($privkey && $pubkey) {
                   17540:                         $captcha = 'recaptcha';
1.1234    raeburn  17541:                         $version = $hashtocheck->{'recaptchaversion'};
                   17542:                         if ($version ne '2') {
                   17543:                             $version = 1;
                   17544:                         }
1.1095    raeburn  17545:                     } else {
                   17546:                         $captcha = 'original';
                   17547:                     }
                   17548:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17549:                     $captcha = 'original';
                   17550:                 }
1.1094    raeburn  17551:             }
1.1095    raeburn  17552:         } else {
                   17553:             $captcha = 'captcha';
                   17554:         }
                   17555:     } elsif ($context eq 'login') {
                   17556:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17557:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17558:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17559:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  17560:             if ($privkey && $pubkey) {
                   17561:                 $captcha = 'recaptcha';
1.1234    raeburn  17562:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17563:                 if ($version ne '2') {
                   17564:                     $version = 1; 
                   17565:                 }
1.1095    raeburn  17566:             } else {
                   17567:                 $captcha = 'original';
1.1094    raeburn  17568:             }
1.1095    raeburn  17569:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17570:             $captcha = 'original';
1.1094    raeburn  17571:         }
                   17572:     }
1.1234    raeburn  17573:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  17574: }
                   17575: 
                   17576: sub create_captcha {
                   17577:     my %captcha_params = &captcha_settings();
                   17578:     my ($output,$maxtries,$tries) = ('',10,0);
                   17579:     while ($tries < $maxtries) {
                   17580:         $tries ++;
                   17581:         my $captcha = Authen::Captcha->new (
                   17582:                                            output_folder => $captcha_params{'output_dir'},
                   17583:                                            data_folder   => $captcha_params{'db_dir'},
                   17584:                                           );
                   17585:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17586: 
                   17587:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17588:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17589:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  17590:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17591:                       '<br />'.
                   17592:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  17593:             last;
                   17594:         }
                   17595:     }
                   17596:     return $output;
                   17597: }
                   17598: 
                   17599: sub captcha_settings {
                   17600:     my %captcha_params = (
                   17601:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17602:                            www_output_dir => "/captchaspool",
                   17603:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17604:                            numchars       => '5',
                   17605:                          );
                   17606:     return %captcha_params;
                   17607: }
                   17608: 
                   17609: sub check_captcha {
                   17610:     my ($captcha_chk,$captcha_error);
                   17611:     my $code = $env{'form.code'};
                   17612:     my $md5sum = $env{'form.crypt'};
                   17613:     my %captcha_params = &captcha_settings();
                   17614:     my $captcha = Authen::Captcha->new(
                   17615:                       output_folder => $captcha_params{'output_dir'},
                   17616:                       data_folder   => $captcha_params{'db_dir'},
                   17617:                   );
1.1109    raeburn  17618:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  17619:     my %captcha_hash = (
                   17620:                         0       => 'Code not checked (file error)',
                   17621:                        -1      => 'Failed: code expired',
                   17622:                        -2      => 'Failed: invalid code (not in database)',
                   17623:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17624:     );
                   17625:     if ($captcha_chk != 1) {
                   17626:         $captcha_error = $captcha_hash{$captcha_chk}
                   17627:     }
                   17628:     return ($captcha_chk,$captcha_error);
                   17629: }
                   17630: 
                   17631: sub create_recaptcha {
1.1234    raeburn  17632:     my ($pubkey,$version) = @_;
                   17633:     if ($version >= 2) {
                   17634:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17635:     } else {
                   17636:         my $use_ssl;
                   17637:         if ($ENV{'SERVER_PORT'} == 443) {
                   17638:             $use_ssl = 1;
                   17639:         }
                   17640:         my $captcha = Captcha::reCAPTCHA->new;
                   17641:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17642:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17643:                &mt('If the text is hard to read, [_1] will replace them.',
                   17644:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17645:                '<br /><br />';
                   17646:     }
1.1094    raeburn  17647: }
                   17648: 
                   17649: sub check_recaptcha {
1.1234    raeburn  17650:     my ($privkey,$version) = @_;
1.1094    raeburn  17651:     my $captcha_chk;
1.1234    raeburn  17652:     if ($version >= 2) {
                   17653:         my %info = (
                   17654:                      secret   => $privkey, 
                   17655:                      response => $env{'form.g-recaptcha-response'},
                   17656:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17657:                    );
1.1280    raeburn  17658:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   17659:         $request->content(join('&',map {
                   17660:                          my $name = escape($_);
                   17661:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   17662:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   17663:                          : &escape($info{$_}) );
                   17664:         } keys(%info)));
                   17665:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  17666:         if ($response->is_success)  {
                   17667:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17668:             if (ref($data) eq 'HASH') {
                   17669:                 if ($data->{'success'}) {
                   17670:                     $captcha_chk = 1;
                   17671:                 }
                   17672:             }
                   17673:         }
                   17674:     } else {
                   17675:         my $captcha = Captcha::reCAPTCHA->new;
                   17676:         my $captcha_result =
                   17677:             $captcha->check_answer(
                   17678:                                     $privkey,
                   17679:                                     $ENV{'REMOTE_ADDR'},
                   17680:                                     $env{'form.recaptcha_challenge_field'},
                   17681:                                     $env{'form.recaptcha_response_field'},
                   17682:                                   );
                   17683:         if ($captcha_result->{is_valid}) {
                   17684:             $captcha_chk = 1;
                   17685:         }
1.1094    raeburn  17686:     }
                   17687:     return $captcha_chk;
                   17688: }
                   17689: 
1.1174    raeburn  17690: sub emailusername_info {
1.1244    raeburn  17691:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  17692:     my %titles = &Apache::lonlocal::texthash (
                   17693:                      lastname      => 'Last Name',
                   17694:                      firstname     => 'First Name',
                   17695:                      institution   => 'School/college/university',
                   17696:                      location      => "School's city, state/province, country",
                   17697:                      web           => "School's web address",
                   17698:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  17699:                      id            => 'Student/Employee ID',
1.1174    raeburn  17700:                  );
                   17701:     return (\@fields,\%titles);
                   17702: }
                   17703: 
1.1161    raeburn  17704: sub cleanup_html {
                   17705:     my ($incoming) = @_;
                   17706:     my $outgoing;
                   17707:     if ($incoming ne '') {
                   17708:         $outgoing = $incoming;
                   17709:         $outgoing =~ s/;/&#059;/g;
                   17710:         $outgoing =~ s/\#/&#035;/g;
                   17711:         $outgoing =~ s/\&/&#038;/g;
                   17712:         $outgoing =~ s/</&#060;/g;
                   17713:         $outgoing =~ s/>/&#062;/g;
                   17714:         $outgoing =~ s/\(/&#040/g;
                   17715:         $outgoing =~ s/\)/&#041;/g;
                   17716:         $outgoing =~ s/"/&#034;/g;
                   17717:         $outgoing =~ s/'/&#039;/g;
                   17718:         $outgoing =~ s/\$/&#036;/g;
                   17719:         $outgoing =~ s{/}{&#047;}g;
                   17720:         $outgoing =~ s/=/&#061;/g;
                   17721:         $outgoing =~ s/\\/&#092;/g
                   17722:     }
                   17723:     return $outgoing;
                   17724: }
                   17725: 
1.1190    musolffc 17726: # Checks for critical messages and returns a redirect url if one exists.
                   17727: # $interval indicates how often to check for messages.
1.1282    raeburn  17728: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 17729: sub critical_redirect {
1.1282    raeburn  17730:     my ($interval,$context) = @_;
1.1190    musolffc 17731:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  17732:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   17733:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17734:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17735:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   17736:             if ($blocked) {
                   17737:                 my $checkrole = "cm./$cdom/$cnum";
                   17738:                 if ($env{'request.course.sec'} ne '') {
                   17739:                     $checkrole .= "/$env{'request.course.sec'}";
                   17740:                 }
                   17741:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   17742:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   17743:                     return;
                   17744:                 }
                   17745:             }
                   17746:         }
1.1190    musolffc 17747:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   17748:                                         $env{'user.name'});
                   17749:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  17750:         my $redirecturl;
1.1190    musolffc 17751:         if ($what[0]) {
                   17752: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17753: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  17754: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17755:                 return (1, $url);
1.1190    musolffc 17756:             }
1.1191    raeburn  17757:         }
                   17758:     } 
                   17759:     return ();
1.1190    musolffc 17760: }
                   17761: 
1.1174    raeburn  17762: # Use:
                   17763: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17764: #
                   17765: ##################################################
                   17766: #          password associated functions         #
                   17767: ##################################################
                   17768: sub des_keys {
                   17769:     # Make a new key for DES encryption.
                   17770:     # Each key has two parts which are returned separately.
                   17771:     # Please note:  Each key must be passed through the &hex function
                   17772:     # before it is output to the web browser.  The hex versions cannot
                   17773:     # be used to decrypt.
                   17774:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17775:                 '8','9','a','b','c','d','e','f');
                   17776:     my $lkey='';
                   17777:     for (0..7) {
                   17778:         $lkey.=$hexstr[rand(15)];
                   17779:     }
                   17780:     my $ukey='';
                   17781:     for (0..7) {
                   17782:         $ukey.=$hexstr[rand(15)];
                   17783:     }
                   17784:     return ($lkey,$ukey);
                   17785: }
                   17786: 
                   17787: sub des_decrypt {
                   17788:     my ($key,$cyphertext) = @_;
                   17789:     my $keybin=pack("H16",$key);
                   17790:     my $cypher;
                   17791:     if ($Crypt::DES::VERSION>=2.03) {
                   17792:         $cypher=new Crypt::DES $keybin;
                   17793:     } else {
                   17794:         $cypher=new DES $keybin;
                   17795:     }
1.1233    raeburn  17796:     my $plaintext='';
                   17797:     my $cypherlength = length($cyphertext);
                   17798:     my $numchunks = int($cypherlength/32);
                   17799:     for (my $j=0; $j<$numchunks; $j++) {
                   17800:         my $start = $j*32;
                   17801:         my $cypherblock = substr($cyphertext,$start,32);
                   17802:         my $chunk =
                   17803:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17804:         $chunk .=
                   17805:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17806:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17807:         $plaintext .= $chunk;
                   17808:     }
1.1174    raeburn  17809:     return $plaintext;
                   17810: }
                   17811: 
1.112     bowersj2 17812: 1;
                   17813: __END__;
1.41      ng       17814: 

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