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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1269  ! raeburn     4: # $Id: loncommon.pm,v 1.1268 2017/01/01 16:32:01 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    74: use DateTime::TimeZone;
1.1241    raeburn    75: use DateTime::Locale;
1.1220    raeburn    76: use Encode();
1.1091    foxr       77: use Text::Aspell;
1.1094    raeburn    78: use Authen::Captcha;
                     79: use Captcha::reCAPTCHA;
1.1234    raeburn    80: use JSON::DWIW;
                     81: use LWP::UserAgent;
1.1174    raeburn    82: use Crypt::DES;
                     83: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   84: use MIME::Lite;
                     85: use MIME::Types;
1.117     www        86: 
1.517     raeburn    87: # ---------------------------------------------- Designs
                     88: use vars qw(%defaultdesign);
                     89: 
1.22      www        90: my $readit;
                     91: 
1.517     raeburn    92: 
1.157     matthew    93: ##
                     94: ## Global Variables
                     95: ##
1.46      matthew    96: 
1.643     foxr       97: 
                     98: # ----------------------------------------------- SSI with retries:
                     99: #
                    100: 
                    101: =pod
                    102: 
1.648     raeburn   103: =head1 Server Side include with retries:
1.643     foxr      104: 
                    105: =over 4
                    106: 
1.648     raeburn   107: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      108: 
                    109: Performs an ssi with some number of retries.  Retries continue either
                    110: until the result is ok or until the retry count supplied by the
                    111: caller is exhausted.  
                    112: 
                    113: Inputs:
1.648     raeburn   114: 
                    115: =over 4
                    116: 
1.643     foxr      117: resource   - Identifies the resource to insert.
1.648     raeburn   118: 
1.643     foxr      119: retries    - Count of the number of retries allowed.
1.648     raeburn   120: 
1.643     foxr      121: form       - Hash that identifies the rendering options.
                    122: 
1.648     raeburn   123: =back
                    124: 
                    125: Returns:
                    126: 
                    127: =over 4
                    128: 
1.643     foxr      129: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   130: 
1.643     foxr      131: response   - The response from the last attempt (which may or may not have been successful.
                    132: 
1.648     raeburn   133: =back
                    134: 
                    135: =back
                    136: 
1.643     foxr      137: =cut
                    138: 
                    139: sub ssi_with_retries {
                    140:     my ($resource, $retries, %form) = @_;
                    141: 
                    142: 
                    143:     my $ok = 0;			# True if we got a good response.
                    144:     my $content;
                    145:     my $response;
                    146: 
                    147:     # Try to get the ssi done. within the retries count:
                    148: 
                    149:     do {
                    150: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    151: 	$ok      = $response->is_success;
1.650     www       152:         if (!$ok) {
                    153:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    154:         }
1.643     foxr      155: 	$retries--;
                    156:     } while (!$ok && ($retries > 0));
                    157: 
                    158:     if (!$ok) {
                    159: 	$content = '';		# On error return an empty content.
                    160:     }
                    161:     return ($content, $response);
                    162: 
                    163: }
                    164: 
                    165: 
                    166: 
1.20      www       167: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  168: my %language;
1.124     www       169: my %supported_language;
1.1088    foxr      170: my %supported_codes;
1.1048    foxr      171: my %latex_language;		# For choosing hyphenation in <transl..>
                    172: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  173: my %cprtag;
1.192     taceyjo1  174: my %scprtag;
1.351     www       175: my %fe; my %fd; my %fm;
1.41      ng        176: my %category_extensions;
1.12      harris41  177: 
1.46      matthew   178: # ---------------------------------------------- Thesaurus variables
1.144     matthew   179: #
                    180: # %Keywords:
                    181: #      A hash used by &keyword to determine if a word is considered a keyword.
                    182: # $thesaurus_db_file 
                    183: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   184: 
                    185: my %Keywords;
                    186: my $thesaurus_db_file;
                    187: 
1.144     matthew   188: #
                    189: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    190: # thesaurus.tab, and filecategories.tab.
                    191: #
1.18      www       192: BEGIN {
1.46      matthew   193:     # Variable initialization
                    194:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    195:     #
1.22      www       196:     unless ($readit) {
1.12      harris41  197: # ------------------------------------------------------------------- languages
                    198:     {
1.158     raeburn   199:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    200:                                    '/language.tab';
                    201:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  202:             while (my $line = <$fh>) {
                    203:                 next if ($line=~/^\#/);
                    204:                 chomp($line);
1.1088    foxr      205:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   206:                 $language{$key}=$val.' - '.$enc;
                    207:                 if ($sup) {
                    208:                     $supported_language{$key}=$sup;
1.1088    foxr      209: 		    $supported_codes{$key}   = $code;
1.158     raeburn   210:                 }
1.1048    foxr      211: 		if ($latex) {
                    212: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      213: 		    $latex_language{$code} = $latex;
1.1048    foxr      214: 		}
1.158     raeburn   215:             }
                    216:             close($fh);
                    217:         }
1.12      harris41  218:     }
                    219: # ------------------------------------------------------------------ copyrights
                    220:     {
1.158     raeburn   221:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    222:                                   '/copyright.tab';
                    223:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  224:             while (my $line = <$fh>) {
                    225:                 next if ($line=~/^\#/);
                    226:                 chomp($line);
                    227:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   228:                 $cprtag{$key}=$val;
                    229:             }
                    230:             close($fh);
                    231:         }
1.12      harris41  232:     }
1.351     www       233: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  234:     {
                    235:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    236:                                   '/source_copyright.tab';
                    237:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  238:             while (my $line = <$fh>) {
                    239:                 next if ($line =~ /^\#/);
                    240:                 chomp($line);
                    241:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  242:                 $scprtag{$key}=$val;
                    243:             }
                    244:             close($fh);
                    245:         }
                    246:     }
1.63      www       247: 
1.517     raeburn   248: # -------------------------------------------------------------- default domain designs
1.63      www       249:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   250:     my $designfile = $designdir.'/default.tab';
                    251:     if ( open (my $fh,"<$designfile") ) {
                    252:         while (my $line = <$fh>) {
                    253:             next if ($line =~ /^\#/);
                    254:             chomp($line);
                    255:             my ($key,$val)=(split(/\=/,$line));
                    256:             if ($val) { $defaultdesign{$key}=$val; }
                    257:         }
                    258:         close($fh);
1.63      www       259:     }
                    260: 
1.15      harris41  261: # ------------------------------------------------------------- file categories
                    262:     {
1.158     raeburn   263:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    264:                                   '/filecategories.tab';
                    265:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  266: 	    while (my $line = <$fh>) {
                    267: 		next if ($line =~ /^\#/);
                    268: 		chomp($line);
                    269:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   270:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   271:             }
                    272:             close($fh);
                    273:         }
                    274: 
1.15      harris41  275:     }
1.12      harris41  276: # ------------------------------------------------------------------ file types
                    277:     {
1.158     raeburn   278:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    279:                '/filetypes.tab';
                    280:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  281:             while (my $line = <$fh>) {
                    282: 		next if ($line =~ /^\#/);
                    283: 		chomp($line);
                    284:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   285:                 if ($descr ne '') {
                    286:                     $fe{$ending}=lc($emb);
                    287:                     $fd{$ending}=$descr;
1.351     www       288:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   289:                 }
                    290:             }
                    291:             close($fh);
                    292:         }
1.12      harris41  293:     }
1.22      www       294:     &Apache::lonnet::logthis(
1.705     tempelho  295:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       296:     $readit=1;
1.46      matthew   297:     }  # end of unless($readit) 
1.32      matthew   298:     
                    299: }
1.112     bowersj2  300: 
1.42      matthew   301: ###############################################################
                    302: ##           HTML and Javascript Helper Functions            ##
                    303: ###############################################################
                    304: 
                    305: =pod 
                    306: 
1.112     bowersj2  307: =head1 HTML and Javascript Functions
1.42      matthew   308: 
1.112     bowersj2  309: =over 4
                    310: 
1.648     raeburn   311: =item * &browser_and_searcher_javascript()
1.112     bowersj2  312: 
                    313: X<browsing, javascript>X<searching, javascript>Returns a string
                    314: containing javascript with two functions, C<openbrowser> and
                    315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    316: tags.
1.42      matthew   317: 
1.648     raeburn   318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   319: 
                    320: inputs: formname, elementname, only, omit
                    321: 
                    322: formname and elementname indicate the name of the html form and name of
                    323: the element that the results of the browsing selection are to be placed in. 
                    324: 
                    325: Specifying 'only' will restrict the browser to displaying only files
1.185     www       326: with the given extension.  Can be a comma separated list.
1.42      matthew   327: 
                    328: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       329: with the given extension.  Can be a comma separated list.
1.42      matthew   330: 
1.648     raeburn   331: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   332: 
                    333: Inputs: formname, elementname
                    334: 
                    335: formname and elementname specify the name of the html form and the name
                    336: of the element the selection from the search results will be placed in.
1.542     raeburn   337: 
1.42      matthew   338: =cut
                    339: 
                    340: sub browser_and_searcher_javascript {
1.199     albertel  341:     my ($mode)=@_;
                    342:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  343:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   344:     return <<END;
1.219     albertel  345: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   346:     var editbrowser = null;
1.135     albertel  347:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       348:         var url = '$resurl/?';
1.42      matthew   349:         if (editbrowser == null) {
                    350:             url += 'launch=1&';
                    351:         }
                    352:         url += 'catalogmode=interactive&';
1.199     albertel  353:         url += 'mode=$mode&';
1.611     albertel  354:         url += 'inhibitmenu=yes&';
1.42      matthew   355:         url += 'form=' + formname + '&';
                    356:         if (only != null) {
                    357:             url += 'only=' + only + '&';
1.217     albertel  358:         } else {
                    359:             url += 'only=&';
                    360: 	}
1.42      matthew   361:         if (omit != null) {
                    362:             url += 'omit=' + omit + '&';
1.217     albertel  363:         } else {
                    364:             url += 'omit=&';
                    365: 	}
1.135     albertel  366:         if (titleelement != null) {
                    367:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  368:         } else {
                    369: 	    url += 'titleelement=&';
                    370: 	}
1.42      matthew   371:         url += 'element=' + elementname + '';
                    372:         var title = 'Browser';
1.435     albertel  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   374:         options += ',width=700,height=600';
                    375:         editbrowser = open(url,title,options,'1');
                    376:         editbrowser.focus();
                    377:     }
                    378:     var editsearcher;
1.135     albertel  379:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   380:         var url = '/adm/searchcat?';
                    381:         if (editsearcher == null) {
                    382:             url += 'launch=1&';
                    383:         }
                    384:         url += 'catalogmode=interactive&';
1.199     albertel  385:         url += 'mode=$mode&';
1.42      matthew   386:         url += 'form=' + formname + '&';
1.135     albertel  387:         if (titleelement != null) {
                    388:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  389:         } else {
                    390: 	    url += 'titleelement=&';
                    391: 	}
1.42      matthew   392:         url += 'element=' + elementname + '';
                    393:         var title = 'Search';
1.435     albertel  394:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   395:         options += ',width=700,height=600';
                    396:         editsearcher = open(url,title,options,'1');
                    397:         editsearcher.focus();
                    398:     }
1.219     albertel  399: // END LON-CAPA Internal -->
1.42      matthew   400: END
1.170     www       401: }
                    402: 
                    403: sub lastresurl {
1.258     albertel  404:     if ($env{'environment.lastresurl'}) {
                    405: 	return $env{'environment.lastresurl'}
1.170     www       406:     } else {
                    407: 	return '/res';
                    408:     }
                    409: }
                    410: 
                    411: sub storeresurl {
                    412:     my $resurl=&Apache::lonnet::clutter(shift);
                    413:     unless ($resurl=~/^\/res/) { return 0; }
                    414:     $resurl=~s/\/$//;
                    415:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   416:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       417:     return 1;
1.42      matthew   418: }
                    419: 
1.74      www       420: sub studentbrowser_javascript {
1.111     www       421:    unless (
1.258     albertel  422:             (($env{'request.course.id'}) && 
1.302     albertel  423:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    424: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    425: 					  '/'.$env{'request.course.sec'})
                    426: 	      ))
1.258     albertel  427:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       428:           ) { return ''; }  
1.74      www       429:    return (<<'ENDSTDBRW');
1.776     bisitz    430: <script type="text/javascript" language="Javascript">
1.824     bisitz    431: // <![CDATA[
1.74      www       432:     var stdeditbrowser;
1.999     www       433:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       434:         var url = '/adm/pickstudent?';
                    435:         var filter;
1.558     albertel  436: 	if (!ignorefilter) {
                    437: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    438: 	}
1.74      www       439:         if (filter != null) {
                    440:            if (filter != '') {
                    441:                url += 'filter='+filter+'&';
                    442: 	   }
                    443:         }
                    444:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       445:                                     '&udomelement='+udom+
                    446:                                     '&clicker='+clicker;
1.111     www       447: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   448:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       449:         var title = 'Student_Browser';
1.74      www       450:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    451:         options += ',width=700,height=600';
                    452:         stdeditbrowser = open(url,title,options,'1');
                    453:         stdeditbrowser.focus();
                    454:     }
1.824     bisitz    455: // ]]>
1.74      www       456: </script>
                    457: ENDSTDBRW
                    458: }
1.42      matthew   459: 
1.1003    www       460: sub resourcebrowser_javascript {
                    461:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       462:    return (<<'ENDRESBRW');
1.1003    www       463: <script type="text/javascript" language="Javascript">
                    464: // <![CDATA[
                    465:     var reseditbrowser;
1.1004    www       466:     function openresbrowser(formname,reslink) {
1.1005    www       467:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       468:         var title = 'Resource_Browser';
                    469:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       470:         options += ',width=700,height=500';
1.1004    www       471:         reseditbrowser = open(url,title,options,'1');
                    472:         reseditbrowser.focus();
1.1003    www       473:     }
                    474: // ]]>
                    475: </script>
1.1004    www       476: ENDRESBRW
1.1003    www       477: }
                    478: 
1.74      www       479: sub selectstudent_link {
1.999     www       480:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    481:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    482:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    483:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  484:    if ($env{'request.course.id'}) {  
1.302     albertel  485:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    486: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    487: 					'/'.$env{'request.course.sec'})) {
1.111     www       488: 	   return '';
                    489:        }
1.999     www       490:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   491:        if ($courseadvonly)  {
                    492:            $callargs .= ",'',1,1";
                    493:        }
                    494:        return '<span class="LC_nobreak">'.
                    495:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    496:               &mt('Select User').'</a></span>';
1.74      www       497:    }
1.258     albertel  498:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       499:        $callargs .= ",'',1"; 
1.793     raeburn   500:        return '<span class="LC_nobreak">'.
                    501:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    502:               &mt('Select User').'</a></span>';
1.111     www       503:    }
                    504:    return '';
1.91      www       505: }
                    506: 
1.1004    www       507: sub selectresource_link {
                    508:    my ($form,$reslink,$arg)=@_;
                    509:    
                    510:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    511:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    512:    unless ($env{'request.course.id'}) { return $arg; }
                    513:    return '<span class="LC_nobreak">'.
                    514:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    515:               $arg.'</a></span>';
                    516: }
                    517: 
                    518: 
                    519: 
1.653     raeburn   520: sub authorbrowser_javascript {
                    521:     return <<"ENDAUTHORBRW";
1.776     bisitz    522: <script type="text/javascript" language="JavaScript">
1.824     bisitz    523: // <![CDATA[
1.653     raeburn   524: var stdeditbrowser;
                    525: 
                    526: function openauthorbrowser(formname,udom) {
                    527:     var url = '/adm/pickauthor?';
                    528:     url += 'form='+formname+'&roledom='+udom;
                    529:     var title = 'Author_Browser';
                    530:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    531:     options += ',width=700,height=600';
                    532:     stdeditbrowser = open(url,title,options,'1');
                    533:     stdeditbrowser.focus();
                    534: }
                    535: 
1.824     bisitz    536: // ]]>
1.653     raeburn   537: </script>
                    538: ENDAUTHORBRW
                    539: }
                    540: 
1.91      www       541: sub coursebrowser_javascript {
1.1116    raeburn   542:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   543:         $credits_element,$instcode) = @_;
1.932     raeburn   544:     my $wintitle = 'Course_Browser';
1.931     raeburn   545:     if ($crstype eq 'Community') {
1.932     raeburn   546:         $wintitle = 'Community_Browser';
1.909     raeburn   547:     }
1.876     raeburn   548:     my $id_functions = &javascript_index_functions();
                    549:     my $output = '
1.776     bisitz    550: <script type="text/javascript" language="JavaScript">
1.824     bisitz    551: // <![CDATA[
1.468     raeburn   552:     var stdeditbrowser;'."\n";
1.876     raeburn   553: 
                    554:     $output .= <<"ENDSTDBRW";
1.909     raeburn   555:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       556:         var url = '/adm/pickcourse?';
1.895     raeburn   557:         var formid = getFormIdByName(formname);
1.876     raeburn   558:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  559:         if (domainfilter != null) {
                    560:            if (domainfilter != '') {
                    561:                url += 'domainfilter='+domainfilter+'&';
                    562: 	   }
                    563:         }
1.91      www       564:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  565: 	                            '&cdomelement='+udom+
                    566:                                     '&cnameelement='+desc;
1.468     raeburn   567:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   568:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   569:                 url += '&roleelement='+extra_element;
                    570:                 if (domainfilter == null || domainfilter == '') {
                    571:                     url += '&domainfilter='+extra_element;
                    572:                 }
1.234     raeburn   573:             }
1.468     raeburn   574:             else {
                    575:                 if (formname == 'portform') {
                    576:                     url += '&setroles='+extra_element;
1.800     raeburn   577:                 } else {
                    578:                     if (formname == 'rules') {
                    579:                         url += '&fixeddom='+extra_element; 
                    580:                     }
1.468     raeburn   581:                 }
                    582:             }     
1.230     raeburn   583:         }
1.909     raeburn   584:         if (type != null && type != '') {
                    585:             url += '&type='+type;
                    586:         }
                    587:         if (type_elem != null && type_elem != '') {
                    588:             url += '&typeelement='+type_elem;
                    589:         }
1.872     raeburn   590:         if (formname == 'ccrs') {
                    591:             var ownername = document.forms[formid].ccuname.value;
                    592:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   593:             url += '&cloner='+ownername+':'+ownerdom;
                    594:             if (type == 'Course') {
                    595:                 url += '&crscode='+document.forms[formid].crscode.value;
                    596:             }
1.1221    raeburn   597:         }
                    598:         if (formname == 'requestcrs') {
                    599:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   600:         }
1.293     raeburn   601:         if (multflag !=null && multflag != '') {
                    602:             url += '&multiple='+multflag;
                    603:         }
1.909     raeburn   604:         var title = '$wintitle';
1.91      www       605:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    606:         options += ',width=700,height=600';
                    607:         stdeditbrowser = open(url,title,options,'1');
                    608:         stdeditbrowser.focus();
                    609:     }
1.876     raeburn   610: $id_functions
                    611: ENDSTDBRW
1.1116    raeburn   612:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    613:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    614:                                       $credits_element);
1.876     raeburn   615:     }
                    616:     $output .= '
                    617: // ]]>
                    618: </script>';
                    619:     return $output;
                    620: }
                    621: 
                    622: sub javascript_index_functions {
                    623:     return <<"ENDJS";
                    624: 
                    625: function getFormIdByName(formname) {
                    626:     for (var i=0;i<document.forms.length;i++) {
                    627:         if (document.forms[i].name == formname) {
                    628:             return i;
                    629:         }
                    630:     }
                    631:     return -1;
                    632: }
                    633: 
                    634: function getIndexByName(formid,item) {
                    635:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    636:         if (document.forms[formid].elements[i].name == item) {
                    637:             return i;
                    638:         }
                    639:     }
                    640:     return -1;
                    641: }
1.468     raeburn   642: 
1.876     raeburn   643: function getDomainFromSelectbox(formname,udom) {
                    644:     var userdom;
                    645:     var formid = getFormIdByName(formname);
                    646:     if (formid > -1) {
                    647:         var domid = getIndexByName(formid,udom);
                    648:         if (domid > -1) {
                    649:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    650:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    651:             }
                    652:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    653:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   654:             }
                    655:         }
                    656:     }
1.876     raeburn   657:     return userdom;
                    658: }
                    659: 
                    660: ENDJS
1.468     raeburn   661: 
1.876     raeburn   662: }
                    663: 
1.1017    raeburn   664: sub javascript_array_indexof {
1.1018    raeburn   665:     return <<ENDJS;
1.1017    raeburn   666: <script type="text/javascript" language="JavaScript">
                    667: // <![CDATA[
                    668: 
                    669: if (!Array.prototype.indexOf) {
                    670:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    671:         "use strict";
                    672:         if (this === void 0 || this === null) {
                    673:             throw new TypeError();
                    674:         }
                    675:         var t = Object(this);
                    676:         var len = t.length >>> 0;
                    677:         if (len === 0) {
                    678:             return -1;
                    679:         }
                    680:         var n = 0;
                    681:         if (arguments.length > 0) {
                    682:             n = Number(arguments[1]);
1.1088    foxr      683:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   684:                 n = 0;
                    685:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    686:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    687:             }
                    688:         }
                    689:         if (n >= len) {
                    690:             return -1;
                    691:         }
                    692:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    693:         for (; k < len; k++) {
                    694:             if (k in t && t[k] === searchElement) {
                    695:                 return k;
                    696:             }
                    697:         }
                    698:         return -1;
                    699:     }
                    700: }
                    701: 
                    702: // ]]>
                    703: </script>
                    704: 
                    705: ENDJS
                    706: 
                    707: }
                    708: 
1.876     raeburn   709: sub userbrowser_javascript {
                    710:     my $id_functions = &javascript_index_functions();
                    711:     return <<"ENDUSERBRW";
                    712: 
1.888     raeburn   713: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   714:     var url = '/adm/pickuser?';
                    715:     var userdom = getDomainFromSelectbox(formname,udom);
                    716:     if (userdom != null) {
                    717:        if (userdom != '') {
                    718:            url += 'srchdom='+userdom+'&';
                    719:        }
                    720:     }
                    721:     url += 'form=' + formname + '&unameelement='+uname+
                    722:                                 '&udomelement='+udom+
                    723:                                 '&ulastelement='+ulast+
                    724:                                 '&ufirstelement='+ufirst+
                    725:                                 '&uemailelement='+uemail+
1.881     raeburn   726:                                 '&hideudomelement='+hideudom+
                    727:                                 '&coursedom='+crsdom;
1.888     raeburn   728:     if ((caller != null) && (caller != undefined)) {
                    729:         url += '&caller='+caller;
                    730:     }
1.876     raeburn   731:     var title = 'User_Browser';
                    732:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    733:     options += ',width=700,height=600';
                    734:     var stdeditbrowser = open(url,title,options,'1');
                    735:     stdeditbrowser.focus();
                    736: }
                    737: 
1.888     raeburn   738: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   739:     var formid = getFormIdByName(formname);
                    740:     if (formid > -1) {
1.888     raeburn   741:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   742:         var domid = getIndexByName(formid,udom);
                    743:         var hidedomid = getIndexByName(formid,origdom);
                    744:         if (hidedomid > -1) {
                    745:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   746:             var unameval = document.forms[formid].elements[unameid].value;
                    747:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    748:                 if (domid > -1) {
                    749:                     var slct = document.forms[formid].elements[domid];
                    750:                     if (slct.type == 'select-one') {
                    751:                         var i;
                    752:                         for (i=0;i<slct.length;i++) {
                    753:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    754:                         }
                    755:                     }
                    756:                     if (slct.type == 'hidden') {
                    757:                         slct.value = fixeddom;
1.876     raeburn   758:                     }
                    759:                 }
1.468     raeburn   760:             }
                    761:         }
                    762:     }
1.876     raeburn   763:     return;
                    764: }
                    765: 
                    766: $id_functions
                    767: ENDUSERBRW
1.468     raeburn   768: }
                    769: 
                    770: sub setsec_javascript {
1.1116    raeburn   771:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   772:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    773:         $communityrolestr);
                    774:     if ($role_element ne '') {
                    775:         my @allroles = ('st','ta','ep','in','ad');
                    776:         foreach my $crstype ('Course','Community') {
                    777:             if ($crstype eq 'Community') {
                    778:                 foreach my $role (@allroles) {
                    779:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    780:                 }
                    781:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    782:             } else {
                    783:                 foreach my $role (@allroles) {
                    784:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    785:                 }
                    786:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    787:             }
                    788:         }
                    789:         $rolestr = '"'.join('","',@allroles).'"';
                    790:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    791:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    792:     }
1.468     raeburn   793:     my $setsections = qq|
                    794: function setSect(sectionlist) {
1.629     raeburn   795:     var sectionsArray = new Array();
                    796:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    797:         sectionsArray = sectionlist.split(",");
                    798:     }
1.468     raeburn   799:     var numSections = sectionsArray.length;
                    800:     document.$formname.$sec_element.length = 0;
                    801:     if (numSections == 0) {
                    802:         document.$formname.$sec_element.multiple=false;
                    803:         document.$formname.$sec_element.size=1;
                    804:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    805:     } else {
                    806:         if (numSections == 1) {
                    807:             document.$formname.$sec_element.multiple=false;
                    808:             document.$formname.$sec_element.size=1;
                    809:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    810:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    811:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    812:         } else {
                    813:             for (var i=0; i<numSections; i++) {
                    814:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    815:             }
                    816:             document.$formname.$sec_element.multiple=true
                    817:             if (numSections < 3) {
                    818:                 document.$formname.$sec_element.size=numSections;
                    819:             } else {
                    820:                 document.$formname.$sec_element.size=3;
                    821:             }
                    822:             document.$formname.$sec_element.options[0].selected = false
                    823:         }
                    824:     }
1.91      www       825: }
1.905     raeburn   826: 
                    827: function setRole(crstype) {
1.468     raeburn   828: |;
1.905     raeburn   829:     if ($role_element eq '') {
                    830:         $setsections .= '    return;
                    831: }
                    832: ';
                    833:     } else {
                    834:         $setsections .= qq|
                    835:     var elementLength = document.$formname.$role_element.length;
                    836:     var allroles = Array($rolestr);
                    837:     var courserolenames = Array($courserolestr);
                    838:     var communityrolenames = Array($communityrolestr);
                    839:     if (elementLength != undefined) {
                    840:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    841:             if (crstype == 'Course') {
                    842:                 return;
                    843:             } else {
                    844:                 allroles[5] = 'co';
                    845:                 for (var i=0; i<6; i++) {
                    846:                     document.$formname.$role_element.options[i].value = allroles[i];
                    847:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    848:                 }
                    849:             }
                    850:         } else {
                    851:             if (crstype == 'Community') {
                    852:                 return;
                    853:             } else {
                    854:                 allroles[5] = 'cc';
                    855:                 for (var i=0; i<6; i++) {
                    856:                     document.$formname.$role_element.options[i].value = allroles[i];
                    857:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    858:                 }
                    859:             }
                    860:         }
                    861:     }
                    862:     return;
                    863: }
                    864: |;
                    865:     }
1.1116    raeburn   866:     if ($credits_element) {
                    867:         $setsections .= qq|
                    868: function setCredits(defaultcredits) {
                    869:     document.$formname.$credits_element.value = defaultcredits;
                    870:     return;
                    871: }
                    872: |;
                    873:     }
1.468     raeburn   874:     return $setsections;
                    875: }
                    876: 
1.91      www       877: sub selectcourse_link {
1.909     raeburn   878:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    879:        $typeelement) = @_;
                    880:    my $type = $selecttype;
1.871     raeburn   881:    my $linktext = &mt('Select Course');
                    882:    if ($selecttype eq 'Community') {
1.909     raeburn   883:        $linktext = &mt('Select Community');
1.1239    raeburn   884:    } elsif ($selecttype eq 'Placement') {
                    885:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   886:    } elsif ($selecttype eq 'Course/Community') {
                    887:        $linktext = &mt('Select Course/Community');
1.909     raeburn   888:        $type = '';
1.1019    raeburn   889:    } elsif ($selecttype eq 'Select') {
                    890:        $linktext = &mt('Select');
                    891:        $type = '';
1.871     raeburn   892:    }
1.787     bisitz    893:    return '<span class="LC_nobreak">'
                    894:          ."<a href='"
                    895:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    896:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   897:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   898:          ."'>".$linktext.'</a>'
1.787     bisitz    899:          .'</span>';
1.74      www       900: }
1.42      matthew   901: 
1.653     raeburn   902: sub selectauthor_link {
                    903:    my ($form,$udom)=@_;
                    904:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    905:           &mt('Select Author').'</a>';
                    906: }
                    907: 
1.876     raeburn   908: sub selectuser_link {
1.881     raeburn   909:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   910:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   911:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   912:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   913:            ');">'.$linktext.'</a>';
1.876     raeburn   914: }
                    915: 
1.273     raeburn   916: sub check_uncheck_jscript {
                    917:     my $jscript = <<"ENDSCRT";
                    918: function checkAll(field) {
                    919:     if (field.length > 0) {
                    920:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   921:             if (!field[i].disabled) { 
                    922:                 field[i].checked = true;
                    923:             }
1.273     raeburn   924:         }
                    925:     } else {
1.1093    raeburn   926:         if (!field.disabled) { 
                    927:             field.checked = true;
                    928:         }
1.273     raeburn   929:     }
                    930: }
                    931:  
                    932: function uncheckAll(field) {
                    933:     if (field.length > 0) {
                    934:         for (i = 0; i < field.length; i++) {
                    935:             field[i].checked = false ;
1.543     albertel  936:         }
                    937:     } else {
1.273     raeburn   938:         field.checked = false ;
                    939:     }
                    940: }
                    941: ENDSCRT
                    942:     return $jscript;
                    943: }
                    944: 
1.656     www       945: sub select_timezone {
1.1256    raeburn   946:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    947:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   948:    if ($includeempty) {
                    949:        $output .= '<option value=""';
                    950:        if (($selected eq '') || ($selected eq 'local')) {
                    951:            $output .= ' selected="selected" ';
                    952:        }
                    953:        $output .= '> </option>';
                    954:    }
1.657     raeburn   955:    my @timezones = DateTime::TimeZone->all_names;
                    956:    foreach my $tzone (@timezones) {
                    957:        $output.= '<option value="'.$tzone.'"';
                    958:        if ($tzone eq $selected) {
                    959:            $output.=' selected="selected"';
                    960:        }
                    961:        $output.=">$tzone</option>\n";
1.656     www       962:    }
                    963:    $output.="</select>";
                    964:    return $output;
                    965: }
1.273     raeburn   966: 
1.687     raeburn   967: sub select_datelocale {
1.1256    raeburn   968:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    969:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   970:     if ($includeempty) {
                    971:         $output .= '<option value=""';
                    972:         if ($selected eq '') {
                    973:             $output .= ' selected="selected" ';
                    974:         }
                    975:         $output .= '> </option>';
                    976:     }
1.1241    raeburn   977:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   978:     my (@possibles,%locale_names);
1.1241    raeburn   979:     my @locales = DateTime::Locale->ids();
                    980:     foreach my $id (@locales) {
                    981:         if ($id ne '') {
                    982:             my ($en_terr,$native_terr);
                    983:             my $loc = DateTime::Locale->load($id);
                    984:             if (ref($loc)) {
                    985:                 $en_terr = $loc->name();
                    986:                 $native_terr = $loc->native_name();
1.687     raeburn   987:                 if (grep(/^en$/,@languages) || !@languages) {
                    988:                     if ($en_terr ne '') {
                    989:                         $locale_names{$id} = '('.$en_terr.')';
                    990:                     } elsif ($native_terr ne '') {
                    991:                         $locale_names{$id} = $native_terr;
                    992:                     }
                    993:                 } else {
                    994:                     if ($native_terr ne '') {
                    995:                         $locale_names{$id} = $native_terr.' ';
                    996:                     } elsif ($en_terr ne '') {
                    997:                         $locale_names{$id} = '('.$en_terr.')';
                    998:                     }
                    999:                 }
1.1220    raeburn  1000:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1001:                 push(@possibles,$id);
                   1002:             } 
1.687     raeburn  1003:         }
                   1004:     }
                   1005:     foreach my $item (sort(@possibles)) {
                   1006:         $output.= '<option value="'.$item.'"';
                   1007:         if ($item eq $selected) {
                   1008:             $output.=' selected="selected"';
                   1009:         }
                   1010:         $output.=">$item";
                   1011:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1012:             $output.='  '.$locale_names{$item};
1.687     raeburn  1013:         }
                   1014:         $output.="</option>\n";
                   1015:     }
                   1016:     $output.="</select>";
                   1017:     return $output;
                   1018: }
                   1019: 
1.792     raeburn  1020: sub select_language {
1.1256    raeburn  1021:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1022:     my %langchoices;
                   1023:     if ($includeempty) {
1.1117    raeburn  1024:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1025:     }
                   1026:     foreach my $id (&languageids()) {
                   1027:         my $code = &supportedlanguagecode($id);
                   1028:         if ($code) {
                   1029:             $langchoices{$code} = &plainlanguagedescription($id);
                   1030:         }
                   1031:     }
1.1117    raeburn  1032:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1033:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1034: }
                   1035: 
1.42      matthew  1036: =pod
1.36      matthew  1037: 
1.1088    foxr     1038: 
                   1039: =item * &list_languages()
                   1040: 
                   1041: Returns an array reference that is suitable for use in language prompters.
                   1042: Each array element is itself a two element array.  The first element
                   1043: is the language code.  The second element a descsriptiuon of the 
                   1044: language itself.  This is suitable for use in e.g.
                   1045: &Apache::edit::select_arg (once dereferenced that is).
                   1046: 
                   1047: =cut 
                   1048: 
                   1049: sub list_languages {
                   1050:     my @lang_choices;
                   1051: 
                   1052:     foreach my $id (&languageids()) {
                   1053: 	my $code = &supportedlanguagecode($id);
                   1054: 	if ($code) {
                   1055: 	    my $selector    = $supported_codes{$id};
                   1056: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1057: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1058: 	}
                   1059:     }
                   1060:     return \@lang_choices;
                   1061: }
                   1062: 
                   1063: =pod
                   1064: 
1.648     raeburn  1065: =item * &linked_select_forms(...)
1.36      matthew  1066: 
                   1067: linked_select_forms returns a string containing a <script></script> block
                   1068: and html for two <select> menus.  The select menus will be linked in that
                   1069: changing the value of the first menu will result in new values being placed
                   1070: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1071: order unless a defined order is provided.
1.36      matthew  1072: 
                   1073: linked_select_forms takes the following ordered inputs:
                   1074: 
                   1075: =over 4
                   1076: 
1.112     bowersj2 1077: =item * $formname, the name of the <form> tag
1.36      matthew  1078: 
1.112     bowersj2 1079: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1080: 
1.112     bowersj2 1081: =item * $firstdefault, the default value for the first menu
1.36      matthew  1082: 
1.112     bowersj2 1083: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1084: 
1.112     bowersj2 1085: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1086: 
1.112     bowersj2 1087: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1088: 
1.609     raeburn  1089: =item * $menuorder, the order of values in the first menu
                   1090: 
1.1115    raeburn  1091: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1092:         event for the first <select> tag
                   1093: 
                   1094: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1095:         event for the second <select> tag
                   1096: 
1.1245    raeburn  1097: =item * $suffix, to differentiate separate uses of select2data javascript
                   1098:         objects in a page.
                   1099: 
1.41      ng       1100: =back 
                   1101: 
1.36      matthew  1102: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1103: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1104: values for the first select menu.  The text that coincides with the 
1.41      ng       1105: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1106: and text for the second menu are given in the hash pointed to by 
                   1107: $menu{$choice1}->{'select2'}.  
                   1108: 
1.112     bowersj2 1109:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1110:                        default => "B3",
                   1111:                        select2 => { 
                   1112:                            B1 => "Choice B1",
                   1113:                            B2 => "Choice B2",
                   1114:                            B3 => "Choice B3",
                   1115:                            B4 => "Choice B4"
1.609     raeburn  1116:                            },
                   1117:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1118:                    },
                   1119:                A2 => { text =>"Choice A2" ,
                   1120:                        default => "C2",
                   1121:                        select2 => { 
                   1122:                            C1 => "Choice C1",
                   1123:                            C2 => "Choice C2",
                   1124:                            C3 => "Choice C3"
1.609     raeburn  1125:                            },
                   1126:                        order => ['C2','C1','C3'],
1.112     bowersj2 1127:                    },
                   1128:                A3 => { text =>"Choice A3" ,
                   1129:                        default => "D6",
                   1130:                        select2 => { 
                   1131:                            D1 => "Choice D1",
                   1132:                            D2 => "Choice D2",
                   1133:                            D3 => "Choice D3",
                   1134:                            D4 => "Choice D4",
                   1135:                            D5 => "Choice D5",
                   1136:                            D6 => "Choice D6",
                   1137:                            D7 => "Choice D7"
1.609     raeburn  1138:                            },
                   1139:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1140:                    }
                   1141:                );
1.36      matthew  1142: 
                   1143: =cut
                   1144: 
                   1145: sub linked_select_forms {
                   1146:     my ($formname,
                   1147:         $middletext,
                   1148:         $firstdefault,
                   1149:         $firstselectname,
                   1150:         $secondselectname, 
1.609     raeburn  1151:         $hashref,
                   1152:         $menuorder,
1.1115    raeburn  1153:         $onchangefirst,
1.1245    raeburn  1154:         $onchangesecond,
                   1155:         $suffix
1.36      matthew  1156:         ) = @_;
                   1157:     my $second = "document.$formname.$secondselectname";
                   1158:     my $first = "document.$formname.$firstselectname";
                   1159:     # output the javascript to do the changing
                   1160:     my $result = '';
1.776     bisitz   1161:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1162:     $result.="// <![CDATA[\n";
1.1245    raeburn  1163:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1164:     $" = '","';
                   1165:     my $debug = '';
                   1166:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1167:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1168:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1169:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1170:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1171:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1172:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1173:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1174:         }
1.36      matthew  1175:         $result.="\"@s2values\");\n";
1.1245    raeburn  1176:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1177:         my @s2texts;
                   1178:         foreach my $value (@s2values) {
1.1263    raeburn  1179:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1180:         }
                   1181:         $result.="\"@s2texts\");\n";
                   1182:     }
                   1183:     $"=' ';
                   1184:     $result.= <<"END";
                   1185: 
1.1245    raeburn  1186: function select1${suffix}_changed() {
1.36      matthew  1187:     // Determine new choice
1.1245    raeburn  1188:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1189:     // update select2
1.1245    raeburn  1190:     var values     = select2data${suffix}[newvalue].values;
                   1191:     var texts      = select2data${suffix}[newvalue].texts;
                   1192:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1193:     var i;
                   1194:     // out with the old
1.1245    raeburn  1195:     $second.options.length = 0;
                   1196:     // in with the new
1.36      matthew  1197:     for (i=0;i<values.length; i++) {
                   1198:         $second.options[i] = new Option(values[i]);
1.143     matthew  1199:         $second.options[i].value = values[i];
1.36      matthew  1200:         $second.options[i].text = texts[i];
                   1201:         if (values[i] == select2def) {
                   1202:             $second.options[i].selected = true;
                   1203:         }
                   1204:     }
                   1205: }
1.824     bisitz   1206: // ]]>
1.36      matthew  1207: </script>
                   1208: END
                   1209:     # output the initial values for the selection lists
1.1245    raeburn  1210:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1211:     my @order = sort(keys(%{$hashref}));
                   1212:     if (ref($menuorder) eq 'ARRAY') {
                   1213:         @order = @{$menuorder};
                   1214:     }
                   1215:     foreach my $value (@order) {
1.36      matthew  1216:         $result.="    <option value=\"$value\" ";
1.253     albertel 1217:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1218:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1219:     }
                   1220:     $result .= "</select>\n";
                   1221:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1222:     $result .= $middletext;
1.1115    raeburn  1223:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1224:     if ($onchangesecond) {
                   1225:         $result .= ' onchange="'.$onchangesecond.'"';
                   1226:     }
                   1227:     $result .= ">\n";
1.36      matthew  1228:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1229:     
                   1230:     my @secondorder = sort(keys(%select2));
                   1231:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1232:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1233:     }
                   1234:     foreach my $value (@secondorder) {
1.36      matthew  1235:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1236:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1237:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1238:     }
                   1239:     $result .= "</select>\n";
                   1240:     #    return $debug;
                   1241:     return $result;
                   1242: }   #  end of sub linked_select_forms {
                   1243: 
1.45      matthew  1244: =pod
1.44      bowersj2 1245: 
1.973     raeburn  1246: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1247: 
1.112     bowersj2 1248: Returns a string corresponding to an HTML link to the given help
                   1249: $topic, where $topic corresponds to the name of a .tex file in
                   1250: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1251: spaces. 
                   1252: 
                   1253: $text will optionally be linked to the same topic, allowing you to
                   1254: link text in addition to the graphic. If you do not want to link
                   1255: text, but wish to specify one of the later parameters, pass an
                   1256: empty string. 
                   1257: 
                   1258: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1259: the link will not open a new window. If false, the link will open
                   1260: a new window using Javascript. (Default is false.) 
                   1261: 
                   1262: $width and $height are optional numerical parameters that will
                   1263: override the width and height of the popped up window, which may
1.973     raeburn  1264: be useful for certain help topics with big pictures included.
                   1265: 
                   1266: $imgid is the id of the img tag used for the help icon. This may be
                   1267: used in a javascript call to switch the image src.  See 
                   1268: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1269: 
                   1270: =cut
                   1271: 
                   1272: sub help_open_topic {
1.973     raeburn  1273:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1274:     $text = "" if (not defined $text);
1.44      bowersj2 1275:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1276:     $width = 500 if (not defined $width);
1.44      bowersj2 1277:     $height = 400 if (not defined $height);
                   1278:     my $filename = $topic;
                   1279:     $filename =~ s/ /_/g;
                   1280: 
1.48      bowersj2 1281:     my $template = "";
                   1282:     my $link;
1.572     banghart 1283:     
1.159     www      1284:     $topic=~s/\W/\_/g;
1.44      bowersj2 1285: 
1.572     banghart 1286:     if (!$stayOnPage) {
1.1033    www      1287: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1288:     } elsif ($stayOnPage eq 'popup') {
                   1289:         $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 1290:     } else {
1.48      bowersj2 1291: 	$link = "/adm/help/${filename}.hlp";
                   1292:     }
                   1293: 
                   1294:     # Add the text
1.755     neumanie 1295:     if ($text ne "") {	
1.763     bisitz   1296: 	$template.='<span class="LC_help_open_topic">'
                   1297:                   .'<a target="_top" href="'.$link.'">'
                   1298:                   .$text.'</a>';
1.48      bowersj2 1299:     }
                   1300: 
1.763     bisitz   1301:     # (Always) Add the graphic
1.179     matthew  1302:     my $title = &mt('Online Help');
1.667     raeburn  1303:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1304:     if ($imgid ne '') {
                   1305:         $imgid = ' id="'.$imgid.'"';
                   1306:     }
1.763     bisitz   1307:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1308:               .'<img src="'.$helpicon.'" border="0"'
                   1309:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1310:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1311:               .' /></a>';
                   1312:     if ($text ne "") {	
                   1313:         $template.='</span>';
                   1314:     }
1.44      bowersj2 1315:     return $template;
                   1316: 
1.106     bowersj2 1317: }
                   1318: 
                   1319: # This is a quicky function for Latex cheatsheet editing, since it 
                   1320: # appears in at least four places
                   1321: sub helpLatexCheatsheet {
1.1037    www      1322:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1323:     my $out;
1.106     bowersj2 1324:     my $addOther = '';
1.732     raeburn  1325:     if ($topic) {
1.1037    www      1326: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1327:     }
                   1328:     $out = '<span>' # Start cheatsheet
                   1329: 	  .$addOther
                   1330:           .'<span>'
1.1037    www      1331: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1332: 	  .'</span> <span>'
1.1037    www      1333: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1334: 	  .'</span>';
1.732     raeburn  1335:     unless ($not_author) {
1.1186    kruse    1336:         $out .= '<span>'
                   1337:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1338:                .'</span> <span>'
                   1339:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1340: 	       .'</span>';
1.732     raeburn  1341:     }
1.763     bisitz   1342:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1343:     return $out;
1.172     www      1344: }
                   1345: 
1.430     albertel 1346: sub general_help {
                   1347:     my $helptopic='Student_Intro';
                   1348:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1349: 	$helptopic='Authoring_Intro';
1.907     raeburn  1350:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1351: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1352:     } elsif ($env{'request.role'}=~/^dc/) {
                   1353:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1354:     }
                   1355:     return $helptopic;
                   1356: }
                   1357: 
                   1358: sub update_help_link {
                   1359:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1360:     my $origurl = $ENV{'REQUEST_URI'};
                   1361:     $origurl=~s|^/~|/priv/|;
                   1362:     my $timestamp = time;
                   1363:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1364:         $$datum = &escape($$datum);
                   1365:     }
                   1366: 
                   1367:     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";
                   1368:     my $output .= <<"ENDOUTPUT";
                   1369: <script type="text/javascript">
1.824     bisitz   1370: // <![CDATA[
1.430     albertel 1371: banner_link = '$banner_link';
1.824     bisitz   1372: // ]]>
1.430     albertel 1373: </script>
                   1374: ENDOUTPUT
                   1375:     return $output;
                   1376: }
                   1377: 
                   1378: # now just updates the help link and generates a blue icon
1.193     raeburn  1379: sub help_open_menu {
1.430     albertel 1380:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1381: 	= @_;    
1.949     droeschl 1382:     $stayOnPage = 1;
1.430     albertel 1383:     my $output;
                   1384:     if ($component_help) {
                   1385: 	if (!$text) {
                   1386: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1387: 				       $width,$height);
                   1388: 	} else {
                   1389: 	    my $help_text;
                   1390: 	    $help_text=&unescape($topic);
                   1391: 	    $output='<table><tr><td>'.
                   1392: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1393: 				 $width,$height).'</td></tr></table>';
                   1394: 	}
                   1395:     }
                   1396:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1397:     return $output.$banner_link;
                   1398: }
                   1399: 
                   1400: sub top_nav_help {
                   1401:     my ($text) = @_;
1.436     albertel 1402:     $text = &mt($text);
1.949     droeschl 1403:     my $stay_on_page = 1;
                   1404: 
1.1168    raeburn  1405:     my ($link,$banner_link);
                   1406:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1407:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1408: 	                         : "javascript:helpMenu('open')";
                   1409:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1410:     }
1.201     raeburn  1411:     my $title = &mt('Get help');
1.1168    raeburn  1412:     if ($link) {
                   1413:         return <<"END";
1.436     albertel 1414: $banner_link
1.1159    raeburn  1415: <a href="$link" title="$title">$text</a>
1.436     albertel 1416: END
1.1168    raeburn  1417:     } else {
                   1418:         return '&nbsp;'.$text.'&nbsp;';
                   1419:     }
1.436     albertel 1420: }
                   1421: 
                   1422: sub help_menu_js {
1.1154    raeburn  1423:     my ($httphost) = @_;
1.949     droeschl 1424:     my $stayOnPage = 1;
1.436     albertel 1425:     my $width = 620;
                   1426:     my $height = 600;
1.430     albertel 1427:     my $helptopic=&general_help();
1.1154    raeburn  1428:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1429:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1430:     my $start_page =
                   1431:         &Apache::loncommon::start_page('Help Menu', undef,
                   1432: 				       {'frameset'    => 1,
                   1433: 					'js_ready'    => 1,
1.1154    raeburn  1434:                                         'use_absolute' => $httphost,
1.331     albertel 1435: 					'add_entries' => {
1.1168    raeburn  1436: 					    'border' => '0', 
1.579     raeburn  1437: 					    'rows'   => "110,*",},});
1.331     albertel 1438:     my $end_page =
                   1439:         &Apache::loncommon::end_page({'frameset' => 1,
                   1440: 				      'js_ready' => 1,});
                   1441: 
1.436     albertel 1442:     my $template .= <<"ENDTEMPLATE";
                   1443: <script type="text/javascript">
1.877     bisitz   1444: // <![CDATA[
1.253     albertel 1445: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1446: var banner_link = '';
1.243     raeburn  1447: function helpMenu(target) {
                   1448:     var caller = this;
                   1449:     if (target == 'open') {
                   1450:         var newWindow = null;
                   1451:         try {
1.262     albertel 1452:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1453:         }
                   1454:         catch(error) {
                   1455:             writeHelp(caller);
                   1456:             return;
                   1457:         }
                   1458:         if (newWindow) {
                   1459:             caller = newWindow;
                   1460:         }
1.193     raeburn  1461:     }
1.243     raeburn  1462:     writeHelp(caller);
                   1463:     return;
                   1464: }
                   1465: function writeHelp(caller) {
1.1168    raeburn  1466:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1467:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1468:     caller.document.close();
                   1469:     caller.focus();
1.193     raeburn  1470: }
1.877     bisitz   1471: // END LON-CAPA Internal -->
1.253     albertel 1472: // ]]>
1.436     albertel 1473: </script>
1.193     raeburn  1474: ENDTEMPLATE
                   1475:     return $template;
                   1476: }
                   1477: 
1.172     www      1478: sub help_open_bug {
                   1479:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1480:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1481:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1482:     $text = "" if (not defined $text);
                   1483: 	$stayOnPage=1;
1.184     albertel 1484:     $width = 600 if (not defined $width);
                   1485:     $height = 600 if (not defined $height);
1.172     www      1486: 
                   1487:     $topic=~s/\W+/\+/g;
                   1488:     my $link='';
                   1489:     my $template='';
1.379     albertel 1490:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1491: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1492:     if (!$stayOnPage)
                   1493:     {
                   1494: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1495:     }
                   1496:     else
                   1497:     {
                   1498: 	$link = $url;
                   1499:     }
                   1500:     # Add the text
                   1501:     if ($text ne "")
                   1502:     {
                   1503: 	$template .= 
                   1504:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1505:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1506:     }
                   1507: 
                   1508:     # Add the graphic
1.179     matthew  1509:     my $title = &mt('Report a Bug');
1.215     albertel 1510:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1511:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1512:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1513: ENDTEMPLATE
                   1514:     if ($text ne '') { $template.='</td></tr></table>' };
                   1515:     return $template;
                   1516: 
                   1517: }
                   1518: 
                   1519: sub help_open_faq {
                   1520:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1521:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1522:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1523:     $text = "" if (not defined $text);
                   1524: 	$stayOnPage=1;
                   1525:     $width = 350 if (not defined $width);
                   1526:     $height = 400 if (not defined $height);
                   1527: 
                   1528:     $topic=~s/\W+/\+/g;
                   1529:     my $link='';
                   1530:     my $template='';
                   1531:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1532:     if (!$stayOnPage)
                   1533:     {
                   1534: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1535:     }
                   1536:     else
                   1537:     {
                   1538: 	$link = $url;
                   1539:     }
                   1540: 
                   1541:     # Add the text
                   1542:     if ($text ne "")
                   1543:     {
                   1544: 	$template .= 
1.173     www      1545:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1546:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1547:     }
                   1548: 
                   1549:     # Add the graphic
1.179     matthew  1550:     my $title = &mt('View the FAQ');
1.215     albertel 1551:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1552:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1553:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1554: ENDTEMPLATE
                   1555:     if ($text ne '') { $template.='</td></tr></table>' };
                   1556:     return $template;
                   1557: 
1.44      bowersj2 1558: }
1.37      matthew  1559: 
1.180     matthew  1560: ###############################################################
                   1561: ###############################################################
                   1562: 
1.45      matthew  1563: =pod
                   1564: 
1.648     raeburn  1565: =item * &change_content_javascript():
1.256     matthew  1566: 
                   1567: This and the next function allow you to create small sections of an
                   1568: otherwise static HTML page that you can update on the fly with
                   1569: Javascript, even in Netscape 4.
                   1570: 
                   1571: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1572: must be written to the HTML page once. It will prove the Javascript
                   1573: function "change(name, content)". Calling the change function with the
                   1574: name of the section 
                   1575: you want to update, matching the name passed to C<changable_area>, and
                   1576: the new content you want to put in there, will put the content into
                   1577: that area.
                   1578: 
                   1579: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1580: to contain room for the original contents. You need to "make space"
                   1581: for whatever changes you wish to make, and be B<sure> to check your
                   1582: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1583: it's adequate for updating a one-line status display, but little more.
                   1584: This script will set the space to 100% width, so you only need to
                   1585: worry about height in Netscape 4.
                   1586: 
                   1587: Modern browsers are much less limiting, and if you can commit to the
                   1588: user not using Netscape 4, this feature may be used freely with
                   1589: pretty much any HTML.
                   1590: 
                   1591: =cut
                   1592: 
                   1593: sub change_content_javascript {
                   1594:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1595:     if ($env{'browser.type'} eq 'netscape' &&
                   1596: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1597: 	return (<<NETSCAPE4);
                   1598: 	function change(name, content) {
                   1599: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1600: 	    doc.open();
                   1601: 	    doc.write(content);
                   1602: 	    doc.close();
                   1603: 	}
                   1604: NETSCAPE4
                   1605:     } else {
                   1606: 	# Otherwise, we need to use semi-standards-compliant code
                   1607: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1608: 	# is really scary, and every useful browser supports it
                   1609: 	return (<<DOMBASED);
                   1610: 	function change(name, content) {
                   1611: 	    element = document.getElementById(name);
                   1612: 	    element.innerHTML = content;
                   1613: 	}
                   1614: DOMBASED
                   1615:     }
                   1616: }
                   1617: 
                   1618: =pod
                   1619: 
1.648     raeburn  1620: =item * &changable_area($name,$origContent):
1.256     matthew  1621: 
                   1622: This provides a "changable area" that can be modified on the fly via
                   1623: the Javascript code provided in C<change_content_javascript>. $name is
                   1624: the name you will use to reference the area later; do not repeat the
                   1625: same name on a given HTML page more then once. $origContent is what
                   1626: the area will originally contain, which can be left blank.
                   1627: 
                   1628: =cut
                   1629: 
                   1630: sub changable_area {
                   1631:     my ($name, $origContent) = @_;
                   1632: 
1.258     albertel 1633:     if ($env{'browser.type'} eq 'netscape' &&
                   1634: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1635: 	# If this is netscape 4, we need to use the Layer tag
                   1636: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1637:     } else {
                   1638: 	return "<span id='$name'>$origContent</span>";
                   1639:     }
                   1640: }
                   1641: 
                   1642: =pod
                   1643: 
1.648     raeburn  1644: =item * &viewport_geometry_js 
1.590     raeburn  1645: 
                   1646: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1647: 
                   1648: =cut
                   1649: 
                   1650: 
                   1651: sub viewport_geometry_js { 
                   1652:     return <<"GEOMETRY";
                   1653: var Geometry = {};
                   1654: function init_geometry() {
                   1655:     if (Geometry.init) { return };
                   1656:     Geometry.init=1;
                   1657:     if (window.innerHeight) {
                   1658:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1659:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1660:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1661:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1662:     }
                   1663:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1664:         Geometry.getViewportHeight =
                   1665:             function() { return document.documentElement.clientHeight; };
                   1666:         Geometry.getViewportWidth =
                   1667:             function() { return document.documentElement.clientWidth; };
                   1668: 
                   1669:         Geometry.getHorizontalScroll =
                   1670:             function() { return document.documentElement.scrollLeft; };
                   1671:         Geometry.getVerticalScroll =
                   1672:             function() { return document.documentElement.scrollTop; };
                   1673:     }
                   1674:     else if (document.body.clientHeight) {
                   1675:         Geometry.getViewportHeight =
                   1676:             function() { return document.body.clientHeight; };
                   1677:         Geometry.getViewportWidth =
                   1678:             function() { return document.body.clientWidth; };
                   1679:         Geometry.getHorizontalScroll =
                   1680:             function() { return document.body.scrollLeft; };
                   1681:         Geometry.getVerticalScroll =
                   1682:             function() { return document.body.scrollTop; };
                   1683:     }
                   1684: }
                   1685: 
                   1686: GEOMETRY
                   1687: }
                   1688: 
                   1689: =pod
                   1690: 
1.648     raeburn  1691: =item * &viewport_size_js()
1.590     raeburn  1692: 
                   1693: 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. 
                   1694: 
                   1695: =cut
                   1696: 
                   1697: sub viewport_size_js {
                   1698:     my $geometry = &viewport_geometry_js();
                   1699:     return <<"DIMS";
                   1700: 
                   1701: $geometry
                   1702: 
                   1703: function getViewportDims(width,height) {
                   1704:     init_geometry();
                   1705:     width.value = Geometry.getViewportWidth();
                   1706:     height.value = Geometry.getViewportHeight();
                   1707:     return;
                   1708: }
                   1709: 
                   1710: DIMS
                   1711: }
                   1712: 
                   1713: =pod
                   1714: 
1.648     raeburn  1715: =item * &resize_textarea_js()
1.565     albertel 1716: 
                   1717: emits the needed javascript to resize a textarea to be as big as possible
                   1718: 
                   1719: creates a function resize_textrea that takes two IDs first should be
                   1720: the id of the element to resize, second should be the id of a div that
                   1721: surrounds everything that comes after the textarea, this routine needs
                   1722: to be attached to the <body> for the onload and onresize events.
                   1723: 
1.648     raeburn  1724: =back
1.565     albertel 1725: 
                   1726: =cut
                   1727: 
                   1728: sub resize_textarea_js {
1.590     raeburn  1729:     my $geometry = &viewport_geometry_js();
1.565     albertel 1730:     return <<"RESIZE";
                   1731:     <script type="text/javascript">
1.824     bisitz   1732: // <![CDATA[
1.590     raeburn  1733: $geometry
1.565     albertel 1734: 
1.588     albertel 1735: function getX(element) {
                   1736:     var x = 0;
                   1737:     while (element) {
                   1738: 	x += element.offsetLeft;
                   1739: 	element = element.offsetParent;
                   1740:     }
                   1741:     return x;
                   1742: }
                   1743: function getY(element) {
                   1744:     var y = 0;
                   1745:     while (element) {
                   1746: 	y += element.offsetTop;
                   1747: 	element = element.offsetParent;
                   1748:     }
                   1749:     return y;
                   1750: }
                   1751: 
                   1752: 
1.565     albertel 1753: function resize_textarea(textarea_id,bottom_id) {
                   1754:     init_geometry();
                   1755:     var textarea        = document.getElementById(textarea_id);
                   1756:     //alert(textarea);
                   1757: 
1.588     albertel 1758:     var textarea_top    = getY(textarea);
1.565     albertel 1759:     var textarea_height = textarea.offsetHeight;
                   1760:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1761:     var bottom_top      = getY(bottom);
1.565     albertel 1762:     var bottom_height   = bottom.offsetHeight;
                   1763:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1764:     var fudge           = 23;
1.565     albertel 1765:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1766:     if (new_height < 300) {
                   1767: 	new_height = 300;
                   1768:     }
                   1769:     textarea.style.height=new_height+'px';
                   1770: }
1.824     bisitz   1771: // ]]>
1.565     albertel 1772: </script>
                   1773: RESIZE
                   1774: 
                   1775: }
                   1776: 
1.1205    golterma 1777: sub colorfuleditor_js {
1.1248    raeburn  1778:     my $browse_or_search;
                   1779:     my $respath;
                   1780:     my ($cnum,$cdom) = &crsauthor_url();
                   1781:     if ($cnum) {
                   1782:         $respath = "/res/$cdom/$cnum/";
                   1783:         my %js_lt = &Apache::lonlocal::texthash(
                   1784:             sunm => 'Sub-directory name',
                   1785:             save => 'Save page to make this permanent',
                   1786:         );
                   1787:         &js_escape(\%js_lt);
                   1788:         $browse_or_search = <<"END";
                   1789: 
                   1790:     function toggleChooser(form,element,titleid,only,search) {
                   1791:         var disp = 'none';
                   1792:         if (document.getElementById('chooser_'+element)) {
                   1793:             var curr = document.getElementById('chooser_'+element).style.display;
                   1794:             if (curr == 'none') {
                   1795:                 disp='inline';
                   1796:                 if (form.elements['chooser_'+element].length) {
                   1797:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1798:                         form.elements['chooser_'+element][i].checked = false;
                   1799:                     }
                   1800:                 }
                   1801:                 toggleResImport(form,element);
                   1802:             }
                   1803:             document.getElementById('chooser_'+element).style.display = disp;
                   1804:         }
                   1805:     }
                   1806: 
                   1807:     function toggleCrsFile(form,element,numdirs) {
                   1808:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1809:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1810:             if (curr == 'none') {
                   1811:                 if (numdirs) {
                   1812:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1813:                     if (numdirs > 1) {
                   1814:                         window['select1'+element+'_changed']();
                   1815:                     }
                   1816:                 }
                   1817:             } 
                   1818:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1819:             
                   1820:         }
                   1821:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1822:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1823:             if (document.getElementById('uploadcrsres_'+element)) {
                   1824:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1825:             }
                   1826:         }
                   1827:         return;
                   1828:     }
                   1829: 
                   1830:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1831:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1832:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1833:         }
                   1834:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1835:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1836:             if (curr == 'none') {
                   1837:                 if (numcrsdirs) {
                   1838:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1839:                    form.elements['newsubdir_'+element][0].checked = true;
                   1840:                    toggleNewsubdir(form,element);
                   1841:                 }
                   1842:             }
                   1843:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1844:         }
                   1845:         return;
                   1846:     }
                   1847: 
                   1848:     function toggleResImport(form,element) {
                   1849:         var choices = new Array('crsres','upload');
                   1850:         for (var i=0; i<choices.length; i++) {
                   1851:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1852:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1853:             }
                   1854:         }
                   1855:     }
                   1856: 
                   1857:     function toggleNewsubdir(form,element) {
                   1858:         var newsub = form.elements['newsubdir_'+element];
                   1859:         if (newsub) {
                   1860:             if (newsub.length) {
                   1861:                 for (var j=0; j<newsub.length; j++) {
                   1862:                     if (newsub[j].checked) {
                   1863:                         if (document.getElementById('newsubdirname_'+element)) {
                   1864:                             if (newsub[j].value == '1') {
                   1865:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1866:                                 if (document.getElementById('newsubdir_'+element)) {
                   1867:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1868:                                 }
                   1869:                             } else {
                   1870:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1871:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1872:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1873:                             }
                   1874:                         }
                   1875:                         break; 
                   1876:                     }
                   1877:                 }
                   1878:             }
                   1879:         }
                   1880:     }
                   1881: 
                   1882:     function updateCrsFile(form,element) {
                   1883:         var directory = form.elements['coursepath_'+element];
                   1884:         var filename = form.elements['coursefile_'+element];
                   1885:         var path = directory.options[directory.selectedIndex].value;
                   1886:         var file = filename.options[filename.selectedIndex].value;
                   1887:         form.elements[element].value = '$respath';
                   1888:         if (path == '/') {
                   1889:             form.elements[element].value += file;
                   1890:         } else {
                   1891:             form.elements[element].value += path+'/'+file;
                   1892:         }
                   1893:         unClean();
                   1894:         if (document.getElementById('previewimg_'+element)) {
                   1895:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1896:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1897:         }
                   1898:         if (document.getElementById('showimg_'+element)) {
                   1899:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1900:         }
                   1901:         toggleChooser(form,element);
                   1902:         return;
                   1903:     }
                   1904: 
                   1905:     function uploadDone(suffix,name) {
                   1906:         if (name) {
                   1907: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1908:             unClean();
                   1909:             toggleChooser(document.forms["lonhomework"],suffix);
                   1910:         }
                   1911:     }
                   1912: 
                   1913: \$(document).ready(function(){
                   1914: 
                   1915:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1916:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1917:             var buttonId = this.id;
                   1918:             var suffix = buttonId.toString();
                   1919:             suffix = suffix.replace(/^crsupload_/,'');
                   1920:             event.preventDefault();
                   1921:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1922:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1923:             \$(this.form).submit();
                   1924:             document.lonhomework.target = '';
                   1925:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1926:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1927:             }
                   1928:             return false;
                   1929:         }
                   1930:     });
                   1931: });
                   1932: END
                   1933:     }
1.1205    golterma 1934:     return <<"COLORFULEDIT"
                   1935: <script type="text/javascript">
                   1936: // <![CDATA[>
                   1937:     function fold_box(curDepth, lastresource){
                   1938: 
                   1939:     // we need a list because there can be several blocks you need to fold in one tag
                   1940:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1941:     // but there is only one folding button per tag
                   1942:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1943: 
                   1944:         if(block.item(0).style.display == 'none'){
                   1945: 
                   1946:             foldbutton.value = '@{[&mt("Hide")]}';
                   1947:             for (i = 0; i < block.length; i++){
                   1948:                 block.item(i).style.display = '';
                   1949:             }
                   1950:         }else{
                   1951: 
                   1952:             foldbutton.value = '@{[&mt("Show")]}';
                   1953:             for (i = 0; i < block.length; i++){
                   1954:                 // block.item(i).style.visibility = 'collapse';
                   1955:                 block.item(i).style.display = 'none';
                   1956:             }
                   1957:         };
                   1958:         saveState(lastresource);
                   1959:     }
                   1960: 
                   1961:     function saveState (lastresource) {
                   1962: 
                   1963:         var tag_list = getTagList();
                   1964:         if(tag_list != null){
                   1965:             var timestamp = new Date().getTime();
                   1966:             var key = lastresource;
                   1967: 
                   1968:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1969:             // starting with timestamp
                   1970:             var value = timestamp+';';
                   1971: 
                   1972:             // building the list of key-value pairs
                   1973:             for(var i = 0; i < tag_list.length; i++){
                   1974:                 value += tag_list[i]+',';
                   1975:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1976:             }
                   1977: 
                   1978:             // only iterate whole storage if nothing to override
                   1979:             if(localStorage.getItem(key) == null){        
                   1980: 
                   1981:                 // prevent storage from growing large
                   1982:                 if(localStorage.length > 50){
                   1983:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1984:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1985:                     var oldest_key;
                   1986:                     
                   1987:                     for(var i = 1; i < localStorage.length; i++){
                   1988:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1989:                             oldest_key = localStorage.key(i);
                   1990:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1991:                         }
                   1992:                     }
                   1993:                     localStorage.removeItem(oldest_key);
                   1994:                 }
                   1995:             }
                   1996:             localStorage.setItem(key,value);
                   1997:         }
                   1998:     }
                   1999: 
                   2000:     // restore folding status of blocks (on page load)
                   2001:     function restoreState (lastresource) {
                   2002:         if(localStorage.getItem(lastresource) != null){
                   2003:             var key = lastresource;
                   2004:             var value = localStorage.getItem(key);
                   2005:             var regex_delTimestamp = /^\d+;/;
                   2006: 
                   2007:             value.replace(regex_delTimestamp, '');
                   2008: 
                   2009:             var valueArr = value.split(';');
                   2010:             var pairs;
                   2011:             var elements;
                   2012:             for (var i = 0; i < valueArr.length; i++){
                   2013:                 pairs = valueArr[i].split(',');
                   2014:                 elements = document.getElementsByName(pairs[0]);
                   2015: 
                   2016:                 for (var j = 0; j < elements.length; j++){  
                   2017:                     elements[j].style.display = pairs[1];
                   2018:                     if (pairs[1] == "none"){
                   2019:                         var regex_id = /([_\\d]+)\$/;
                   2020:                         regex_id.exec(pairs[0]);
                   2021:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2022:                     }
                   2023:                 }
                   2024:             }
                   2025:         }
                   2026:     }
                   2027: 
                   2028:     function getTagList () {
                   2029:         
                   2030:         var stringToSearch = document.lonhomework.innerHTML;
                   2031: 
                   2032:         var ret = new Array();
                   2033:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2034:         var tag_list = stringToSearch.match(regex_findBlock);
                   2035: 
                   2036:         if(tag_list != null){
                   2037:             for(var i = 0; i < tag_list.length; i++){            
                   2038:                 ret.push(tag_list[i].replace(/"/, ''));
                   2039:             }
                   2040:         }
                   2041:         return ret;
                   2042:     }
                   2043: 
                   2044:     function saveScrollPosition (resource) {
                   2045:         var tag_list = getTagList();
                   2046: 
                   2047:         // we dont always want to jump to the first block
                   2048:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2049:         if(\$(window).scrollTop() > 170){
                   2050:             if(tag_list != null){
                   2051:                 var result;
                   2052:                 for(var i = 0; i < tag_list.length; i++){
                   2053:                     if(isElementInViewport(tag_list[i])){
                   2054:                         result += tag_list[i]+';';
                   2055:                     }
                   2056:                 }
                   2057:                 sessionStorage.setItem('anchor_'+resource, result);
                   2058:             }
                   2059:         } else {
                   2060:             // we dont need to save zero, just delete the item to leave everything tidy
                   2061:             sessionStorage.removeItem('anchor_'+resource);
                   2062:         }
                   2063:     }
                   2064: 
                   2065:     function restoreScrollPosition(resource){
                   2066: 
                   2067:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2068:         if(elem != null){
                   2069:             var tag_list = elem.split(';');
                   2070:             var elem_list;
                   2071: 
                   2072:             for(var i = 0; i < tag_list.length; i++){
                   2073:                 elem_list = document.getElementsByName(tag_list[i]);
                   2074:                 
                   2075:                 if(elem_list.length > 0){
                   2076:                     elem = elem_list[0];
                   2077:                     break;
                   2078:                 }
                   2079:             }
                   2080:             elem.scrollIntoView();
                   2081:         }
                   2082:     }
                   2083: 
                   2084:     function isElementInViewport(el) {
                   2085: 
                   2086:         // change to last element instead of first
                   2087:         var elem = document.getElementsByName(el);
                   2088:         var rect = elem[0].getBoundingClientRect();
                   2089: 
                   2090:         return (
                   2091:             rect.top >= 0 &&
                   2092:             rect.left >= 0 &&
                   2093:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2094:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2095:         );
                   2096:     }
                   2097:     
                   2098:     function autosize(depth){
                   2099:         var cmInst = window['cm'+depth];
                   2100:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2101: 
                   2102:         // is fixed size, switching to dynamic
                   2103:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2104:             cmInst.setSize("","auto");
                   2105:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2106:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2107: 
                   2108:         // is dynamic size, switching to fixed
                   2109:         } else {
                   2110:             cmInst.setSize("","300px");
                   2111:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2112:             sessionStorage.removeItem("autosized_"+depth);
                   2113:         }
                   2114:     }
                   2115: 
1.1248    raeburn  2116: $browse_or_search
1.1205    golterma 2117: 
                   2118: // ]]>
                   2119: </script>
                   2120: COLORFULEDIT
                   2121: }
                   2122: 
                   2123: sub xmleditor_js {
                   2124:     return <<XMLEDIT
                   2125: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2126: <script type="text/javascript">
                   2127: // <![CDATA[>
                   2128: 
                   2129:     function saveScrollPosition (resource) {
                   2130: 
                   2131:         var scrollPos = \$(window).scrollTop();
                   2132:         sessionStorage.setItem(resource,scrollPos);
                   2133:     }
                   2134: 
                   2135:     function restoreScrollPosition(resource){
                   2136: 
                   2137:         var scrollPos = sessionStorage.getItem(resource);
                   2138:         \$(window).scrollTop(scrollPos);
                   2139:     }
                   2140: 
                   2141:     // unless internet explorer
                   2142:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2143: 
                   2144:         \$(document).ready(function() {
                   2145:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2146:         });
                   2147:     }
                   2148: 
                   2149:     // inserts text at cursor position into codemirror (xml editor only)
                   2150:     function insertText(text){
                   2151:         cm.focus();
                   2152:         var curPos = cm.getCursor();
                   2153:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2154:     }
                   2155: // ]]>
                   2156: </script>
                   2157: XMLEDIT
                   2158: }
                   2159: 
                   2160: sub insert_folding_button {
                   2161:     my $curDepth = $Apache::lonxml::curdepth;
                   2162:     my $lastresource = $env{'request.ambiguous'};
                   2163: 
                   2164:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2165:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2166: }
                   2167: 
1.1248    raeburn  2168: sub crsauthor_url {
                   2169:     my ($url) = @_;
                   2170:     if ($url eq '') {
                   2171:         $url = $ENV{'REQUEST_URI'};
                   2172:     }
                   2173:     my ($cnum,$cdom);
                   2174:     if ($env{'request.course.id'}) {
                   2175:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2176:         if ($audom ne '' && $auname ne '') {
                   2177:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2178:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2179:                 $cnum = $auname;
                   2180:                 $cdom = $audom;
                   2181:             }
                   2182:         }
                   2183:     }
                   2184:     return ($cnum,$cdom);
                   2185: }
                   2186: 
                   2187: sub import_crsauthor_form {
1.1265    raeburn  2188:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2189:     return (0) unless ($env{'request.course.id'});
                   2190:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2191:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2192:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2193:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2194:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2195:     my @ids=&Apache::lonnet::current_machine_ids();
                   2196:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2197:     
                   2198:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2199:         $is_home = 1;
                   2200:     }
                   2201:     $relpath = "/priv/$cdom/$cnum";
                   2202:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2203:     my %lt = &Apache::lonlocal::texthash (
                   2204:         fnam => 'Filename',
                   2205:         dire => 'Directory',
                   2206:     );
                   2207:     my $numdirs = scalar(keys(%files));
                   2208:     my (%possexts,$singledir,@singledirfiles);
                   2209:     if ($only) {
                   2210:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2211:     }
                   2212:     my (%nonemptydirs,$possdirs);
                   2213:     if ($numdirs > 1) {
                   2214:         my @order;
                   2215:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2216:             if (ref($files{$key}) eq 'HASH') {
                   2217:                 my $shown = $key;
                   2218:                 if ($key eq '') {
                   2219:                     $shown = '/';
                   2220:                 }
                   2221:                 my @ordered = ();
                   2222:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
                   2223:                     if ($only) {
                   2224:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2225:                         unless ($possexts{lc($ext)}) {
                   2226:                             next;
                   2227:                         }
                   2228:                     }
                   2229:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2230:                     push(@ordered,$file);
                   2231:                 }
                   2232:                 if (@ordered) {
                   2233:                     push(@order,$key);
                   2234:                     $nonemptydirs{$key} = 1;
                   2235:                     $selimport_menus{$key}->{'text'} = $shown;
                   2236:                     $selimport_menus{$key}->{'default'} = '';
                   2237:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2238:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2239:                 }
                   2240:             }
                   2241:         }
                   2242:         $possdirs = scalar(keys(%nonemptydirs));
                   2243:         if ($possdirs > 1) {
                   2244:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2245:             $output = $lt{'dire'}.
                   2246:                       &linked_select_forms($form,'<br />'.
                   2247:                                            $lt{'fnam'},'',
                   2248:                                            $firstselectname,$secondselectname,
                   2249:                                            \%selimport_menus,\@order,
                   2250:                                            $onchangefirst,'',$suffix).'<br />';
                   2251:         } elsif ($possdirs == 1) {
                   2252:             $singledir = (keys(%nonemptydirs))[0];
                   2253:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2254:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2255:             }
                   2256:             delete($selimport_menus{$singledir});
                   2257:         }
                   2258:     } elsif ($numdirs == 1) {
                   2259:         $singledir = (keys(%files))[0];
                   2260:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2261:             if ($only) {
                   2262:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2263:                 unless ($possexts{lc($ext)}) {
                   2264:                     next;
                   2265:                 }
                   2266:             }
                   2267:             push(@singledirfiles,$file);
                   2268:         }
                   2269:         if (@singledirfiles) {
                   2270:             $possdirs == 1;
                   2271:         }
                   2272:     }
                   2273:     if (($possdirs == 1) && (@singledirfiles)) {
                   2274:         my $showdir = $singledir;
                   2275:         if ($singledir eq '') {
                   2276:             $showdir = '/';
                   2277:         }
                   2278:         $output = $lt{'dire'}.
                   2279:                   '<select name="'.$firstselectname.'">'.
                   2280:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2281:                   '</select><br />'.
                   2282:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2283:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2284:         foreach my $file (@singledirfiles) {
                   2285:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2286:         }
                   2287:         $output .= '</select><br />'."\n";
                   2288:     }
                   2289:     return ($possdirs,$output);
                   2290: }
                   2291: 
1.565     albertel 2292: =pod
                   2293: 
1.256     matthew  2294: =head1 Excel and CSV file utility routines
                   2295: 
                   2296: =cut
                   2297: 
                   2298: ###############################################################
                   2299: ###############################################################
                   2300: 
                   2301: =pod
                   2302: 
1.1162    raeburn  2303: =over 4
                   2304: 
1.648     raeburn  2305: =item * &csv_translate($text) 
1.37      matthew  2306: 
1.185     www      2307: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2308: format.
                   2309: 
                   2310: =cut
                   2311: 
1.180     matthew  2312: ###############################################################
                   2313: ###############################################################
1.37      matthew  2314: sub csv_translate {
                   2315:     my $text = shift;
                   2316:     $text =~ s/\"/\"\"/g;
1.209     albertel 2317:     $text =~ s/\n/ /g;
1.37      matthew  2318:     return $text;
                   2319: }
1.180     matthew  2320: 
                   2321: ###############################################################
                   2322: ###############################################################
                   2323: 
                   2324: =pod
                   2325: 
1.648     raeburn  2326: =item * &define_excel_formats()
1.180     matthew  2327: 
                   2328: Define some commonly used Excel cell formats.
                   2329: 
                   2330: Currently supported formats:
                   2331: 
                   2332: =over 4
                   2333: 
                   2334: =item header
                   2335: 
                   2336: =item bold
                   2337: 
                   2338: =item h1
                   2339: 
                   2340: =item h2
                   2341: 
                   2342: =item h3
                   2343: 
1.256     matthew  2344: =item h4
                   2345: 
                   2346: =item i
                   2347: 
1.180     matthew  2348: =item date
                   2349: 
                   2350: =back
                   2351: 
                   2352: Inputs: $workbook
                   2353: 
                   2354: Returns: $format, a hash reference.
                   2355: 
1.1057    foxr     2356: 
1.180     matthew  2357: =cut
                   2358: 
                   2359: ###############################################################
                   2360: ###############################################################
                   2361: sub define_excel_formats {
                   2362:     my ($workbook) = @_;
                   2363:     my $format;
                   2364:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2365:                                                 bottom    => 1,
                   2366:                                                 align     => 'center');
                   2367:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2368:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2369:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2370:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2371:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2372:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2373:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2374:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2375:     return $format;
                   2376: }
                   2377: 
                   2378: ###############################################################
                   2379: ###############################################################
1.113     bowersj2 2380: 
                   2381: =pod
                   2382: 
1.648     raeburn  2383: =item * &create_workbook()
1.255     matthew  2384: 
                   2385: Create an Excel worksheet.  If it fails, output message on the
                   2386: request object and return undefs.
                   2387: 
                   2388: Inputs: Apache request object
                   2389: 
                   2390: Returns (undef) on failure, 
                   2391:     Excel worksheet object, scalar with filename, and formats 
                   2392:     from &Apache::loncommon::define_excel_formats on success
                   2393: 
                   2394: =cut
                   2395: 
                   2396: ###############################################################
                   2397: ###############################################################
                   2398: sub create_workbook {
                   2399:     my ($r) = @_;
                   2400:         #
                   2401:     # Create the excel spreadsheet
                   2402:     my $filename = '/prtspool/'.
1.258     albertel 2403:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2404:         time.'_'.rand(1000000000).'.xls';
                   2405:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2406:     if (! defined($workbook)) {
                   2407:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2408:         $r->print(
                   2409:             '<p class="LC_error">'
                   2410:            .&mt('Problems occurred in creating the new Excel file.')
                   2411:            .' '.&mt('This error has been logged.')
                   2412:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2413:            .'</p>'
                   2414:         );
1.255     matthew  2415:         return (undef);
                   2416:     }
                   2417:     #
1.1014    foxr     2418:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2419:     #
                   2420:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2421:     return ($workbook,$filename,$format);
                   2422: }
                   2423: 
                   2424: ###############################################################
                   2425: ###############################################################
                   2426: 
                   2427: =pod
                   2428: 
1.648     raeburn  2429: =item * &create_text_file()
1.113     bowersj2 2430: 
1.542     raeburn  2431: Create a file to write to and eventually make available to the user.
1.256     matthew  2432: If file creation fails, outputs an error message on the request object and 
                   2433: return undefs.
1.113     bowersj2 2434: 
1.256     matthew  2435: Inputs: Apache request object, and file suffix
1.113     bowersj2 2436: 
1.256     matthew  2437: Returns (undef) on failure, 
                   2438:     Filehandle and filename on success.
1.113     bowersj2 2439: 
                   2440: =cut
                   2441: 
1.256     matthew  2442: ###############################################################
                   2443: ###############################################################
                   2444: sub create_text_file {
                   2445:     my ($r,$suffix) = @_;
                   2446:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2447:     my $fh;
                   2448:     my $filename = '/prtspool/'.
1.258     albertel 2449:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2450:         time.'_'.rand(1000000000).'.'.$suffix;
                   2451:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2452:     if (! defined($fh)) {
                   2453:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2454:         $r->print(
                   2455:             '<p class="LC_error">'
                   2456:            .&mt('Problems occurred in creating the output file.')
                   2457:            .' '.&mt('This error has been logged.')
                   2458:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2459:            .'</p>'
                   2460:         );
1.113     bowersj2 2461:     }
1.256     matthew  2462:     return ($fh,$filename)
1.113     bowersj2 2463: }
                   2464: 
                   2465: 
1.256     matthew  2466: =pod 
1.113     bowersj2 2467: 
                   2468: =back
                   2469: 
                   2470: =cut
1.37      matthew  2471: 
                   2472: ###############################################################
1.33      matthew  2473: ##        Home server <option> list generating code          ##
                   2474: ###############################################################
1.35      matthew  2475: 
1.169     www      2476: # ------------------------------------------
                   2477: 
                   2478: sub domain_select {
                   2479:     my ($name,$value,$multiple)=@_;
                   2480:     my %domains=map { 
1.514     albertel 2481: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2482:     } &Apache::lonnet::all_domains();
1.169     www      2483:     if ($multiple) {
                   2484: 	$domains{''}=&mt('Any domain');
1.550     albertel 2485: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2486: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2487:     } else {
1.550     albertel 2488: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2489: 	return &select_form($name,$value,\%domains);
1.169     www      2490:     }
                   2491: }
                   2492: 
1.282     albertel 2493: #-------------------------------------------
                   2494: 
                   2495: =pod
                   2496: 
1.519     raeburn  2497: =head1 Routines for form select boxes
                   2498: 
                   2499: =over 4
                   2500: 
1.648     raeburn  2501: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2502: 
                   2503: Returns a string containing a <select> element int multiple mode
                   2504: 
                   2505: 
                   2506: Args:
                   2507:   $name - name of the <select> element
1.506     raeburn  2508:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2509:   $size - number of rows long the select element is
1.283     albertel 2510:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2511:           (shown text should already have been &mt())
1.506     raeburn  2512:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2513: 
1.282     albertel 2514: =cut
                   2515: 
                   2516: #-------------------------------------------
1.169     www      2517: sub multiple_select_form {
1.284     albertel 2518:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2519:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2520:     my $output='';
1.191     matthew  2521:     if (! defined($size)) {
                   2522:         $size = 4;
1.283     albertel 2523:         if (scalar(keys(%$hash))<4) {
                   2524:             $size = scalar(keys(%$hash));
1.191     matthew  2525:         }
                   2526:     }
1.734     bisitz   2527:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2528:     my @order;
1.506     raeburn  2529:     if (ref($order) eq 'ARRAY')  {
                   2530:         @order = @{$order};
                   2531:     } else {
                   2532:         @order = sort(keys(%$hash));
1.501     banghart 2533:     }
                   2534:     if (exists($$hash{'select_form_order'})) {
                   2535:         @order = @{$$hash{'select_form_order'}};
                   2536:     }
                   2537:         
1.284     albertel 2538:     foreach my $key (@order) {
1.356     albertel 2539:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2540:         $output.='selected="selected" ' if ($selected{$key});
                   2541:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2542:     }
                   2543:     $output.="</select>\n";
                   2544:     return $output;
                   2545: }
                   2546: 
1.88      www      2547: #-------------------------------------------
                   2548: 
                   2549: =pod
                   2550: 
1.1254    raeburn  2551: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2552: 
                   2553: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2554: allow a user to select options from a ref to a hash containing:
                   2555: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2556: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2557: An optional arg -- $readonly -- if true will cause the select form
                   2558: to be disabled, e.g., for the case where an instructor has a section-
                   2559: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2560: 
1.88      www      2561: See lonrights.pm for an example invocation and use.
                   2562: 
                   2563: =cut
                   2564: 
                   2565: #-------------------------------------------
                   2566: sub select_form {
1.1228    raeburn  2567:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2568:     return unless (ref($hashref) eq 'HASH');
                   2569:     if ($onchange) {
                   2570:         $onchange = ' onchange="'.$onchange.'"';
                   2571:     }
1.1228    raeburn  2572:     my $disabled;
                   2573:     if ($readonly) {
                   2574:         $disabled = ' disabled="disabled"';
                   2575:     }
                   2576:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2577:     my @keys;
1.970     raeburn  2578:     if (exists($hashref->{'select_form_order'})) {
                   2579: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2580:     } else {
1.970     raeburn  2581: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2582:     }
1.356     albertel 2583:     foreach my $key (@keys) {
                   2584:         $selectform.=
                   2585: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2586:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2587:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2588:     }
                   2589:     $selectform.="</select>";
                   2590:     return $selectform;
                   2591: }
                   2592: 
1.475     www      2593: # For display filters
                   2594: 
                   2595: sub display_filter {
1.1074    raeburn  2596:     my ($context) = @_;
1.475     www      2597:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2598:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2599:     my $phraseinput = 'hidden';
                   2600:     my $includeinput = 'hidden';
                   2601:     my ($checked,$includetypestext);
                   2602:     if ($env{'form.displayfilter'} eq 'containing') {
                   2603:         $phraseinput = 'text'; 
                   2604:         if ($context eq 'parmslog') {
                   2605:             $includeinput = 'checkbox';
                   2606:             if ($env{'form.includetypes'}) {
                   2607:                 $checked = ' checked="checked"';
                   2608:             }
                   2609:             $includetypestext = &mt('Include parameter types');
                   2610:         }
                   2611:     } else {
                   2612:         $includetypestext = '&nbsp;';
                   2613:     }
                   2614:     my ($additional,$secondid,$thirdid);
                   2615:     if ($context eq 'parmslog') {
                   2616:         $additional = 
                   2617:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2618:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2619:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2620:             '</label>';
                   2621:         $secondid = 'includetypes';
                   2622:         $thirdid = 'includetypestext';
                   2623:     }
                   2624:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2625:                                                     '$secondid','$thirdid')";
                   2626:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2627: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2628: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2629: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2630:            &mt('Filter: [_1]',
1.477     www      2631: 	   &select_form($env{'form.displayfilter'},
                   2632: 			'displayfilter',
1.970     raeburn  2633: 			{'currentfolder' => 'Current folder/page',
1.477     www      2634: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2635: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2636: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2637:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2638:                          '" />'.$additional;
                   2639: }
                   2640: 
                   2641: sub display_filter_js {
                   2642:     my $includetext = &mt('Include parameter types');
                   2643:     return <<"ENDJS";
                   2644:   
                   2645: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2646:     var firstType = 'hidden';
                   2647:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2648:         firstType = 'text';
                   2649:     }
                   2650:     firstObject = document.getElementById(firstid);
                   2651:     if (typeof(firstObject) == 'object') {
                   2652:         if (firstObject.type != firstType) {
                   2653:             changeInputType(firstObject,firstType);
                   2654:         }
                   2655:     }
                   2656:     if (context == 'parmslog') {
                   2657:         var secondType = 'hidden';
                   2658:         if (firstType == 'text') {
                   2659:             secondType = 'checkbox';
                   2660:         }
                   2661:         secondObject = document.getElementById(secondid);  
                   2662:         if (typeof(secondObject) == 'object') {
                   2663:             if (secondObject.type != secondType) {
                   2664:                 changeInputType(secondObject,secondType);
                   2665:             }
                   2666:         }
                   2667:         var textItem = document.getElementById(thirdid);
                   2668:         var currtext = textItem.innerHTML;
                   2669:         var newtext;
                   2670:         if (firstType == 'text') {
                   2671:             newtext = '$includetext';
                   2672:         } else {
                   2673:             newtext = '&nbsp;';
                   2674:         }
                   2675:         if (currtext != newtext) {
                   2676:             textItem.innerHTML = newtext;
                   2677:         }
                   2678:     }
                   2679:     return;
                   2680: }
                   2681: 
                   2682: function changeInputType(oldObject,newType) {
                   2683:     var newObject = document.createElement('input');
                   2684:     newObject.type = newType;
                   2685:     if (oldObject.size) {
                   2686:         newObject.size = oldObject.size;
                   2687:     }
                   2688:     if (oldObject.value) {
                   2689:         newObject.value = oldObject.value;
                   2690:     }
                   2691:     if (oldObject.name) {
                   2692:         newObject.name = oldObject.name;
                   2693:     }
                   2694:     if (oldObject.id) {
                   2695:         newObject.id = oldObject.id;
                   2696:     }
                   2697:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2698:     return;
                   2699: }
                   2700: 
                   2701: ENDJS
1.475     www      2702: }
                   2703: 
1.167     www      2704: sub gradeleveldescription {
                   2705:     my $gradelevel=shift;
                   2706:     my %gradelevels=(0 => 'Not specified',
                   2707: 		     1 => 'Grade 1',
                   2708: 		     2 => 'Grade 2',
                   2709: 		     3 => 'Grade 3',
                   2710: 		     4 => 'Grade 4',
                   2711: 		     5 => 'Grade 5',
                   2712: 		     6 => 'Grade 6',
                   2713: 		     7 => 'Grade 7',
                   2714: 		     8 => 'Grade 8',
                   2715: 		     9 => 'Grade 9',
                   2716: 		     10 => 'Grade 10',
                   2717: 		     11 => 'Grade 11',
                   2718: 		     12 => 'Grade 12',
                   2719: 		     13 => 'Grade 13',
                   2720: 		     14 => '100 Level',
                   2721: 		     15 => '200 Level',
                   2722: 		     16 => '300 Level',
                   2723: 		     17 => '400 Level',
                   2724: 		     18 => 'Graduate Level');
                   2725:     return &mt($gradelevels{$gradelevel});
                   2726: }
                   2727: 
1.163     www      2728: sub select_level_form {
                   2729:     my ($deflevel,$name)=@_;
                   2730:     unless ($deflevel) { $deflevel=0; }
1.167     www      2731:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2732:     for (my $i=0; $i<=18; $i++) {
                   2733:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2734:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2735:                 ">".&gradeleveldescription($i)."</option>\n";
                   2736:     }
                   2737:     $selectform.="</select>";
                   2738:     return $selectform;
1.163     www      2739: }
1.167     www      2740: 
1.35      matthew  2741: #-------------------------------------------
                   2742: 
1.45      matthew  2743: =pod
                   2744: 
1.1256    raeburn  2745: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2746: 
                   2747: Returns a string containing a <select name='$name' size='1'> form to 
                   2748: allow a user to select the domain to preform an operation in.  
                   2749: See loncreateuser.pm for an example invocation and use.
                   2750: 
1.90      www      2751: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2752: selected");
                   2753: 
1.743     raeburn  2754: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2755: 
1.910     raeburn  2756: 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.
                   2757: 
1.1121    raeburn  2758: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2759: 
                   2760: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2761: 
1.1256    raeburn  2762: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2763: 
1.35      matthew  2764: =cut
                   2765: 
                   2766: #-------------------------------------------
1.34      matthew  2767: sub select_dom_form {
1.1256    raeburn  2768:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2769:     if ($onchange) {
1.874     raeburn  2770:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2771:     }
1.1256    raeburn  2772:     if ($disabled) {
                   2773:         $disabled = ' disabled="disabled"';
                   2774:     }
1.1121    raeburn  2775:     my (@domains,%exclude);
1.910     raeburn  2776:     if (ref($incdoms) eq 'ARRAY') {
                   2777:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2778:     } else {
                   2779:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2780:     }
1.90      www      2781:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2782:     if (ref($excdoms) eq 'ARRAY') {
                   2783:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2784:     }
1.1256    raeburn  2785:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2786:     foreach my $dom (@domains) {
1.1121    raeburn  2787:         next if ($exclude{$dom});
1.356     albertel 2788:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2789:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2790:         if ($showdomdesc) {
                   2791:             if ($dom ne '') {
                   2792:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2793:                 if ($domdesc ne '') {
                   2794:                     $selectdomain .= ' ('.$domdesc.')';
                   2795:                 }
                   2796:             } 
                   2797:         }
                   2798:         $selectdomain .= "</option>\n";
1.34      matthew  2799:     }
                   2800:     $selectdomain.="</select>";
                   2801:     return $selectdomain;
                   2802: }
                   2803: 
1.35      matthew  2804: #-------------------------------------------
                   2805: 
1.45      matthew  2806: =pod
                   2807: 
1.648     raeburn  2808: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2809: 
1.586     raeburn  2810: input: 4 arguments (two required, two optional) - 
                   2811:     $domain - domain of new user
                   2812:     $name - name of form element
                   2813:     $default - Value of 'default' causes a default item to be first 
                   2814:                             option, and selected by default. 
                   2815:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2816:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2817: output: returns 2 items: 
1.586     raeburn  2818: (a) form element which contains either:
                   2819:    (i) <select name="$name">
                   2820:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2821:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2822:        </select>
                   2823:        form item if there are multiple library servers in $domain, or
                   2824:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2825:        if there is only one library server in $domain.
                   2826: 
                   2827: (b) number of library servers found.
                   2828: 
                   2829: See loncreateuser.pm for example of use.
1.35      matthew  2830: 
                   2831: =cut
                   2832: 
                   2833: #-------------------------------------------
1.586     raeburn  2834: sub home_server_form_item {
                   2835:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2836:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2837:     my $result;
                   2838:     my $numlib = keys(%servers);
                   2839:     if ($numlib > 1) {
                   2840:         $result .= '<select name="'.$name.'" />'."\n";
                   2841:         if ($default) {
1.804     bisitz   2842:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2843:                        '</option>'."\n";
                   2844:         }
                   2845:         foreach my $hostid (sort(keys(%servers))) {
                   2846:             $result.= '<option value="'.$hostid.'">'.
                   2847: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2848:         }
                   2849:         $result .= '</select>'."\n";
                   2850:     } elsif ($numlib == 1) {
                   2851:         my $hostid;
                   2852:         foreach my $item (keys(%servers)) {
                   2853:             $hostid = $item;
                   2854:         }
                   2855:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2856:                    $hostid.'" />';
                   2857:                    if (!$hide) {
                   2858:                        $result .= $hostid.' '.$servers{$hostid};
                   2859:                    }
                   2860:                    $result .= "\n";
                   2861:     } elsif ($default) {
                   2862:         $result .= '<input type="hidden" name="'.$name.
                   2863:                    '" value="default" />';
                   2864:                    if (!$hide) {
                   2865:                        $result .= &mt('default');
                   2866:                    }
                   2867:                    $result .= "\n";
1.33      matthew  2868:     }
1.586     raeburn  2869:     return ($result,$numlib);
1.33      matthew  2870: }
1.112     bowersj2 2871: 
                   2872: =pod
                   2873: 
1.534     albertel 2874: =back 
                   2875: 
1.112     bowersj2 2876: =cut
1.87      matthew  2877: 
                   2878: ###############################################################
1.112     bowersj2 2879: ##                  Decoding User Agent                      ##
1.87      matthew  2880: ###############################################################
                   2881: 
                   2882: =pod
                   2883: 
1.112     bowersj2 2884: =head1 Decoding the User Agent
                   2885: 
                   2886: =over 4
                   2887: 
                   2888: =item * &decode_user_agent()
1.87      matthew  2889: 
                   2890: Inputs: $r
                   2891: 
                   2892: Outputs:
                   2893: 
                   2894: =over 4
                   2895: 
1.112     bowersj2 2896: =item * $httpbrowser
1.87      matthew  2897: 
1.112     bowersj2 2898: =item * $clientbrowser
1.87      matthew  2899: 
1.112     bowersj2 2900: =item * $clientversion
1.87      matthew  2901: 
1.112     bowersj2 2902: =item * $clientmathml
1.87      matthew  2903: 
1.112     bowersj2 2904: =item * $clientunicode
1.87      matthew  2905: 
1.112     bowersj2 2906: =item * $clientos
1.87      matthew  2907: 
1.1137    raeburn  2908: =item * $clientmobile
                   2909: 
1.1141    raeburn  2910: =item * $clientinfo
                   2911: 
1.1194    raeburn  2912: =item * $clientosversion
                   2913: 
1.87      matthew  2914: =back
                   2915: 
1.157     matthew  2916: =back 
                   2917: 
1.87      matthew  2918: =cut
                   2919: 
                   2920: ###############################################################
                   2921: ###############################################################
                   2922: sub decode_user_agent {
1.247     albertel 2923:     my ($r)=@_;
1.87      matthew  2924:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2925:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2926:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2927:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2928:     my $clientbrowser='unknown';
                   2929:     my $clientversion='0';
                   2930:     my $clientmathml='';
                   2931:     my $clientunicode='0';
1.1137    raeburn  2932:     my $clientmobile=0;
1.1194    raeburn  2933:     my $clientosversion='';
1.87      matthew  2934:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2935:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2936: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2937: 	    $clientbrowser=$bname;
                   2938:             $httpbrowser=~/$vreg/i;
                   2939: 	    $clientversion=$1;
                   2940:             $clientmathml=($clientversion>=$minv);
                   2941:             $clientunicode=($clientversion>=$univ);
                   2942: 	}
                   2943:     }
                   2944:     my $clientos='unknown';
1.1141    raeburn  2945:     my $clientinfo;
1.87      matthew  2946:     if (($httpbrowser=~/linux/i) ||
                   2947:         ($httpbrowser=~/unix/i) ||
                   2948:         ($httpbrowser=~/ux/i) ||
                   2949:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2950:     if (($httpbrowser=~/vax/i) ||
                   2951:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2952:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2953:     if (($httpbrowser=~/mac/i) ||
                   2954:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2955:     if ($httpbrowser=~/win/i) {
                   2956:         $clientos='win';
                   2957:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2958:             $clientosversion = $1;
                   2959:         }
                   2960:     }
1.87      matthew  2961:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2962:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2963:         $clientmobile=lc($1);
                   2964:     }
1.1141    raeburn  2965:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2966:         $clientinfo = 'firefox-'.$1;
                   2967:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2968:         $clientinfo = 'chromeframe-'.$1;
                   2969:     }
1.87      matthew  2970:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  2971:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2972:             $clientosversion);
1.87      matthew  2973: }
                   2974: 
1.32      matthew  2975: ###############################################################
                   2976: ##    Authentication changing form generation subroutines    ##
                   2977: ###############################################################
                   2978: ##
                   2979: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2980: ## hash, and have reasonable default values.
                   2981: ##
                   2982: ##    formname = the name given in the <form> tag.
1.35      matthew  2983: #-------------------------------------------
                   2984: 
1.45      matthew  2985: =pod
                   2986: 
1.112     bowersj2 2987: =head1 Authentication Routines
                   2988: 
                   2989: =over 4
                   2990: 
1.648     raeburn  2991: =item * &authform_xxxxxx()
1.35      matthew  2992: 
                   2993: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2994: handle some of the conveniences required for authentication forms.  
                   2995: This is not an optimal method, but it works.  
                   2996: 
                   2997: =over 4
                   2998: 
1.112     bowersj2 2999: =item * authform_header
1.35      matthew  3000: 
1.112     bowersj2 3001: =item * authform_authorwarning
1.35      matthew  3002: 
1.112     bowersj2 3003: =item * authform_nochange
1.35      matthew  3004: 
1.112     bowersj2 3005: =item * authform_kerberos
1.35      matthew  3006: 
1.112     bowersj2 3007: =item * authform_internal
1.35      matthew  3008: 
1.112     bowersj2 3009: =item * authform_filesystem
1.35      matthew  3010: 
                   3011: =back
                   3012: 
1.648     raeburn  3013: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3014: 
1.35      matthew  3015: =cut
                   3016: 
                   3017: #-------------------------------------------
1.32      matthew  3018: sub authform_header{  
                   3019:     my %in = (
                   3020:         formname => 'cu',
1.80      albertel 3021:         kerb_def_dom => '',
1.32      matthew  3022:         @_,
                   3023:     );
                   3024:     $in{'formname'} = 'document.' . $in{'formname'};
                   3025:     my $result='';
1.80      albertel 3026: 
                   3027: #---------------------------------------------- Code for upper case translation
                   3028:     my $Javascript_toUpperCase;
                   3029:     unless ($in{kerb_def_dom}) {
                   3030:         $Javascript_toUpperCase =<<"END";
                   3031:         switch (choice) {
                   3032:            case 'krb': currentform.elements[choicearg].value =
                   3033:                currentform.elements[choicearg].value.toUpperCase();
                   3034:                break;
                   3035:            default:
                   3036:         }
                   3037: END
                   3038:     } else {
                   3039:         $Javascript_toUpperCase = "";
                   3040:     }
                   3041: 
1.165     raeburn  3042:     my $radioval = "'nochange'";
1.591     raeburn  3043:     if (defined($in{'curr_authtype'})) {
                   3044:         if ($in{'curr_authtype'} ne '') {
                   3045:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3046:         }
1.174     matthew  3047:     }
1.165     raeburn  3048:     my $argfield = 'null';
1.591     raeburn  3049:     if (defined($in{'mode'})) {
1.165     raeburn  3050:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3051:             if (defined($in{'curr_autharg'})) {
                   3052:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3053:                     $argfield = "'$in{'curr_autharg'}'";
                   3054:                 }
                   3055:             }
                   3056:         }
                   3057:     }
                   3058: 
1.32      matthew  3059:     $result.=<<"END";
                   3060: var current = new Object();
1.165     raeburn  3061: current.radiovalue = $radioval;
                   3062: current.argfield = $argfield;
1.32      matthew  3063: 
                   3064: function changed_radio(choice,currentform) {
                   3065:     var choicearg = choice + 'arg';
                   3066:     // If a radio button in changed, we need to change the argfield
                   3067:     if (current.radiovalue != choice) {
                   3068:         current.radiovalue = choice;
                   3069:         if (current.argfield != null) {
                   3070:             currentform.elements[current.argfield].value = '';
                   3071:         }
                   3072:         if (choice == 'nochange') {
                   3073:             current.argfield = null;
                   3074:         } else {
                   3075:             current.argfield = choicearg;
                   3076:             switch(choice) {
                   3077:                 case 'krb': 
                   3078:                     currentform.elements[current.argfield].value = 
                   3079:                         "$in{'kerb_def_dom'}";
                   3080:                 break;
                   3081:               default:
                   3082:                 break;
                   3083:             }
                   3084:         }
                   3085:     }
                   3086:     return;
                   3087: }
1.22      www      3088: 
1.32      matthew  3089: function changed_text(choice,currentform) {
                   3090:     var choicearg = choice + 'arg';
                   3091:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3092:         $Javascript_toUpperCase
1.32      matthew  3093:         // clear old field
                   3094:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3095:             currentform.elements[current.argfield].value = '';
                   3096:         }
                   3097:         current.argfield = choicearg;
                   3098:     }
                   3099:     set_auth_radio_buttons(choice,currentform);
                   3100:     return;
1.20      www      3101: }
1.32      matthew  3102: 
                   3103: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3104:     var numauthchoices = currentform.login.length;
                   3105:     if (typeof numauthchoices  == "undefined") {
                   3106:         return;
                   3107:     } 
1.32      matthew  3108:     var i=0;
1.986     raeburn  3109:     while (i < numauthchoices) {
1.32      matthew  3110:         if (currentform.login[i].value == newvalue) { break; }
                   3111:         i++;
                   3112:     }
1.986     raeburn  3113:     if (i == numauthchoices) {
1.32      matthew  3114:         return;
                   3115:     }
                   3116:     current.radiovalue = newvalue;
                   3117:     currentform.login[i].checked = true;
                   3118:     return;
                   3119: }
                   3120: END
                   3121:     return $result;
                   3122: }
                   3123: 
1.1106    raeburn  3124: sub authform_authorwarning {
1.32      matthew  3125:     my $result='';
1.144     matthew  3126:     $result='<i>'.
                   3127:         &mt('As a general rule, only authors or co-authors should be '.
                   3128:             'filesystem authenticated '.
                   3129:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3130:     return $result;
                   3131: }
                   3132: 
1.1106    raeburn  3133: sub authform_nochange {
1.32      matthew  3134:     my %in = (
                   3135:               formname => 'document.cu',
                   3136:               kerb_def_dom => 'MSU.EDU',
                   3137:               @_,
                   3138:           );
1.1106    raeburn  3139:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3140:     my $result;
1.1104    raeburn  3141:     if (!$authnum) {
1.1105    raeburn  3142:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3143:     } else {
                   3144:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3145:                   '<input type="radio" name="login" value="nochange" '.
                   3146:                   'checked="checked" onclick="'.
1.281     albertel 3147:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3148: 	    '</label>';
1.586     raeburn  3149:     }
1.32      matthew  3150:     return $result;
                   3151: }
                   3152: 
1.591     raeburn  3153: sub authform_kerberos {
1.32      matthew  3154:     my %in = (
                   3155:               formname => 'document.cu',
                   3156:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3157:               kerb_def_auth => 'krb4',
1.32      matthew  3158:               @_,
                   3159:               );
1.586     raeburn  3160:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3161:         $autharg,$jscall,$disabled);
1.1106    raeburn  3162:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3163:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3164:        $check5 = ' checked="checked"';
1.80      albertel 3165:     } else {
1.772     bisitz   3166:        $check4 = ' checked="checked"';
1.80      albertel 3167:     }
1.1259    raeburn  3168:     if ($in{'readonly'}) {
                   3169:         $disabled = ' disabled="disabled"';
                   3170:     }
1.165     raeburn  3171:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3172:     if (defined($in{'curr_authtype'})) {
                   3173:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3174:             $krbcheck = ' checked="checked"';
1.623     raeburn  3175:             if (defined($in{'mode'})) {
                   3176:                 if ($in{'mode'} eq 'modifyuser') {
                   3177:                     $krbcheck = '';
                   3178:                 }
                   3179:             }
1.591     raeburn  3180:             if (defined($in{'curr_kerb_ver'})) {
                   3181:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3182:                     $check5 = ' checked="checked"';
1.591     raeburn  3183:                     $check4 = '';
                   3184:                 } else {
1.772     bisitz   3185:                     $check4 = ' checked="checked"';
1.591     raeburn  3186:                     $check5 = '';
                   3187:                 }
1.586     raeburn  3188:             }
1.591     raeburn  3189:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3190:                 $krbarg = $in{'curr_autharg'};
                   3191:             }
1.586     raeburn  3192:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3193:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3194:                     $result = 
                   3195:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3196:         $in{'curr_autharg'},$krbver);
                   3197:                 } else {
                   3198:                     $result =
                   3199:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3200:                 }
                   3201:                 return $result; 
                   3202:             }
                   3203:         }
                   3204:     } else {
                   3205:         if ($authnum == 1) {
1.784     bisitz   3206:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3207:         }
                   3208:     }
1.586     raeburn  3209:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3210:         return;
1.587     raeburn  3211:     } elsif ($authtype eq '') {
1.591     raeburn  3212:         if (defined($in{'mode'})) {
1.587     raeburn  3213:             if ($in{'mode'} eq 'modifycourse') {
                   3214:                 if ($authnum == 1) {
1.1259    raeburn  3215:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3216:                 }
                   3217:             }
                   3218:         }
1.586     raeburn  3219:     }
                   3220:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3221:     if ($authtype eq '') {
                   3222:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3223:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3224:                     $krbcheck.$disabled.' />';
1.586     raeburn  3225:     }
                   3226:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3227:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3228:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3229:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3230:          $in{'curr_authtype'} eq 'krb4')) {
                   3231:         $result .= &mt
1.144     matthew  3232:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3233:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3234:          '<label>'.$authtype,
1.281     albertel 3235:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3236:              'value="'.$krbarg.'" '.
1.1259    raeburn  3237:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3238:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3239:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3240: 	 '</label>');
1.586     raeburn  3241:     } elsif ($can_assign{'krb4'}) {
                   3242:         $result .= &mt
                   3243:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3244:          '[_3] Version 4 [_4]',
                   3245:          '<label>'.$authtype,
                   3246:          '</label><input type="text" size="10" name="krbarg" '.
                   3247:              'value="'.$krbarg.'" '.
1.1259    raeburn  3248:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3249:          '<label><input type="hidden" name="krbver" value="4" />',
                   3250:          '</label>');
                   3251:     } elsif ($can_assign{'krb5'}) {
                   3252:         $result .= &mt
                   3253:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3254:          '[_3] Version 5 [_4]',
                   3255:          '<label>'.$authtype,
                   3256:          '</label><input type="text" size="10" name="krbarg" '.
                   3257:              'value="'.$krbarg.'" '.
1.1259    raeburn  3258:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3259:          '<label><input type="hidden" name="krbver" value="5" />',
                   3260:          '</label>');
                   3261:     }
1.32      matthew  3262:     return $result;
                   3263: }
                   3264: 
1.1106    raeburn  3265: sub authform_internal {
1.586     raeburn  3266:     my %in = (
1.32      matthew  3267:                 formname => 'document.cu',
                   3268:                 kerb_def_dom => 'MSU.EDU',
                   3269:                 @_,
                   3270:                 );
1.1259    raeburn  3271:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3272:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3273:     if ($in{'readonly'}) {
                   3274:         $disabled = ' disabled="disabled"';
                   3275:     }
1.591     raeburn  3276:     if (defined($in{'curr_authtype'})) {
                   3277:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3278:             if ($can_assign{'int'}) {
1.772     bisitz   3279:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3280:                 if (defined($in{'mode'})) {
                   3281:                     if ($in{'mode'} eq 'modifyuser') {
                   3282:                         $intcheck = '';
                   3283:                     }
                   3284:                 }
1.591     raeburn  3285:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3286:                     $intarg = $in{'curr_autharg'};
                   3287:                 }
                   3288:             } else {
                   3289:                 $result = &mt('Currently internally authenticated.');
                   3290:                 return $result;
1.165     raeburn  3291:             }
                   3292:         }
1.586     raeburn  3293:     } else {
                   3294:         if ($authnum == 1) {
1.784     bisitz   3295:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3296:         }
                   3297:     }
                   3298:     if (!$can_assign{'int'}) {
                   3299:         return;
1.587     raeburn  3300:     } elsif ($authtype eq '') {
1.591     raeburn  3301:         if (defined($in{'mode'})) {
1.587     raeburn  3302:             if ($in{'mode'} eq 'modifycourse') {
                   3303:                 if ($authnum == 1) {
1.1259    raeburn  3304:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3305:                 }
                   3306:             }
                   3307:         }
1.165     raeburn  3308:     }
1.586     raeburn  3309:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3310:     if ($authtype eq '') {
                   3311:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3312:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3313:     }
1.605     bisitz   3314:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3315:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3316:     $result = &mt
1.144     matthew  3317:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3318:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3319:     $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  3320:     return $result;
                   3321: }
                   3322: 
1.1104    raeburn  3323: sub authform_local {
1.32      matthew  3324:     my %in = (
                   3325:               formname => 'document.cu',
                   3326:               kerb_def_dom => 'MSU.EDU',
                   3327:               @_,
                   3328:               );
1.1259    raeburn  3329:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3330:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3331:     if ($in{'readonly'}) {
                   3332:         $disabled = ' disabled="disabled"';
                   3333:     } 
1.591     raeburn  3334:     if (defined($in{'curr_authtype'})) {
                   3335:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3336:             if ($can_assign{'loc'}) {
1.772     bisitz   3337:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3338:                 if (defined($in{'mode'})) {
                   3339:                     if ($in{'mode'} eq 'modifyuser') {
                   3340:                         $loccheck = '';
                   3341:                     }
                   3342:                 }
1.591     raeburn  3343:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3344:                     $locarg = $in{'curr_autharg'};
                   3345:                 }
                   3346:             } else {
                   3347:                 $result = &mt('Currently using local (institutional) authentication.');
                   3348:                 return $result;
1.165     raeburn  3349:             }
                   3350:         }
1.586     raeburn  3351:     } else {
                   3352:         if ($authnum == 1) {
1.784     bisitz   3353:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3354:         }
                   3355:     }
                   3356:     if (!$can_assign{'loc'}) {
                   3357:         return;
1.587     raeburn  3358:     } elsif ($authtype eq '') {
1.591     raeburn  3359:         if (defined($in{'mode'})) {
1.587     raeburn  3360:             if ($in{'mode'} eq 'modifycourse') {
                   3361:                 if ($authnum == 1) {
1.1259    raeburn  3362:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3363:                 }
                   3364:             }
                   3365:         }
1.165     raeburn  3366:     }
1.586     raeburn  3367:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3368:     if ($authtype eq '') {
                   3369:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3370:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3371:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3372:     }
                   3373:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3374:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3375:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3376:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3377:     return $result;
                   3378: }
                   3379: 
1.1106    raeburn  3380: sub authform_filesystem {
1.32      matthew  3381:     my %in = (
                   3382:               formname => 'document.cu',
                   3383:               kerb_def_dom => 'MSU.EDU',
                   3384:               @_,
                   3385:               );
1.1259    raeburn  3386:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3387:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3388:     if ($in{'readonly'}) {
                   3389:         $disabled = ' disabled="disabled"';
                   3390:     }
1.591     raeburn  3391:     if (defined($in{'curr_authtype'})) {
                   3392:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3393:             if ($can_assign{'fsys'}) {
1.772     bisitz   3394:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3395:                 if (defined($in{'mode'})) {
                   3396:                     if ($in{'mode'} eq 'modifyuser') {
                   3397:                         $fsyscheck = '';
                   3398:                     }
                   3399:                 }
1.586     raeburn  3400:             } else {
                   3401:                 $result = &mt('Currently Filesystem Authenticated.');
                   3402:                 return $result;
1.1259    raeburn  3403:             }
1.586     raeburn  3404:         }
                   3405:     } else {
                   3406:         if ($authnum == 1) {
1.784     bisitz   3407:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3408:         }
                   3409:     }
                   3410:     if (!$can_assign{'fsys'}) {
                   3411:         return;
1.587     raeburn  3412:     } elsif ($authtype eq '') {
1.591     raeburn  3413:         if (defined($in{'mode'})) {
1.587     raeburn  3414:             if ($in{'mode'} eq 'modifycourse') {
                   3415:                 if ($authnum == 1) {
1.1259    raeburn  3416:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3417:                 }
                   3418:             }
                   3419:         }
1.586     raeburn  3420:     }
                   3421:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3422:     if ($authtype eq '') {
                   3423:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3424:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3425:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3426:     }
                   3427:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3428:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3429:     $result = &mt
1.144     matthew  3430:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3431:          '<label><input type="radio" name="login" value="fsys" '.
1.1259    raeburn  3432:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3433:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1259    raeburn  3434:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3435:     return $result;
                   3436: }
                   3437: 
1.586     raeburn  3438: sub get_assignable_auth {
                   3439:     my ($dom) = @_;
                   3440:     if ($dom eq '') {
                   3441:         $dom = $env{'request.role.domain'};
                   3442:     }
                   3443:     my %can_assign = (
                   3444:                           krb4 => 1,
                   3445:                           krb5 => 1,
                   3446:                           int  => 1,
                   3447:                           loc  => 1,
                   3448:                      );
                   3449:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3450:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3451:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3452:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3453:             my $context;
                   3454:             if ($env{'request.role'} =~ /^au/) {
                   3455:                 $context = 'author';
1.1259    raeburn  3456:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3457:                 $context = 'domain';
                   3458:             } elsif ($env{'request.course.id'}) {
                   3459:                 $context = 'course';
                   3460:             }
                   3461:             if ($context) {
                   3462:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3463:                    %can_assign = %{$authhash->{$context}}; 
                   3464:                 }
                   3465:             }
                   3466:         }
                   3467:     }
                   3468:     my $authnum = 0;
                   3469:     foreach my $key (keys(%can_assign)) {
                   3470:         if ($can_assign{$key}) {
                   3471:             $authnum ++;
                   3472:         }
                   3473:     }
                   3474:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3475:         $authnum --;
                   3476:     }
                   3477:     return ($authnum,%can_assign);
                   3478: }
                   3479: 
1.80      albertel 3480: ###############################################################
                   3481: ##    Get Kerberos Defaults for Domain                 ##
                   3482: ###############################################################
                   3483: ##
                   3484: ## Returns default kerberos version and an associated argument
                   3485: ## as listed in file domain.tab. If not listed, provides
                   3486: ## appropriate default domain and kerberos version.
                   3487: ##
                   3488: #-------------------------------------------
                   3489: 
                   3490: =pod
                   3491: 
1.648     raeburn  3492: =item * &get_kerberos_defaults()
1.80      albertel 3493: 
                   3494: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3495: version and domain. If not found, it defaults to version 4 and the 
                   3496: domain of the server.
1.80      albertel 3497: 
1.648     raeburn  3498: =over 4
                   3499: 
1.80      albertel 3500: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3501: 
1.648     raeburn  3502: =back
                   3503: 
                   3504: =back
                   3505: 
1.80      albertel 3506: =cut
                   3507: 
                   3508: #-------------------------------------------
                   3509: sub get_kerberos_defaults {
                   3510:     my $domain=shift;
1.641     raeburn  3511:     my ($krbdef,$krbdefdom);
                   3512:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3513:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3514:         $krbdef = $domdefaults{'auth_def'};
                   3515:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3516:     } else {
1.80      albertel 3517:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3518:         my $krbdefdom=$1;
                   3519:         $krbdefdom=~tr/a-z/A-Z/;
                   3520:         $krbdef = "krb4";
                   3521:     }
                   3522:     return ($krbdef,$krbdefdom);
                   3523: }
1.112     bowersj2 3524: 
1.32      matthew  3525: 
1.46      matthew  3526: ###############################################################
                   3527: ##                Thesaurus Functions                        ##
                   3528: ###############################################################
1.20      www      3529: 
1.46      matthew  3530: =pod
1.20      www      3531: 
1.112     bowersj2 3532: =head1 Thesaurus Functions
                   3533: 
                   3534: =over 4
                   3535: 
1.648     raeburn  3536: =item * &initialize_keywords()
1.46      matthew  3537: 
                   3538: Initializes the package variable %Keywords if it is empty.  Uses the
                   3539: package variable $thesaurus_db_file.
                   3540: 
                   3541: =cut
                   3542: 
                   3543: ###################################################
                   3544: 
                   3545: sub initialize_keywords {
                   3546:     return 1 if (scalar keys(%Keywords));
                   3547:     # If we are here, %Keywords is empty, so fill it up
                   3548:     #   Make sure the file we need exists...
                   3549:     if (! -e $thesaurus_db_file) {
                   3550:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3551:                                  " failed because it does not exist");
                   3552:         return 0;
                   3553:     }
                   3554:     #   Set up the hash as a database
                   3555:     my %thesaurus_db;
                   3556:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3557:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3558:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3559:                                  $thesaurus_db_file);
                   3560:         return 0;
                   3561:     } 
                   3562:     #  Get the average number of appearances of a word.
                   3563:     my $avecount = $thesaurus_db{'average.count'};
                   3564:     #  Put keywords (those that appear > average) into %Keywords
                   3565:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3566:         my ($count,undef) = split /:/,$data;
                   3567:         $Keywords{$word}++ if ($count > $avecount);
                   3568:     }
                   3569:     untie %thesaurus_db;
                   3570:     # Remove special values from %Keywords.
1.356     albertel 3571:     foreach my $value ('total.count','average.count') {
                   3572:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3573:   }
1.46      matthew  3574:     return 1;
                   3575: }
                   3576: 
                   3577: ###################################################
                   3578: 
                   3579: =pod
                   3580: 
1.648     raeburn  3581: =item * &keyword($word)
1.46      matthew  3582: 
                   3583: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3584: than the average number of times in the thesaurus database.  Calls 
                   3585: &initialize_keywords
                   3586: 
                   3587: =cut
                   3588: 
                   3589: ###################################################
1.20      www      3590: 
                   3591: sub keyword {
1.46      matthew  3592:     return if (!&initialize_keywords());
                   3593:     my $word=lc(shift());
                   3594:     $word=~s/\W//g;
                   3595:     return exists($Keywords{$word});
1.20      www      3596: }
1.46      matthew  3597: 
                   3598: ###############################################################
                   3599: 
                   3600: =pod 
1.20      www      3601: 
1.648     raeburn  3602: =item * &get_related_words()
1.46      matthew  3603: 
1.160     matthew  3604: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3605: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3606: will be returned.  The order of the words returned is determined by the
                   3607: database which holds them.
                   3608: 
                   3609: Uses global $thesaurus_db_file.
                   3610: 
1.1057    foxr     3611: 
1.46      matthew  3612: =cut
                   3613: 
                   3614: ###############################################################
                   3615: sub get_related_words {
                   3616:     my $keyword = shift;
                   3617:     my %thesaurus_db;
                   3618:     if (! -e $thesaurus_db_file) {
                   3619:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3620:                                  "failed because the file does not exist");
                   3621:         return ();
                   3622:     }
                   3623:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3624:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3625:         return ();
                   3626:     } 
                   3627:     my @Words=();
1.429     www      3628:     my $count=0;
1.46      matthew  3629:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3630: 	# The first element is the number of times
                   3631: 	# the word appears.  We do not need it now.
1.429     www      3632: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3633: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3634: 	my $threshold=$mostfrequentcount/10;
                   3635:         foreach my $possibleword (@RelatedWords) {
                   3636:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3637:             if ($wordcount>$threshold) {
                   3638: 		push(@Words,$word);
                   3639:                 $count++;
                   3640:                 if ($count>10) { last; }
                   3641: 	    }
1.20      www      3642:         }
                   3643:     }
1.46      matthew  3644:     untie %thesaurus_db;
                   3645:     return @Words;
1.14      harris41 3646: }
1.1090    foxr     3647: ###############################################################
                   3648: #
                   3649: #  Spell checking
                   3650: #
                   3651: 
                   3652: =pod
                   3653: 
1.1142    raeburn  3654: =back
                   3655: 
1.1090    foxr     3656: =head1 Spell checking
                   3657: 
                   3658: =over 4
                   3659: 
                   3660: =item * &check_spelling($wordlist $language)
                   3661: 
                   3662: Takes a string containing words and feeds it to an external
                   3663: spellcheck program via a pipeline. Returns a string containing
                   3664: them mis-spelled words.
                   3665: 
                   3666: Parameters:
                   3667: 
                   3668: =over 4
                   3669: 
                   3670: =item - $wordlist
                   3671: 
                   3672: String that will be fed into the spellcheck program.
                   3673: 
                   3674: =item - $language
                   3675: 
                   3676: Language string that specifies the language for which the spell
                   3677: check will be performed.
                   3678: 
                   3679: =back
                   3680: 
                   3681: =back
                   3682: 
                   3683: Note: This sub assumes that aspell is installed.
                   3684: 
                   3685: 
                   3686: =cut
                   3687: 
1.46      matthew  3688: 
1.1090    foxr     3689: sub check_spelling {
                   3690:     my ($wordlist, $language) = @_;
1.1091    foxr     3691:     my @misspellings;
                   3692:     
                   3693:     # Generate the speller and set the langauge.
                   3694:     # if explicitly selected:
1.1090    foxr     3695: 
1.1091    foxr     3696:     my $speller = Text::Aspell->new;
1.1090    foxr     3697:     if ($language) {
1.1091    foxr     3698: 	$speller->set_option('lang', $language);
1.1090    foxr     3699:     }
                   3700: 
1.1091    foxr     3701:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3702: 
1.1091    foxr     3703:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3704: 
1.1091    foxr     3705:     foreach my $word (@words) {
                   3706: 	if(! $speller->check($word)) {
                   3707: 	    push(@misspellings, $word);
1.1090    foxr     3708: 	}
                   3709:     }
1.1091    foxr     3710:     return join(' ', @misspellings);
                   3711:     
1.1090    foxr     3712: }
                   3713: 
1.61      www      3714: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3715: =pod
                   3716: 
1.112     bowersj2 3717: =head1 User Name Functions
                   3718: 
                   3719: =over 4
                   3720: 
1.648     raeburn  3721: =item * &plainname($uname,$udom,$first)
1.81      albertel 3722: 
1.112     bowersj2 3723: Takes a users logon name and returns it as a string in
1.226     albertel 3724: "first middle last generation" form 
                   3725: if $first is set to 'lastname' then it returns it as
                   3726: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3727: 
                   3728: =cut
1.61      www      3729: 
1.295     www      3730: 
1.81      albertel 3731: ###############################################################
1.61      www      3732: sub plainname {
1.226     albertel 3733:     my ($uname,$udom,$first)=@_;
1.537     albertel 3734:     return if (!defined($uname) || !defined($udom));
1.295     www      3735:     my %names=&getnames($uname,$udom);
1.226     albertel 3736:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3737: 					  $names{'middlename'},
                   3738: 					  $names{'lastname'},
                   3739: 					  $names{'generation'},$first);
                   3740:     $name=~s/^\s+//;
1.62      www      3741:     $name=~s/\s+$//;
                   3742:     $name=~s/\s+/ /g;
1.353     albertel 3743:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3744:     return $name;
1.61      www      3745: }
1.66      www      3746: 
                   3747: # -------------------------------------------------------------------- Nickname
1.81      albertel 3748: =pod
                   3749: 
1.648     raeburn  3750: =item * &nickname($uname,$udom)
1.81      albertel 3751: 
                   3752: Gets a users name and returns it as a string as
                   3753: 
                   3754: "&quot;nickname&quot;"
1.66      www      3755: 
1.81      albertel 3756: if the user has a nickname or
                   3757: 
                   3758: "first middle last generation"
                   3759: 
                   3760: if the user does not
                   3761: 
                   3762: =cut
1.66      www      3763: 
                   3764: sub nickname {
                   3765:     my ($uname,$udom)=@_;
1.537     albertel 3766:     return if (!defined($uname) || !defined($udom));
1.295     www      3767:     my %names=&getnames($uname,$udom);
1.68      albertel 3768:     my $name=$names{'nickname'};
1.66      www      3769:     if ($name) {
                   3770:        $name='&quot;'.$name.'&quot;'; 
                   3771:     } else {
                   3772:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3773: 	     $names{'lastname'}.' '.$names{'generation'};
                   3774:        $name=~s/\s+$//;
                   3775:        $name=~s/\s+/ /g;
                   3776:     }
                   3777:     return $name;
                   3778: }
                   3779: 
1.295     www      3780: sub getnames {
                   3781:     my ($uname,$udom)=@_;
1.537     albertel 3782:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3783:     if ($udom eq 'public' && $uname eq 'public') {
                   3784: 	return ('lastname' => &mt('Public'));
                   3785:     }
1.295     www      3786:     my $id=$uname.':'.$udom;
                   3787:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3788:     if ($cached) {
                   3789: 	return %{$names};
                   3790:     } else {
                   3791: 	my %loadnames=&Apache::lonnet::get('environment',
                   3792:                     ['firstname','middlename','lastname','generation','nickname'],
                   3793: 					 $udom,$uname);
                   3794: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3795: 	return %loadnames;
                   3796:     }
                   3797: }
1.61      www      3798: 
1.542     raeburn  3799: # -------------------------------------------------------------------- getemails
1.648     raeburn  3800: 
1.542     raeburn  3801: =pod
                   3802: 
1.648     raeburn  3803: =item * &getemails($uname,$udom)
1.542     raeburn  3804: 
                   3805: Gets a user's email information and returns it as a hash with keys:
                   3806: notification, critnotification, permanentemail
                   3807: 
                   3808: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3809: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3810:  
1.648     raeburn  3811: 
1.542     raeburn  3812: =cut
                   3813: 
1.648     raeburn  3814: 
1.466     albertel 3815: sub getemails {
                   3816:     my ($uname,$udom)=@_;
                   3817:     if ($udom eq 'public' && $uname eq 'public') {
                   3818: 	return;
                   3819:     }
1.467     www      3820:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3821:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3822:     my $id=$uname.':'.$udom;
                   3823:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3824:     if ($cached) {
                   3825: 	return %{$names};
                   3826:     } else {
                   3827: 	my %loadnames=&Apache::lonnet::get('environment',
                   3828:                     			   ['notification','critnotification',
                   3829: 					    'permanentemail'],
                   3830: 					   $udom,$uname);
                   3831: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3832: 	return %loadnames;
                   3833:     }
                   3834: }
                   3835: 
1.551     albertel 3836: sub flush_email_cache {
                   3837:     my ($uname,$udom)=@_;
                   3838:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3839:     if (!$uname) { $uname=$env{'user.name'};   }
                   3840:     return if ($udom eq 'public' && $uname eq 'public');
                   3841:     my $id=$uname.':'.$udom;
                   3842:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3843: }
                   3844: 
1.728     raeburn  3845: # -------------------------------------------------------------------- getlangs
                   3846: 
                   3847: =pod
                   3848: 
                   3849: =item * &getlangs($uname,$udom)
                   3850: 
                   3851: Gets a user's language preference and returns it as a hash with key:
                   3852: language.
                   3853: 
                   3854: =cut
                   3855: 
                   3856: 
                   3857: sub getlangs {
                   3858:     my ($uname,$udom) = @_;
                   3859:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3860:     if (!$uname) { $uname=$env{'user.name'};   }
                   3861:     my $id=$uname.':'.$udom;
                   3862:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3863:     if ($cached) {
                   3864:         return %{$langs};
                   3865:     } else {
                   3866:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3867:                                            $udom,$uname);
                   3868:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3869:         return %loadlangs;
                   3870:     }
                   3871: }
                   3872: 
                   3873: sub flush_langs_cache {
                   3874:     my ($uname,$udom)=@_;
                   3875:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3876:     if (!$uname) { $uname=$env{'user.name'};   }
                   3877:     return if ($udom eq 'public' && $uname eq 'public');
                   3878:     my $id=$uname.':'.$udom;
                   3879:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3880: }
                   3881: 
1.61      www      3882: # ------------------------------------------------------------------ Screenname
1.81      albertel 3883: 
                   3884: =pod
                   3885: 
1.648     raeburn  3886: =item * &screenname($uname,$udom)
1.81      albertel 3887: 
                   3888: Gets a users screenname and returns it as a string
                   3889: 
                   3890: =cut
1.61      www      3891: 
                   3892: sub screenname {
                   3893:     my ($uname,$udom)=@_;
1.258     albertel 3894:     if ($uname eq $env{'user.name'} &&
                   3895: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3896:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3897:     return $names{'screenname'};
1.62      www      3898: }
                   3899: 
1.212     albertel 3900: 
1.802     bisitz   3901: # ------------------------------------------------------------- Confirm Wrapper
                   3902: =pod
                   3903: 
1.1142    raeburn  3904: =item * &confirmwrapper($message)
1.802     bisitz   3905: 
                   3906: Wrap messages about completion of operation in box
                   3907: 
                   3908: =cut
                   3909: 
                   3910: sub confirmwrapper {
                   3911:     my ($message)=@_;
                   3912:     if ($message) {
                   3913:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3914:                .$message."\n"
                   3915:                .'</div>'."\n";
                   3916:     } else {
                   3917:         return $message;
                   3918:     }
                   3919: }
                   3920: 
1.62      www      3921: # ------------------------------------------------------------- Message Wrapper
                   3922: 
                   3923: sub messagewrapper {
1.369     www      3924:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3925:     return 
1.441     albertel 3926:         '<a href="/adm/email?compose=individual&amp;'.
                   3927:         'recname='.$username.'&amp;recdom='.$domain.
                   3928: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3929:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3930: }
1.802     bisitz   3931: 
1.74      www      3932: # --------------------------------------------------------------- Notes Wrapper
                   3933: 
                   3934: sub noteswrapper {
                   3935:     my ($link,$un,$do)=@_;
                   3936:     return 
1.896     amueller 3937: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3938: }
1.802     bisitz   3939: 
1.62      www      3940: # ------------------------------------------------------------- Aboutme Wrapper
                   3941: 
                   3942: sub aboutmewrapper {
1.1070    raeburn  3943:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3944:     if (!defined($username)  && !defined($domain)) {
                   3945:         return;
                   3946:     }
1.1096    raeburn  3947:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3948: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3949: }
                   3950: 
                   3951: # ------------------------------------------------------------ Syllabus Wrapper
                   3952: 
                   3953: sub syllabuswrapper {
1.707     bisitz   3954:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3955:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3956: }
1.14      harris41 3957: 
1.802     bisitz   3958: # -----------------------------------------------------------------------------
                   3959: 
1.208     matthew  3960: sub track_student_link {
1.887     raeburn  3961:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3962:     my $link ="/adm/trackstudent?";
1.208     matthew  3963:     my $title = 'View recent activity';
                   3964:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3965:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3966:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3967:         $title .= ' of this student';
1.268     albertel 3968:     } 
1.208     matthew  3969:     if (defined($target) && $target !~ /^\s*$/) {
                   3970:         $target = qq{target="$target"};
                   3971:     } else {
                   3972:         $target = '';
                   3973:     }
1.268     albertel 3974:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3975:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3976:     $title = &mt($title);
                   3977:     $linktext = &mt($linktext);
1.448     albertel 3978:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3979: 	&help_open_topic('View_recent_activity');
1.208     matthew  3980: }
                   3981: 
1.781     raeburn  3982: sub slot_reservations_link {
                   3983:     my ($linktext,$sname,$sdom,$target) = @_;
                   3984:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3985:     my $title = 'View slot reservation history';
                   3986:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3987:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3988:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3989:         $title .= ' of this student';
                   3990:     }
                   3991:     if (defined($target) && $target !~ /^\s*$/) {
                   3992:         $target = qq{target="$target"};
                   3993:     } else {
                   3994:         $target = '';
                   3995:     }
                   3996:     $title = &mt($title);
                   3997:     $linktext = &mt($linktext);
                   3998:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3999: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4000: 
                   4001: }
                   4002: 
1.508     www      4003: # ===================================================== Display a student photo
                   4004: 
                   4005: 
1.509     albertel 4006: sub student_image_tag {
1.508     www      4007:     my ($domain,$user)=@_;
                   4008:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4009:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4010: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4011:     } else {
                   4012: 	return '';
                   4013:     }
                   4014: }
                   4015: 
1.112     bowersj2 4016: =pod
                   4017: 
                   4018: =back
                   4019: 
                   4020: =head1 Access .tab File Data
                   4021: 
                   4022: =over 4
                   4023: 
1.648     raeburn  4024: =item * &languageids() 
1.112     bowersj2 4025: 
                   4026: returns list of all language ids
                   4027: 
                   4028: =cut
                   4029: 
1.14      harris41 4030: sub languageids {
1.16      harris41 4031:     return sort(keys(%language));
1.14      harris41 4032: }
                   4033: 
1.112     bowersj2 4034: =pod
                   4035: 
1.648     raeburn  4036: =item * &languagedescription() 
1.112     bowersj2 4037: 
                   4038: returns description of a specified language id
                   4039: 
                   4040: =cut
                   4041: 
1.14      harris41 4042: sub languagedescription {
1.125     www      4043:     my $code=shift;
                   4044:     return  ($supported_language{$code}?'* ':'').
                   4045:             $language{$code}.
1.126     www      4046: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4047: }
                   4048: 
1.1048    foxr     4049: =pod
                   4050: 
                   4051: =item * &plainlanguagedescription
                   4052: 
                   4053: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4054: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4055: 
                   4056: =cut
                   4057: 
1.145     www      4058: sub plainlanguagedescription {
                   4059:     my $code=shift;
                   4060:     return $language{$code};
                   4061: }
                   4062: 
1.1048    foxr     4063: =pod
                   4064: 
                   4065: =item * &supportedlanguagecode
                   4066: 
                   4067: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4068: code.
                   4069: 
                   4070: =cut
                   4071: 
1.145     www      4072: sub supportedlanguagecode {
                   4073:     my $code=shift;
                   4074:     return $supported_language{$code};
1.97      www      4075: }
                   4076: 
1.112     bowersj2 4077: =pod
                   4078: 
1.1048    foxr     4079: =item * &latexlanguage()
                   4080: 
                   4081: Given a language key code returns the correspondnig language to use
                   4082: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4083: is no supported hyphenation for the language code.
                   4084: 
                   4085: =cut
                   4086: 
                   4087: sub latexlanguage {
                   4088:     my $code = shift;
                   4089:     return $latex_language{$code};
                   4090: }
                   4091: 
                   4092: =pod
                   4093: 
                   4094: =item * &latexhyphenation()
                   4095: 
                   4096: Same as above but what's supplied is the language as it might be stored
                   4097: in the metadata.
                   4098: 
                   4099: =cut
                   4100: 
                   4101: sub latexhyphenation {
                   4102:     my $key = shift;
                   4103:     return $latex_language_bykey{$key};
                   4104: }
                   4105: 
                   4106: =pod
                   4107: 
1.648     raeburn  4108: =item * &copyrightids() 
1.112     bowersj2 4109: 
                   4110: returns list of all copyrights
                   4111: 
                   4112: =cut
                   4113: 
                   4114: sub copyrightids {
                   4115:     return sort(keys(%cprtag));
                   4116: }
                   4117: 
                   4118: =pod
                   4119: 
1.648     raeburn  4120: =item * &copyrightdescription() 
1.112     bowersj2 4121: 
                   4122: returns description of a specified copyright id
                   4123: 
                   4124: =cut
                   4125: 
                   4126: sub copyrightdescription {
1.166     www      4127:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4128: }
1.197     matthew  4129: 
                   4130: =pod
                   4131: 
1.648     raeburn  4132: =item * &source_copyrightids() 
1.192     taceyjo1 4133: 
                   4134: returns list of all source copyrights
                   4135: 
                   4136: =cut
                   4137: 
                   4138: sub source_copyrightids {
                   4139:     return sort(keys(%scprtag));
                   4140: }
                   4141: 
                   4142: =pod
                   4143: 
1.648     raeburn  4144: =item * &source_copyrightdescription() 
1.192     taceyjo1 4145: 
                   4146: returns description of a specified source copyright id
                   4147: 
                   4148: =cut
                   4149: 
                   4150: sub source_copyrightdescription {
                   4151:     return &mt($scprtag{shift(@_)});
                   4152: }
1.112     bowersj2 4153: 
                   4154: =pod
                   4155: 
1.648     raeburn  4156: =item * &filecategories() 
1.112     bowersj2 4157: 
                   4158: returns list of all file categories
                   4159: 
                   4160: =cut
                   4161: 
                   4162: sub filecategories {
                   4163:     return sort(keys(%category_extensions));
                   4164: }
                   4165: 
                   4166: =pod
                   4167: 
1.648     raeburn  4168: =item * &filecategorytypes() 
1.112     bowersj2 4169: 
                   4170: returns list of file types belonging to a given file
                   4171: category
                   4172: 
                   4173: =cut
                   4174: 
                   4175: sub filecategorytypes {
1.356     albertel 4176:     my ($cat) = @_;
1.1248    raeburn  4177:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4178:         return @{$category_extensions{lc($cat)}};
                   4179:     } else {
                   4180:         return ();
                   4181:     }
1.112     bowersj2 4182: }
                   4183: 
                   4184: =pod
                   4185: 
1.648     raeburn  4186: =item * &fileembstyle() 
1.112     bowersj2 4187: 
                   4188: returns embedding style for a specified file type
                   4189: 
                   4190: =cut
                   4191: 
                   4192: sub fileembstyle {
                   4193:     return $fe{lc(shift(@_))};
1.169     www      4194: }
                   4195: 
1.351     www      4196: sub filemimetype {
                   4197:     return $fm{lc(shift(@_))};
                   4198: }
                   4199: 
1.169     www      4200: 
                   4201: sub filecategoryselect {
                   4202:     my ($name,$value)=@_;
1.189     matthew  4203:     return &select_form($value,$name,
1.970     raeburn  4204:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4205: }
                   4206: 
                   4207: =pod
                   4208: 
1.648     raeburn  4209: =item * &filedescription() 
1.112     bowersj2 4210: 
                   4211: returns description for a specified file type
                   4212: 
                   4213: =cut
                   4214: 
                   4215: sub filedescription {
1.188     matthew  4216:     my $file_description = $fd{lc(shift())};
                   4217:     $file_description =~ s:([\[\]]):~$1:g;
                   4218:     return &mt($file_description);
1.112     bowersj2 4219: }
                   4220: 
                   4221: =pod
                   4222: 
1.648     raeburn  4223: =item * &filedescriptionex() 
1.112     bowersj2 4224: 
                   4225: returns description for a specified file type with
                   4226: extra formatting
                   4227: 
                   4228: =cut
                   4229: 
                   4230: sub filedescriptionex {
                   4231:     my $ex=shift;
1.188     matthew  4232:     my $file_description = $fd{lc($ex)};
                   4233:     $file_description =~ s:([\[\]]):~$1:g;
                   4234:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4235: }
                   4236: 
                   4237: # End of .tab access
                   4238: =pod
                   4239: 
                   4240: =back
                   4241: 
                   4242: =cut
                   4243: 
                   4244: # ------------------------------------------------------------------ File Types
                   4245: sub fileextensions {
                   4246:     return sort(keys(%fe));
                   4247: }
                   4248: 
1.97      www      4249: # ----------------------------------------------------------- Display Languages
                   4250: # returns a hash with all desired display languages
                   4251: #
                   4252: 
                   4253: sub display_languages {
                   4254:     my %languages=();
1.695     raeburn  4255:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4256: 	$languages{$lang}=1;
1.97      www      4257:     }
                   4258:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4259:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4260: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4261: 	    $languages{$lang}=1;
1.97      www      4262:         }
                   4263:     }
                   4264:     return %languages;
1.14      harris41 4265: }
                   4266: 
1.582     albertel 4267: sub languages {
                   4268:     my ($possible_langs) = @_;
1.695     raeburn  4269:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4270:     if (!ref($possible_langs)) {
                   4271: 	if( wantarray ) {
                   4272: 	    return @preferred_langs;
                   4273: 	} else {
                   4274: 	    return $preferred_langs[0];
                   4275: 	}
                   4276:     }
                   4277:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4278:     my @preferred_possibilities;
                   4279:     foreach my $preferred_lang (@preferred_langs) {
                   4280: 	if (exists($possibilities{$preferred_lang})) {
                   4281: 	    push(@preferred_possibilities, $preferred_lang);
                   4282: 	}
                   4283:     }
                   4284:     if( wantarray ) {
                   4285: 	return @preferred_possibilities;
                   4286:     }
                   4287:     return $preferred_possibilities[0];
                   4288: }
                   4289: 
1.742     raeburn  4290: sub user_lang {
                   4291:     my ($touname,$toudom,$fromcid) = @_;
                   4292:     my @userlangs;
                   4293:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4294:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4295:                     $env{'course.'.$fromcid.'.languages'}));
                   4296:     } else {
                   4297:         my %langhash = &getlangs($touname,$toudom);
                   4298:         if ($langhash{'languages'} ne '') {
                   4299:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4300:         } else {
                   4301:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4302:             if ($domdefs{'lang_def'} ne '') {
                   4303:                 @userlangs = ($domdefs{'lang_def'});
                   4304:             }
                   4305:         }
                   4306:     }
                   4307:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4308:     my $user_lh = Apache::localize->get_handle(@languages);
                   4309:     return $user_lh;
                   4310: }
                   4311: 
                   4312: 
1.112     bowersj2 4313: ###############################################################
                   4314: ##               Student Answer Attempts                     ##
                   4315: ###############################################################
                   4316: 
                   4317: =pod
                   4318: 
                   4319: =head1 Alternate Problem Views
                   4320: 
                   4321: =over 4
                   4322: 
1.648     raeburn  4323: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4324:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4325: 
                   4326: Return string with previous attempt on problem. Arguments:
                   4327: 
                   4328: =over 4
                   4329: 
                   4330: =item * $symb: Problem, including path
                   4331: 
                   4332: =item * $username: username of the desired student
                   4333: 
                   4334: =item * $domain: domain of the desired student
1.14      harris41 4335: 
1.112     bowersj2 4336: =item * $course: Course ID
1.14      harris41 4337: 
1.112     bowersj2 4338: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4339:     something
1.14      harris41 4340: 
1.112     bowersj2 4341: =item * $regexp: if string matches this regexp, the string will be
                   4342:     sent to $gradesub
1.14      harris41 4343: 
1.112     bowersj2 4344: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4345: 
1.1199    raeburn  4346: =item * $usec: section of the desired student
                   4347: 
                   4348: =item * $identifier: counter for student (multiple students one problem) or 
                   4349:     problem (one student; whole sequence).
                   4350: 
1.112     bowersj2 4351: =back
1.14      harris41 4352: 
1.112     bowersj2 4353: The output string is a table containing all desired attempts, if any.
1.16      harris41 4354: 
1.112     bowersj2 4355: =cut
1.1       albertel 4356: 
                   4357: sub get_previous_attempt {
1.1199    raeburn  4358:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4359:   my $prevattempts='';
1.43      ng       4360:   no strict 'refs';
1.1       albertel 4361:   if ($symb) {
1.3       albertel 4362:     my (%returnhash)=
                   4363:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4364:     if ($returnhash{'version'}) {
                   4365:       my %lasthash=();
                   4366:       my $version;
                   4367:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4368:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4369:             if ($key =~ /\.rawrndseed$/) {
                   4370:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4371:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4372:             } else {
                   4373:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4374:             }
1.19      harris41 4375:         }
1.1       albertel 4376:       }
1.596     albertel 4377:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4378:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4379:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4380:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4381:       foreach my $key (sort(keys(%lasthash))) {
                   4382: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4383: 	if ($#parts > 0) {
1.31      albertel 4384: 	  my $data=$parts[-1];
1.989     raeburn  4385:           next if ($data eq 'foilorder');
1.31      albertel 4386: 	  pop(@parts);
1.1010    www      4387:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4388:           if ($data eq 'type') {
                   4389:               unless ($showsurv) {
                   4390:                   my $id = join(',',@parts);
                   4391:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4392:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4393:                       $lasthidden{$ign.'.'.$id} = 1;
                   4394:                   }
1.945     raeburn  4395:               }
1.1199    raeburn  4396:               if ($identifier ne '') {
                   4397:                   my $id = join(',',@parts);
                   4398:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4399:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4400:                       $hidestatus{$ign.'.'.$id} = 1;
                   4401:                   }
                   4402:               }
                   4403:           } elsif ($data eq 'regrader') {
                   4404:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4405:                   my $id = join(',',@parts);
                   4406:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4407:               }
1.1010    www      4408:           } 
1.31      albertel 4409: 	} else {
1.41      ng       4410: 	  if ($#parts == 0) {
                   4411: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4412: 	  } else {
                   4413: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4414: 	  }
1.31      albertel 4415: 	}
1.16      harris41 4416:       }
1.596     albertel 4417:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4418:       if ($getattempt eq '') {
1.1199    raeburn  4419:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4420:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4421:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4422:                 foreach my $id (keys(%regraded)) {
                   4423:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4424:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4425:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4426:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4427:                     }
                   4428:                 }
                   4429:             }
1.1200    raeburn  4430:         }
                   4431: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4432:             my (@hidden,@unsolved);
1.945     raeburn  4433:             if (%typeparts) {
                   4434:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4435:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4436:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4437:                         push(@hidden,$id);
1.1199    raeburn  4438:                     } elsif ($identifier ne '') {
                   4439:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4440:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4441:                                 ($hidestatus{$id})) {
1.1200    raeburn  4442:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4443:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4444:                                 push(@{$solved{$id}},$version);
                   4445:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4446:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4447:                                 my $skip;
                   4448:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4449:                                     foreach my $reset (@{$resets{$id}}) {
                   4450:                                         if ($reset > $solved{$id}[-1]) {
                   4451:                                             $skip=1;
                   4452:                                             last;
                   4453:                                         }
                   4454:                                     }
                   4455:                                 }
                   4456:                                 unless ($skip) {
                   4457:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4458:                                     push(@unsolved,$partslist);
                   4459:                                 }
                   4460:                             }
                   4461:                         }
1.945     raeburn  4462:                     }
                   4463:                 }
                   4464:             }
                   4465:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4466:                            '<td>'.&mt('Transaction [_1]',$version);
                   4467:             if (@unsolved) {
                   4468:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4469:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4470:                                  &mt('Hide').'</label></span>';
                   4471:             }
                   4472:             $prevattempts .= '</td>';
1.945     raeburn  4473:             if (@hidden) {
                   4474:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4475:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4476:                     my $hide;
                   4477:                     foreach my $id (@hidden) {
                   4478:                         if ($key =~ /^\Q$id\E/) {
                   4479:                             $hide = 1;
                   4480:                             last;
                   4481:                         }
                   4482:                     }
                   4483:                     if ($hide) {
                   4484:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4485:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4486:                             my $value = &format_previous_attempt_value($key,
                   4487:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4488:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4489:                         } else {
                   4490:                             $prevattempts.='<td>&nbsp;</td>';
                   4491:                         }
                   4492:                     } else {
                   4493:                         if ($key =~ /\./) {
1.1212    raeburn  4494:                             my $value = $returnhash{$version.':'.$key};
                   4495:                             if ($key =~ /\.rndseed$/) {
                   4496:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4497:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4498:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4499:                                 }
                   4500:                             }
                   4501:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4502:                                            '&nbsp;</td>';
1.945     raeburn  4503:                         } else {
                   4504:                             $prevattempts.='<td>&nbsp;</td>';
                   4505:                         }
                   4506:                     }
                   4507:                 }
                   4508:             } else {
                   4509: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4510:                     next if ($key =~ /\.foilorder$/);
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: 	        }
                   4521:             }
                   4522: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4523: 	 }
1.1       albertel 4524:       }
1.945     raeburn  4525:       my @currhidden = keys(%lasthidden);
1.596     albertel 4526:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4527:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4528:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4529:           if (%typeparts) {
                   4530:               my $hidden;
                   4531:               foreach my $id (@currhidden) {
                   4532:                   if ($key =~ /^\Q$id\E/) {
                   4533:                       $hidden = 1;
                   4534:                       last;
                   4535:                   }
                   4536:               }
                   4537:               if ($hidden) {
                   4538:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4539:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4540:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4541:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4542:                           $value = &$gradesub($value);
                   4543:                       }
1.1173    kruse    4544:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4545:                   } else {
                   4546:                       $prevattempts.='<td>&nbsp;</td>';
                   4547:                   }
                   4548:               } else {
                   4549:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4550:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4551:                       $value = &$gradesub($value);
                   4552:                   }
1.1173    kruse    4553:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4554:               }
                   4555:           } else {
                   4556: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4557: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4558:                   $value = &$gradesub($value);
                   4559:               }
1.1173    kruse    4560: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4561:           }
1.16      harris41 4562:       }
1.596     albertel 4563:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4564:     } else {
1.596     albertel 4565:       $prevattempts=
                   4566: 	  &start_data_table().&start_data_table_row().
                   4567: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4568: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4569:     }
                   4570:   } else {
1.596     albertel 4571:     $prevattempts=
                   4572: 	  &start_data_table().&start_data_table_row().
                   4573: 	  '<td>'.&mt('No data.').'</td>'.
                   4574: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4575:   }
1.10      albertel 4576: }
                   4577: 
1.581     albertel 4578: sub format_previous_attempt_value {
                   4579:     my ($key,$value) = @_;
1.1011    www      4580:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4581:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4582:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4583:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4584:     } elsif ($key =~ /answerstring$/) {
                   4585:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4586:         my @answer = %answers;
                   4587:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4588:         my @anskeys = sort(keys(%answers));
                   4589:         if (@anskeys == 1) {
                   4590:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4591:             if ($answer =~ m{\0}) {
                   4592:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4593:             }
                   4594:             my $tag_internal_answer_name = 'INTERNAL';
                   4595:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4596:                 $value = $answer; 
                   4597:             } else {
                   4598:                 $value = $anskeys[0].'='.$answer;
                   4599:             }
                   4600:         } else {
                   4601:             foreach my $ans (@anskeys) {
                   4602:                 my $answer = $answers{$ans};
1.1001    raeburn  4603:                 if ($answer =~ m{\0}) {
                   4604:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4605:                 }
                   4606:                 $value .=  $ans.'='.$answer.'<br />';;
                   4607:             } 
                   4608:         }
1.581     albertel 4609:     } else {
1.1173    kruse    4610:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4611:     }
                   4612:     return $value;
                   4613: }
                   4614: 
                   4615: 
1.107     albertel 4616: sub relative_to_absolute {
                   4617:     my ($url,$output)=@_;
                   4618:     my $parser=HTML::TokeParser->new(\$output);
                   4619:     my $token;
                   4620:     my $thisdir=$url;
                   4621:     my @rlinks=();
                   4622:     while ($token=$parser->get_token) {
                   4623: 	if ($token->[0] eq 'S') {
                   4624: 	    if ($token->[1] eq 'a') {
                   4625: 		if ($token->[2]->{'href'}) {
                   4626: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4627: 		}
                   4628: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4629: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4630: 	    } elsif ($token->[1] eq 'base') {
                   4631: 		$thisdir=$token->[2]->{'href'};
                   4632: 	    }
                   4633: 	}
                   4634:     }
                   4635:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4636:     foreach my $link (@rlinks) {
1.726     raeburn  4637: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4638: 		($link=~/^\//) ||
                   4639: 		($link=~/^javascript:/i) ||
                   4640: 		($link=~/^mailto:/i) ||
                   4641: 		($link=~/^\#/)) {
                   4642: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4643: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4644: 	}
                   4645:     }
                   4646: # -------------------------------------------------- Deal with Applet codebases
                   4647:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4648:     return $output;
                   4649: }
                   4650: 
1.112     bowersj2 4651: =pod
                   4652: 
1.648     raeburn  4653: =item * &get_student_view()
1.112     bowersj2 4654: 
                   4655: show a snapshot of what student was looking at
                   4656: 
                   4657: =cut
                   4658: 
1.10      albertel 4659: sub get_student_view {
1.186     albertel 4660:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4661:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4662:   my (%form);
1.10      albertel 4663:   my @elements=('symb','courseid','domain','username');
                   4664:   foreach my $element (@elements) {
1.186     albertel 4665:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4666:   }
1.186     albertel 4667:   if (defined($moreenv)) {
                   4668:       %form=(%form,%{$moreenv});
                   4669:   }
1.236     albertel 4670:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4671:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4672:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4673:   $userview=~s/\<body[^\>]*\>//gi;
                   4674:   $userview=~s/\<\/body\>//gi;
                   4675:   $userview=~s/\<html\>//gi;
                   4676:   $userview=~s/\<\/html\>//gi;
                   4677:   $userview=~s/\<head\>//gi;
                   4678:   $userview=~s/\<\/head\>//gi;
                   4679:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4680:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4681:   if (wantarray) {
                   4682:      return ($userview,$response);
                   4683:   } else {
                   4684:      return $userview;
                   4685:   }
                   4686: }
                   4687: 
                   4688: sub get_student_view_with_retries {
                   4689:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4690: 
                   4691:     my $ok = 0;                 # True if we got a good response.
                   4692:     my $content;
                   4693:     my $response;
                   4694: 
                   4695:     # Try to get the student_view done. within the retries count:
                   4696:     
                   4697:     do {
                   4698:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4699:          $ok      = $response->is_success;
                   4700:          if (!$ok) {
                   4701:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4702:          }
                   4703:          $retries--;
                   4704:     } while (!$ok && ($retries > 0));
                   4705:     
                   4706:     if (!$ok) {
                   4707:        $content = '';          # On error return an empty content.
                   4708:     }
1.651     www      4709:     if (wantarray) {
                   4710:        return ($content, $response);
                   4711:     } else {
                   4712:        return $content;
                   4713:     }
1.11      albertel 4714: }
                   4715: 
1.112     bowersj2 4716: =pod
                   4717: 
1.648     raeburn  4718: =item * &get_student_answers() 
1.112     bowersj2 4719: 
                   4720: show a snapshot of how student was answering problem
                   4721: 
                   4722: =cut
                   4723: 
1.11      albertel 4724: sub get_student_answers {
1.100     sakharuk 4725:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4726:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4727:   my (%moreenv);
1.11      albertel 4728:   my @elements=('symb','courseid','domain','username');
                   4729:   foreach my $element (@elements) {
1.186     albertel 4730:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4731:   }
1.186     albertel 4732:   $moreenv{'grade_target'}='answer';
                   4733:   %moreenv=(%form,%moreenv);
1.497     raeburn  4734:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4735:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4736:   return $userview;
1.1       albertel 4737: }
1.116     albertel 4738: 
                   4739: =pod
                   4740: 
                   4741: =item * &submlink()
                   4742: 
1.242     albertel 4743: Inputs: $text $uname $udom $symb $target
1.116     albertel 4744: 
                   4745: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4746: 
                   4747: =cut
                   4748: 
                   4749: ###############################################
                   4750: sub submlink {
1.242     albertel 4751:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4752:     if (!($uname && $udom)) {
                   4753: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4754: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4755: 	if (!$symb) { $symb=$cursymb; }
                   4756:     }
1.254     matthew  4757:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4758:     $symb=&escape($symb);
1.960     bisitz   4759:     if ($target) { $target=" target=\"$target\""; }
                   4760:     return
                   4761:         '<a href="/adm/grades?command=submission'.
                   4762:         '&amp;symb='.$symb.
                   4763:         '&amp;student='.$uname.
                   4764:         '&amp;userdom='.$udom.'"'.
                   4765:         $target.'>'.$text.'</a>';
1.242     albertel 4766: }
                   4767: ##############################################
                   4768: 
                   4769: =pod
                   4770: 
                   4771: =item * &pgrdlink()
                   4772: 
                   4773: Inputs: $text $uname $udom $symb $target
                   4774: 
                   4775: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4776: 
                   4777: =cut
                   4778: 
                   4779: ###############################################
                   4780: sub pgrdlink {
                   4781:     my $link=&submlink(@_);
                   4782:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4783:     return $link;
                   4784: }
                   4785: ##############################################
                   4786: 
                   4787: =pod
                   4788: 
                   4789: =item * &pprmlink()
                   4790: 
                   4791: Inputs: $text $uname $udom $symb $target
                   4792: 
                   4793: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4794: student and a specific resource
1.242     albertel 4795: 
                   4796: =cut
                   4797: 
                   4798: ###############################################
                   4799: sub pprmlink {
                   4800:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4801:     if (!($uname && $udom)) {
                   4802: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4803: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4804: 	if (!$symb) { $symb=$cursymb; }
                   4805:     }
1.254     matthew  4806:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4807:     $symb=&escape($symb);
1.242     albertel 4808:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4809:     return '<a href="/adm/parmset?command=set&amp;'.
                   4810: 	'symb='.$symb.'&amp;uname='.$uname.
                   4811: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4812: }
                   4813: ##############################################
1.37      matthew  4814: 
1.112     bowersj2 4815: =pod
                   4816: 
                   4817: =back
                   4818: 
                   4819: =cut
                   4820: 
1.37      matthew  4821: ###############################################
1.51      www      4822: 
                   4823: 
                   4824: sub timehash {
1.687     raeburn  4825:     my ($thistime) = @_;
                   4826:     my $timezone = &Apache::lonlocal::gettimezone();
                   4827:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4828:                      ->set_time_zone($timezone);
                   4829:     my $wday = $dt->day_of_week();
                   4830:     if ($wday == 7) { $wday = 0; }
                   4831:     return ( 'second' => $dt->second(),
                   4832:              'minute' => $dt->minute(),
                   4833:              'hour'   => $dt->hour(),
                   4834:              'day'     => $dt->day_of_month(),
                   4835:              'month'   => $dt->month(),
                   4836:              'year'    => $dt->year(),
                   4837:              'weekday' => $wday,
                   4838:              'dayyear' => $dt->day_of_year(),
                   4839:              'dlsav'   => $dt->is_dst() );
1.51      www      4840: }
                   4841: 
1.370     www      4842: sub utc_string {
                   4843:     my ($date)=@_;
1.371     www      4844:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4845: }
                   4846: 
1.51      www      4847: sub maketime {
                   4848:     my %th=@_;
1.687     raeburn  4849:     my ($epoch_time,$timezone,$dt);
                   4850:     $timezone = &Apache::lonlocal::gettimezone();
                   4851:     eval {
                   4852:         $dt = DateTime->new( year   => $th{'year'},
                   4853:                              month  => $th{'month'},
                   4854:                              day    => $th{'day'},
                   4855:                              hour   => $th{'hour'},
                   4856:                              minute => $th{'minute'},
                   4857:                              second => $th{'second'},
                   4858:                              time_zone => $timezone,
                   4859:                          );
                   4860:     };
                   4861:     if (!$@) {
                   4862:         $epoch_time = $dt->epoch;
                   4863:         if ($epoch_time) {
                   4864:             return $epoch_time;
                   4865:         }
                   4866:     }
1.51      www      4867:     return POSIX::mktime(
                   4868:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4869:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4870: }
                   4871: 
                   4872: #########################################
1.51      www      4873: 
                   4874: sub findallcourses {
1.482     raeburn  4875:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4876:     my %roles;
                   4877:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4878:     my %courses;
1.51      www      4879:     my $now=time;
1.482     raeburn  4880:     if (!defined($uname)) {
                   4881:         $uname = $env{'user.name'};
                   4882:     }
                   4883:     if (!defined($udom)) {
                   4884:         $udom = $env{'user.domain'};
                   4885:     }
                   4886:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4887:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4888:         if (!%roles) {
                   4889:             %roles = (
                   4890:                        cc => 1,
1.907     raeburn  4891:                        co => 1,
1.482     raeburn  4892:                        in => 1,
                   4893:                        ep => 1,
                   4894:                        ta => 1,
                   4895:                        cr => 1,
                   4896:                        st => 1,
                   4897:              );
                   4898:         }
                   4899:         foreach my $entry (keys(%roleshash)) {
                   4900:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4901:             if ($trole =~ /^cr/) { 
                   4902:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4903:             } else {
                   4904:                 next if (!exists($roles{$trole}));
                   4905:             }
                   4906:             if ($tend) {
                   4907:                 next if ($tend < $now);
                   4908:             }
                   4909:             if ($tstart) {
                   4910:                 next if ($tstart > $now);
                   4911:             }
1.1058    raeburn  4912:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4913:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4914:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4915:             if ($secpart eq '') {
                   4916:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4917:                 $sec = 'none';
1.1058    raeburn  4918:                 $value .= $cnum.'/';
1.482     raeburn  4919:             } else {
                   4920:                 $cnum = $cnumpart;
                   4921:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4922:                 $value .= $cnum.'/'.$sec;
                   4923:             }
                   4924:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4925:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4926:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4927:                 }
                   4928:             } else {
                   4929:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4930:             }
1.482     raeburn  4931:         }
                   4932:     } else {
                   4933:         foreach my $key (keys(%env)) {
1.483     albertel 4934: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4935:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4936: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4937: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4938: 	        next if (%roles && !exists($roles{$role}));
                   4939: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4940:                 my $active=1;
                   4941:                 if ($starttime) {
                   4942: 		    if ($now<$starttime) { $active=0; }
                   4943:                 }
                   4944:                 if ($endtime) {
                   4945:                     if ($now>$endtime) { $active=0; }
                   4946:                 }
                   4947:                 if ($active) {
1.1058    raeburn  4948:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4949:                     if ($sec eq '') {
                   4950:                         $sec = 'none';
1.1058    raeburn  4951:                     } else {
                   4952:                         $value .= $sec;
                   4953:                     }
                   4954:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4955:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4956:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4957:                         }
                   4958:                     } else {
                   4959:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4960:                     }
1.474     raeburn  4961:                 }
                   4962:             }
1.51      www      4963:         }
                   4964:     }
1.474     raeburn  4965:     return %courses;
1.51      www      4966: }
1.37      matthew  4967: 
1.54      www      4968: ###############################################
1.474     raeburn  4969: 
                   4970: sub blockcheck {
1.1189    raeburn  4971:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4972: 
1.1189    raeburn  4973:     if (defined($udom) && defined($uname)) {
                   4974:         # If uname and udom are for a course, check for blocks in the course.
                   4975:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4976:             my ($startblock,$endblock,$triggerblock) =
                   4977:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4978:             return ($startblock,$endblock,$triggerblock);
                   4979:         }
                   4980:     } else {
1.490     raeburn  4981:         $udom = $env{'user.domain'};
                   4982:         $uname = $env{'user.name'};
                   4983:     }
                   4984: 
1.502     raeburn  4985:     my $startblock = 0;
                   4986:     my $endblock = 0;
1.1062    raeburn  4987:     my $triggerblock = '';
1.482     raeburn  4988:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4989: 
1.490     raeburn  4990:     # If uname is for a user, and activity is course-specific, i.e.,
                   4991:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4992: 
1.490     raeburn  4993:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1189    raeburn  4994:          $activity eq 'groups' || $activity eq 'printout') &&
                   4995:         ($env{'request.course.id'})) {
1.490     raeburn  4996:         foreach my $key (keys(%live_courses)) {
                   4997:             if ($key ne $env{'request.course.id'}) {
                   4998:                 delete($live_courses{$key});
                   4999:             }
                   5000:         }
                   5001:     }
                   5002: 
                   5003:     my $otheruser = 0;
                   5004:     my %own_courses;
                   5005:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5006:         # Resource belongs to user other than current user.
                   5007:         $otheruser = 1;
                   5008:         # Gather courses for current user
                   5009:         %own_courses = 
                   5010:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5011:     }
                   5012: 
                   5013:     # Gather active course roles - course coordinator, instructor, 
                   5014:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5015: 
                   5016:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5017:         my ($cdom,$cnum);
                   5018:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5019:             $cdom = $env{'course.'.$course.'.domain'};
                   5020:             $cnum = $env{'course.'.$course.'.num'};
                   5021:         } else {
1.490     raeburn  5022:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5023:         }
                   5024:         my $no_ownblock = 0;
                   5025:         my $no_userblock = 0;
1.533     raeburn  5026:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5027:             # Check if current user has 'evb' priv for this
                   5028:             if (defined($own_courses{$course})) {
                   5029:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5030:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5031:                     if ($sec ne 'none') {
                   5032:                         $checkrole .= '/'.$sec;
                   5033:                     }
                   5034:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5035:                         $no_ownblock = 1;
                   5036:                         last;
                   5037:                     }
                   5038:                 }
                   5039:             }
                   5040:             # if they have 'evb' priv and are currently not playing student
                   5041:             next if (($no_ownblock) &&
                   5042:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5043:         }
1.474     raeburn  5044:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5045:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5046:             if ($sec ne 'none') {
1.482     raeburn  5047:                 $checkrole .= '/'.$sec;
1.474     raeburn  5048:             }
1.490     raeburn  5049:             if ($otheruser) {
                   5050:                 # Resource belongs to user other than current user.
                   5051:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5052:                 my (%allroles,%userroles);
                   5053:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5054:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5055:                         my ($trole,$tdom,$tnum,$tsec);
                   5056:                         if ($entry =~ /^cr/) {
                   5057:                             ($trole,$tdom,$tnum,$tsec) = 
                   5058:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5059:                         } else {
                   5060:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5061:                         }
                   5062:                         my ($spec,$area,$trest);
                   5063:                         $area = '/'.$tdom.'/'.$tnum;
                   5064:                         $trest = $tnum;
                   5065:                         if ($tsec ne '') {
                   5066:                             $area .= '/'.$tsec;
                   5067:                             $trest .= '/'.$tsec;
                   5068:                         }
                   5069:                         $spec = $trole.'.'.$area;
                   5070:                         if ($trole =~ /^cr/) {
                   5071:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5072:                                                               $tdom,$spec,$trest,$area);
                   5073:                         } else {
                   5074:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5075:                                                                 $tdom,$spec,$trest,$area);
                   5076:                         }
                   5077:                     }
                   5078:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   5079:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5080:                         if ($1) {
                   5081:                             $no_userblock = 1;
                   5082:                             last;
                   5083:                         }
1.486     raeburn  5084:                     }
                   5085:                 }
1.490     raeburn  5086:             } else {
                   5087:                 # Resource belongs to current user
                   5088:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5089:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5090:                     $no_ownblock = 1;
                   5091:                     last;
                   5092:                 }
1.474     raeburn  5093:             }
                   5094:         }
                   5095:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5096:         next if (($no_ownblock) &&
1.491     albertel 5097:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5098:         next if ($no_userblock);
1.474     raeburn  5099: 
1.866     kalberla 5100:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  5101:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  5102:         
1.1062    raeburn  5103:         my ($start,$end,$trigger) = 
                   5104:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  5105:         if (($start != 0) && 
                   5106:             (($startblock == 0) || ($startblock > $start))) {
                   5107:             $startblock = $start;
1.1062    raeburn  5108:             if ($trigger ne '') {
                   5109:                 $triggerblock = $trigger;
                   5110:             }
1.502     raeburn  5111:         }
                   5112:         if (($end != 0)  &&
                   5113:             (($endblock == 0) || ($endblock < $end))) {
                   5114:             $endblock = $end;
1.1062    raeburn  5115:             if ($trigger ne '') {
                   5116:                 $triggerblock = $trigger;
                   5117:             }
1.502     raeburn  5118:         }
1.490     raeburn  5119:     }
1.1062    raeburn  5120:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5121: }
                   5122: 
                   5123: sub get_blocks {
1.1062    raeburn  5124:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  5125:     my $startblock = 0;
                   5126:     my $endblock = 0;
1.1062    raeburn  5127:     my $triggerblock = '';
1.490     raeburn  5128:     my $course = $cdom.'_'.$cnum;
                   5129:     $setters->{$course} = {};
                   5130:     $setters->{$course}{'staff'} = [];
                   5131:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5132:     $setters->{$course}{'triggers'} = [];
                   5133:     my (@blockers,%triggered);
                   5134:     my $now = time;
                   5135:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5136:     if ($activity eq 'docs') {
                   5137:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   5138:         foreach my $block (@blockers) {
                   5139:             if ($block =~ /^firstaccess____(.+)$/) {
                   5140:                 my $item = $1;
                   5141:                 my $type = 'map';
                   5142:                 my $timersymb = $item;
                   5143:                 if ($item eq 'course') {
                   5144:                     $type = 'course';
                   5145:                 } elsif ($item =~ /___\d+___/) {
                   5146:                     $type = 'resource';
                   5147:                 } else {
                   5148:                     $timersymb = &Apache::lonnet::symbread($item);
                   5149:                 }
                   5150:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5151:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5152:                 $triggered{$block} = {
                   5153:                                        start => $start,
                   5154:                                        end   => $end,
                   5155:                                        type  => $type,
                   5156:                                      };
                   5157:             }
                   5158:         }
                   5159:     } else {
                   5160:         foreach my $block (keys(%commblocks)) {
                   5161:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5162:                 my ($start,$end) = ($1,$2);
                   5163:                 if ($start <= time && $end >= time) {
                   5164:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5165:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5166:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5167:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5168:                                     push(@blockers,$block);
                   5169:                                 }
                   5170:                             }
                   5171:                         }
                   5172:                     }
                   5173:                 }
                   5174:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5175:                 my $item = $1;
                   5176:                 my $timersymb = $item; 
                   5177:                 my $type = 'map';
                   5178:                 if ($item eq 'course') {
                   5179:                     $type = 'course';
                   5180:                 } elsif ($item =~ /___\d+___/) {
                   5181:                     $type = 'resource';
                   5182:                 } else {
                   5183:                     $timersymb = &Apache::lonnet::symbread($item);
                   5184:                 }
                   5185:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5186:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5187:                 if ($start && $end) {
                   5188:                     if (($start <= time) && ($end >= time)) {
                   5189:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   5190:                             push(@blockers,$block);
                   5191:                             $triggered{$block} = {
                   5192:                                                    start => $start,
                   5193:                                                    end   => $end,
                   5194:                                                    type  => $type,
                   5195:                                                  };
                   5196:                         }
                   5197:                     }
1.490     raeburn  5198:                 }
1.1062    raeburn  5199:             }
                   5200:         }
                   5201:     }
                   5202:     foreach my $blocker (@blockers) {
                   5203:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5204:             &parse_block_record($commblocks{$blocker});
                   5205:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5206:         my ($start,$end,$triggertype);
                   5207:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5208:             ($start,$end) = ($1,$2);
                   5209:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5210:             $start = $triggered{$blocker}{'start'};
                   5211:             $end = $triggered{$blocker}{'end'};
                   5212:             $triggertype = $triggered{$blocker}{'type'};
                   5213:         }
                   5214:         if ($start) {
                   5215:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5216:             if ($triggertype) {
                   5217:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5218:             } else {
                   5219:                 push(@{$$setters{$course}{'triggers'}},0);
                   5220:             }
                   5221:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5222:                 $startblock = $start;
                   5223:                 if ($triggertype) {
                   5224:                     $triggerblock = $blocker;
1.474     raeburn  5225:                 }
                   5226:             }
1.1062    raeburn  5227:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5228:                $endblock = $end;
                   5229:                if ($triggertype) {
                   5230:                    $triggerblock = $blocker;
                   5231:                }
                   5232:             }
1.474     raeburn  5233:         }
                   5234:     }
1.1062    raeburn  5235:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5236: }
                   5237: 
                   5238: sub parse_block_record {
                   5239:     my ($record) = @_;
                   5240:     my ($setuname,$setudom,$title,$blocks);
                   5241:     if (ref($record) eq 'HASH') {
                   5242:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5243:         $title = &unescape($record->{'event'});
                   5244:         $blocks = $record->{'blocks'};
                   5245:     } else {
                   5246:         my @data = split(/:/,$record,3);
                   5247:         if (scalar(@data) eq 2) {
                   5248:             $title = $data[1];
                   5249:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5250:         } else {
                   5251:             ($setuname,$setudom,$title) = @data;
                   5252:         }
                   5253:         $blocks = { 'com' => 'on' };
                   5254:     }
                   5255:     return ($setuname,$setudom,$title,$blocks);
                   5256: }
                   5257: 
1.854     kalberla 5258: sub blocking_status {
1.1189    raeburn  5259:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  5260:     my %setters;
1.890     droeschl 5261: 
1.1061    raeburn  5262: # check for active blocking
1.1062    raeburn  5263:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  5264:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  5265:     my $blocked = 0;
                   5266:     if ($startblock && $endblock) {
                   5267:         $blocked = 1;
                   5268:     }
1.890     droeschl 5269: 
1.1061    raeburn  5270: # caller just wants to know whether a block is active
                   5271:     if (!wantarray) { return $blocked; }
                   5272: 
                   5273: # build a link to a popup window containing the details
                   5274:     my $querystring  = "?activity=$activity";
                   5275: # $uname and $udom decide whose portfolio the user is trying to look at
1.1232    raeburn  5276:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5277:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5278:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5279:     } elsif ($activity eq 'docs') {
                   5280:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   5281:     }
1.1061    raeburn  5282: 
                   5283:     my $output .= <<'END_MYBLOCK';
                   5284: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5285:     var options = "width=" + w + ",height=" + h + ",";
                   5286:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5287:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5288:     var newWin = window.open(url, wdwName, options);
                   5289:     newWin.focus();
                   5290: }
1.890     droeschl 5291: END_MYBLOCK
1.854     kalberla 5292: 
1.1061    raeburn  5293:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5294:   
1.1061    raeburn  5295:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5296:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5297:     my $class = 'LC_comblock';
1.1062    raeburn  5298:     if ($activity eq 'docs') {
                   5299:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5300:         $class = '';
1.1063    raeburn  5301:     } elsif ($activity eq 'printout') {
                   5302:         $text = &mt('Printing Blocked');
1.1232    raeburn  5303:     } elsif ($activity eq 'passwd') {
                   5304:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  5305:     }
1.1061    raeburn  5306:     $output .= <<"END_BLOCK";
1.1217    raeburn  5307: <div class='$class'>
1.869     kalberla 5308:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5309:   title='$text'>
                   5310:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5311:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5312:   title='$text'>$text</a>
1.867     kalberla 5313: </div>
                   5314: 
                   5315: END_BLOCK
1.474     raeburn  5316: 
1.1061    raeburn  5317:     return ($blocked, $output);
1.854     kalberla 5318: }
1.490     raeburn  5319: 
1.60      matthew  5320: ###############################################
                   5321: 
1.682     raeburn  5322: sub check_ip_acc {
1.1201    raeburn  5323:     my ($acc,$clientip)=@_;
1.682     raeburn  5324:     &Apache::lonxml::debug("acc is $acc");
                   5325:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5326:         return 1;
                   5327:     }
1.1219    raeburn  5328:     my $allowed;
1.1252    raeburn  5329:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  5330: 
                   5331:     my $name;
1.1219    raeburn  5332:     my %access = (
                   5333:                      allowfrom => 1,
                   5334:                      denyfrom  => 0,
                   5335:                  );
                   5336:     my @allows;
                   5337:     my @denies;
                   5338:     foreach my $item (split(',',$acc)) {
                   5339:         $item =~ s/^\s*//;
                   5340:         $item =~ s/\s*$//;
                   5341:         my $pattern;
                   5342:         if ($item =~ /^\!(.+)$/) {
                   5343:             push(@denies,$1);
                   5344:         } else {
                   5345:             push(@allows,$item);
                   5346:         }
                   5347:    }
                   5348:    my $numdenies = scalar(@denies);
                   5349:    my $numallows = scalar(@allows);
                   5350:    my $count = 0;
                   5351:    foreach my $pattern (@denies,@allows) {
                   5352:         $count ++; 
                   5353:         my $acctype = 'allowfrom';
                   5354:         if ($count <= $numdenies) {
                   5355:             $acctype = 'denyfrom';
                   5356:         }
1.682     raeburn  5357:         if ($pattern =~ /\*$/) {
                   5358:             #35.8.*
                   5359:             $pattern=~s/\*//;
1.1219    raeburn  5360:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5361:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5362:             #35.8.3.[34-56]
                   5363:             my $low=$2;
                   5364:             my $high=$3;
                   5365:             $pattern=$1;
                   5366:             if ($ip =~ /^\Q$pattern\E/) {
                   5367:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5368:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5369:             }
                   5370:         } elsif ($pattern =~ /^\*/) {
                   5371:             #*.msu.edu
                   5372:             $pattern=~s/\*//;
                   5373:             if (!defined($name)) {
                   5374:                 use Socket;
                   5375:                 my $netaddr=inet_aton($ip);
                   5376:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5377:             }
1.1219    raeburn  5378:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5379:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5380:             #127.0.0.1
1.1219    raeburn  5381:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5382:         } else {
                   5383:             #some.name.com
                   5384:             if (!defined($name)) {
                   5385:                 use Socket;
                   5386:                 my $netaddr=inet_aton($ip);
                   5387:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5388:             }
1.1219    raeburn  5389:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5390:         }
                   5391:         if ($allowed =~ /^(0|1)$/) { last; }
                   5392:     }
                   5393:     if ($allowed eq '') {
                   5394:         if ($numdenies && !$numallows) {
                   5395:             $allowed = 1;
                   5396:         } else {
                   5397:             $allowed = 0;
1.682     raeburn  5398:         }
                   5399:     }
                   5400:     return $allowed;
                   5401: }
                   5402: 
                   5403: ###############################################
                   5404: 
1.60      matthew  5405: =pod
                   5406: 
1.112     bowersj2 5407: =head1 Domain Template Functions
                   5408: 
                   5409: =over 4
                   5410: 
                   5411: =item * &determinedomain()
1.60      matthew  5412: 
                   5413: Inputs: $domain (usually will be undef)
                   5414: 
1.63      www      5415: Returns: Determines which domain should be used for designs
1.60      matthew  5416: 
                   5417: =cut
1.54      www      5418: 
1.60      matthew  5419: ###############################################
1.63      www      5420: sub determinedomain {
                   5421:     my $domain=shift;
1.531     albertel 5422:     if (! $domain) {
1.60      matthew  5423:         # Determine domain if we have not been given one
1.893     raeburn  5424:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5425:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5426:         if ($env{'request.role.domain'}) { 
                   5427:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5428:         }
                   5429:     }
1.63      www      5430:     return $domain;
                   5431: }
                   5432: ###############################################
1.517     raeburn  5433: 
1.518     albertel 5434: sub devalidate_domconfig_cache {
                   5435:     my ($udom)=@_;
                   5436:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5437: }
                   5438: 
                   5439: # ---------------------- Get domain configuration for a domain
                   5440: sub get_domainconf {
                   5441:     my ($udom) = @_;
                   5442:     my $cachetime=1800;
                   5443:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5444:     if (defined($cached)) { return %{$result}; }
                   5445: 
                   5446:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5447: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5448:     my (%designhash,%legacy);
1.518     albertel 5449:     if (keys(%domconfig) > 0) {
                   5450:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5451:             if (keys(%{$domconfig{'login'}})) {
                   5452:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5453:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5454:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5455:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5456:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5457:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5458:                                         if ($key eq 'loginvia') {
                   5459:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5460:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5461:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5462:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5463: 
                   5464:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5465:                                                 } else {
                   5466:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5467:                                                 }
1.948     raeburn  5468:                                             }
1.1208    raeburn  5469:                                         } elsif ($key eq 'headtag') {
                   5470:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5471:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5472:                                             }
1.946     raeburn  5473:                                         }
1.1208    raeburn  5474:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5475:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5476:                                         }
1.946     raeburn  5477:                                     }
                   5478:                                 }
                   5479:                             }
                   5480:                         } else {
                   5481:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5482:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5483:                                     $domconfig{'login'}{$key}{$img};
                   5484:                             }
1.699     raeburn  5485:                         }
                   5486:                     } else {
                   5487:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5488:                     }
1.632     raeburn  5489:                 }
                   5490:             } else {
                   5491:                 $legacy{'login'} = 1;
1.518     albertel 5492:             }
1.632     raeburn  5493:         } else {
                   5494:             $legacy{'login'} = 1;
1.518     albertel 5495:         }
                   5496:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5497:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5498:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5499:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5500:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5501:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5502:                         }
1.518     albertel 5503:                     }
                   5504:                 }
1.632     raeburn  5505:             } else {
                   5506:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5507:             }
1.632     raeburn  5508:         } else {
                   5509:             $legacy{'rolecolors'} = 1;
1.518     albertel 5510:         }
1.948     raeburn  5511:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5512:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5513:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5514:             }
                   5515:         }
1.632     raeburn  5516:         if (keys(%legacy) > 0) {
                   5517:             my %legacyhash = &get_legacy_domconf($udom);
                   5518:             foreach my $item (keys(%legacyhash)) {
                   5519:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5520:                     if ($legacy{'login'}) { 
                   5521:                         $designhash{$item} = $legacyhash{$item};
                   5522:                     }
                   5523:                 } else {
                   5524:                     if ($legacy{'rolecolors'}) {
                   5525:                         $designhash{$item} = $legacyhash{$item};
                   5526:                     }
1.518     albertel 5527:                 }
                   5528:             }
                   5529:         }
1.632     raeburn  5530:     } else {
                   5531:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5532:     }
                   5533:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5534: 				  $cachetime);
                   5535:     return %designhash;
                   5536: }
                   5537: 
1.632     raeburn  5538: sub get_legacy_domconf {
                   5539:     my ($udom) = @_;
                   5540:     my %legacyhash;
                   5541:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5542:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5543:     if (-e $designfile) {
                   5544:         if ( open (my $fh,"<$designfile") ) {
                   5545:             while (my $line = <$fh>) {
                   5546:                 next if ($line =~ /^\#/);
                   5547:                 chomp($line);
                   5548:                 my ($key,$val)=(split(/\=/,$line));
                   5549:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5550:             }
                   5551:             close($fh);
                   5552:         }
                   5553:     }
1.1026    raeburn  5554:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5555:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5556:     }
                   5557:     return %legacyhash;
                   5558: }
                   5559: 
1.63      www      5560: =pod
                   5561: 
1.112     bowersj2 5562: =item * &domainlogo()
1.63      www      5563: 
                   5564: Inputs: $domain (usually will be undef)
                   5565: 
                   5566: Returns: A link to a domain logo, if the domain logo exists.
                   5567: If the domain logo does not exist, a description of the domain.
                   5568: 
                   5569: =cut
1.112     bowersj2 5570: 
1.63      www      5571: ###############################################
                   5572: sub domainlogo {
1.517     raeburn  5573:     my $domain = &determinedomain(shift);
1.518     albertel 5574:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5575:     # See if there is a logo
                   5576:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5577:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5578:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5579: 	    if ($imgsrc =~ m{^/res/}) {
                   5580: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5581: 		&Apache::lonnet::repcopy($local_name);
                   5582: 	    }
                   5583: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5584:         } 
                   5585:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5586:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5587:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5588:     } else {
1.60      matthew  5589:         return '';
1.59      www      5590:     }
                   5591: }
1.63      www      5592: ##############################################
                   5593: 
                   5594: =pod
                   5595: 
1.112     bowersj2 5596: =item * &designparm()
1.63      www      5597: 
                   5598: Inputs: $which parameter; $domain (usually will be undef)
                   5599: 
                   5600: Returns: value of designparamter $which
                   5601: 
                   5602: =cut
1.112     bowersj2 5603: 
1.397     albertel 5604: 
1.400     albertel 5605: ##############################################
1.397     albertel 5606: sub designparm {
                   5607:     my ($which,$domain)=@_;
                   5608:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5609:         return $env{'environment.color.'.$which};
1.96      www      5610:     }
1.63      www      5611:     $domain=&determinedomain($domain);
1.1016    raeburn  5612:     my %domdesign;
                   5613:     unless ($domain eq 'public') {
                   5614:         %domdesign = &get_domainconf($domain);
                   5615:     }
1.520     raeburn  5616:     my $output;
1.517     raeburn  5617:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5618:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5619:     } else {
1.520     raeburn  5620:         $output = $defaultdesign{$which};
                   5621:     }
                   5622:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5623:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5624:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5625:             if ($output =~ m{^/res/}) {
                   5626:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5627:                 &Apache::lonnet::repcopy($local_name);
                   5628:             }
1.520     raeburn  5629:             $output = &lonhttpdurl($output);
                   5630:         }
1.63      www      5631:     }
1.520     raeburn  5632:     return $output;
1.63      www      5633: }
1.59      www      5634: 
1.822     bisitz   5635: ##############################################
                   5636: =pod
                   5637: 
1.832     bisitz   5638: =item * &authorspace()
                   5639: 
1.1028    raeburn  5640: Inputs: $url (usually will be undef).
1.832     bisitz   5641: 
1.1132    raeburn  5642: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5643:          directory being viewed (or for which action is being taken). 
                   5644:          If $url is provided, and begins /priv/<domain>/<uname>
                   5645:          the path will be that portion of the $context argument.
                   5646:          Otherwise the path will be for the author space of the current
                   5647:          user when the current role is author, or for that of the 
                   5648:          co-author/assistant co-author space when the current role 
                   5649:          is co-author or assistant co-author.
1.832     bisitz   5650: 
                   5651: =cut
                   5652: 
                   5653: sub authorspace {
1.1028    raeburn  5654:     my ($url) = @_;
                   5655:     if ($url ne '') {
                   5656:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5657:            return $1;
                   5658:         }
                   5659:     }
1.832     bisitz   5660:     my $caname = '';
1.1024    www      5661:     my $cadom = '';
1.1028    raeburn  5662:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5663:         ($cadom,$caname) =
1.832     bisitz   5664:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5665:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5666:         $caname = $env{'user.name'};
1.1024    www      5667:         $cadom = $env{'user.domain'};
1.832     bisitz   5668:     }
1.1028    raeburn  5669:     if (($caname ne '') && ($cadom ne '')) {
                   5670:         return "/priv/$cadom/$caname/";
                   5671:     }
                   5672:     return;
1.832     bisitz   5673: }
                   5674: 
                   5675: ##############################################
                   5676: =pod
                   5677: 
1.822     bisitz   5678: =item * &head_subbox()
                   5679: 
                   5680: Inputs: $content (contains HTML code with page functions, etc.)
                   5681: 
                   5682: Returns: HTML div with $content
                   5683:          To be included in page header
                   5684: 
                   5685: =cut
                   5686: 
                   5687: sub head_subbox {
                   5688:     my ($content)=@_;
                   5689:     my $output =
1.993     raeburn  5690:         '<div class="LC_head_subbox">'
1.822     bisitz   5691:        .$content
                   5692:        .'</div>'
                   5693: }
                   5694: 
                   5695: ##############################################
                   5696: =pod
                   5697: 
                   5698: =item * &CSTR_pageheader()
                   5699: 
1.1026    raeburn  5700: Input: (optional) filename from which breadcrumb trail is built.
                   5701:        In most cases no input as needed, as $env{'request.filename'}
                   5702:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5703: 
                   5704: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5705:          To be included on Authoring Space pages
1.822     bisitz   5706: 
                   5707: =cut
                   5708: 
                   5709: sub CSTR_pageheader {
1.1026    raeburn  5710:     my ($trailfile) = @_;
                   5711:     if ($trailfile eq '') {
                   5712:         $trailfile = $env{'request.filename'};
                   5713:     }
                   5714: 
                   5715: # this is for resources; directories have customtitle, and crumbs
                   5716: # and select recent are created in lonpubdir.pm
                   5717: 
                   5718:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5719:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5720:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5721:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5722:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5723: 
                   5724:     my $parentpath = '';
                   5725:     my $lastitem = '';
                   5726:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5727:         $parentpath = $1;
                   5728:         $lastitem = $2;
                   5729:     } else {
                   5730:         $lastitem = $thisdisfn;
                   5731:     }
1.921     bisitz   5732: 
1.1246    raeburn  5733:     my ($crsauthor,$title);
                   5734:     if (($env{'request.course.id'}) &&
                   5735:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  5736:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  5737:         $crsauthor = 1;
                   5738:         $title = &mt('Course Authoring Space');
                   5739:     } else {
                   5740:         $title = &mt('Authoring Space');
                   5741:     }
                   5742: 
1.921     bisitz   5743:     my $output =
1.822     bisitz   5744:          '<div>'
                   5745:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  5746:         .'<b>'.$title.'</b> '
1.822     bisitz   5747:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5748:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5749:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5750: 
                   5751:     if ($lastitem) {
                   5752:         $output .=
                   5753:              '<span class="LC_filename">'
                   5754:             .$lastitem
                   5755:             .'</span>';
                   5756:     }
1.1245    raeburn  5757: 
1.1246    raeburn  5758:     if ($crsauthor) {
                   5759:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   5760:     } else {
                   5761:         $output .=
                   5762:              '<br />'
                   5763:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5764:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5765:             .'</form>'
                   5766:             .&Apache::lonmenu::constspaceform();
                   5767:     }
                   5768:     $output .= '</div>';
1.921     bisitz   5769: 
                   5770:     return $output;
1.822     bisitz   5771: }
                   5772: 
1.60      matthew  5773: ###############################################
                   5774: ###############################################
                   5775: 
                   5776: =pod
                   5777: 
1.112     bowersj2 5778: =back
                   5779: 
1.549     albertel 5780: =head1 HTML Helpers
1.112     bowersj2 5781: 
                   5782: =over 4
                   5783: 
                   5784: =item * &bodytag()
1.60      matthew  5785: 
                   5786: Returns a uniform header for LON-CAPA web pages.
                   5787: 
                   5788: Inputs: 
                   5789: 
1.112     bowersj2 5790: =over 4
                   5791: 
                   5792: =item * $title, A title to be displayed on the page.
                   5793: 
                   5794: =item * $function, the current role (can be undef).
                   5795: 
                   5796: =item * $addentries, extra parameters for the <body> tag.
                   5797: 
                   5798: =item * $bodyonly, if defined, only return the <body> tag.
                   5799: 
                   5800: =item * $domain, if defined, force a given domain.
                   5801: 
                   5802: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5803:             text interface only)
1.60      matthew  5804: 
1.814     bisitz   5805: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5806:                      navigational links
1.317     albertel 5807: 
1.338     albertel 5808: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5809: 
1.460     albertel 5810: =item * $args, optional argument valid values are
                   5811:             no_auto_mt_title -> prevents &mt()ing the title arg
                   5812: 
1.1096    raeburn  5813: =item * $advtoolsref, optional argument, ref to an array containing
                   5814:             inlineremote items to be added in "Functions" menu below
                   5815:             breadcrumbs.
                   5816: 
1.112     bowersj2 5817: =back
                   5818: 
1.60      matthew  5819: Returns: A uniform header for LON-CAPA web pages.  
                   5820: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5821: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5822: other decorations will be returned.
                   5823: 
                   5824: =cut
                   5825: 
1.54      www      5826: sub bodytag {
1.831     bisitz   5827:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5828:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5829: 
1.954     raeburn  5830:     my $public;
                   5831:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5832:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5833:         $public = 1;
                   5834:     }
1.460     albertel 5835:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5836:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5837: 
1.183     matthew  5838:     $function = &get_users_function() if (!$function);
1.339     albertel 5839:     my $img =    &designparm($function.'.img',$domain);
                   5840:     my $font =   &designparm($function.'.font',$domain);
                   5841:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5842: 
1.803     bisitz   5843:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5844: 		   'bgcolor' => $pgbg,
1.339     albertel 5845: 		   'text'    => $font,
                   5846:                    'alink'   => &designparm($function.'.alink',$domain),
                   5847: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5848: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5849:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5850: 
1.63      www      5851:  # role and realm
1.1178    raeburn  5852:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5853:     if ($realm) {
                   5854:         $realm = '/'.$realm;
                   5855:     }
1.378     raeburn  5856:     if ($role  eq 'ca') {
1.479     albertel 5857:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5858:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5859:     } 
1.55      www      5860: # realm
1.258     albertel 5861:     if ($env{'request.course.id'}) {
1.378     raeburn  5862:         if ($env{'request.role'} !~ /^cr/) {
                   5863:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  5864:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269  ! raeburn  5865:             if ($env{'request.role.desc'}) {
        !          5866:                 $role = $env{'request.role.desc'};
        !          5867:             } else {
        !          5868:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
        !          5869:             }
1.1257    raeburn  5870:         } else {
                   5871:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  5872:         }
1.898     raeburn  5873:         if ($env{'request.course.sec'}) {
                   5874:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5875:         }   
1.359     albertel 5876: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5877:     } else {
                   5878:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5879:     }
1.433     albertel 5880: 
1.359     albertel 5881:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5882: 
1.438     albertel 5883:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5884: 
1.101     www      5885: # construct main body tag
1.359     albertel 5886:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  5887: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5888: 
1.1131    raeburn  5889:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5890: 
1.1130    raeburn  5891:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5892:         return $bodytag;
1.1130    raeburn  5893:     }
1.359     albertel 5894: 
1.954     raeburn  5895:     if ($public) {
1.433     albertel 5896: 	undef($role);
                   5897:     }
1.359     albertel 5898:     
1.762     bisitz   5899:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5900:     #
                   5901:     # Extra info if you are the DC
                   5902:     my $dc_info = '';
                   5903:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5904:                         $env{'course.'.$env{'request.course.id'}.
                   5905:                                  '.domain'}.'/'})) {
                   5906:         my $cid = $env{'request.course.id'};
1.917     raeburn  5907:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5908:         $dc_info =~ s/\s+$//;
1.359     albertel 5909:     }
                   5910: 
1.1237    raeburn  5911:     my $crstype;
                   5912:     if ($env{'request.course.id'}) {
                   5913:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   5914:     } elsif ($args->{'crstype'}) {
                   5915:         $crstype = $args->{'crstype'};
                   5916:     }
                   5917:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   5918:         undef($role);
                   5919:     } else {
1.1242    raeburn  5920:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  5921:     }
1.853     droeschl 5922: 
1.903     droeschl 5923:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5924: 
                   5925:         #    if ($env{'request.state'} eq 'construct') {
                   5926:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5927:         #    }
                   5928: 
1.1130    raeburn  5929:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5930:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5931: 
1.1237    raeburn  5932:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
1.359     albertel 5933: 
1.916     droeschl 5934:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5935:              if ($dc_info) {
                   5936:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5937:              }
1.1130    raeburn  5938:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5939:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5940:             return $bodytag;
                   5941:         }
1.894     droeschl 5942: 
1.927     raeburn  5943:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5944:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5945:         }
1.916     droeschl 5946: 
1.1130    raeburn  5947:         $bodytag .= $right;
1.852     droeschl 5948: 
1.917     raeburn  5949:         if ($dc_info) {
                   5950:             $dc_info = &dc_courseid_toggle($dc_info);
                   5951:         }
                   5952:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5953: 
1.1169    raeburn  5954:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5955:         if ($args->{'no_secondary_menu'}) {
                   5956:             return $bodytag;
                   5957:         }
1.1169    raeburn  5958:         #don't show menus for public users
1.954     raeburn  5959:         if (!$public){
1.1154    raeburn  5960:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5961:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5962:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5963:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5964:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5965:                                 $args->{'bread_crumbs'});
1.1096    raeburn  5966:             } elsif ($forcereg) {
                   5967:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  5968:                                                             $args->{'group'},
                   5969:                                                             $args->{'hide_buttons'});
1.1096    raeburn  5970:             } else {
                   5971:                 $bodytag .= 
                   5972:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5973:                                                         $forcereg,$args->{'group'},
                   5974:                                                         $args->{'bread_crumbs'},
                   5975:                                                         $advtoolsref);
1.920     raeburn  5976:             }
1.903     droeschl 5977:         }else{
                   5978:             # this is to seperate menu from content when there's no secondary
                   5979:             # menu. Especially needed for public accessible ressources.
                   5980:             $bodytag .= '<hr style="clear:both" />';
                   5981:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5982:         }
1.903     droeschl 5983: 
1.235     raeburn  5984:         return $bodytag;
1.182     matthew  5985: }
                   5986: 
1.917     raeburn  5987: sub dc_courseid_toggle {
                   5988:     my ($dc_info) = @_;
1.980     raeburn  5989:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5990:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5991:            &mt('(More ...)').'</a></span>'.
                   5992:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5993: }
                   5994: 
1.330     albertel 5995: sub make_attr_string {
                   5996:     my ($register,$attr_ref) = @_;
                   5997: 
                   5998:     if ($attr_ref && !ref($attr_ref)) {
                   5999: 	die("addentries Must be a hash ref ".
                   6000: 	    join(':',caller(1))." ".
                   6001: 	    join(':',caller(0))." ");
                   6002:     }
                   6003: 
                   6004:     if ($register) {
1.339     albertel 6005: 	my ($on_load,$on_unload);
                   6006: 	foreach my $key (keys(%{$attr_ref})) {
                   6007: 	    if      (lc($key) eq 'onload') {
                   6008: 		$on_load.=$attr_ref->{$key}.';';
                   6009: 		delete($attr_ref->{$key});
                   6010: 
                   6011: 	    } elsif (lc($key) eq 'onunload') {
                   6012: 		$on_unload.=$attr_ref->{$key}.';';
                   6013: 		delete($attr_ref->{$key});
                   6014: 	    }
                   6015: 	}
1.953     droeschl 6016: 	$attr_ref->{'onload'}  = $on_load;
                   6017: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6018:     }
1.339     albertel 6019: 
1.330     albertel 6020:     my $attr_string;
1.1159    raeburn  6021:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6022: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6023:     }
                   6024:     return $attr_string;
                   6025: }
                   6026: 
                   6027: 
1.182     matthew  6028: ###############################################
1.251     albertel 6029: ###############################################
                   6030: 
                   6031: =pod
                   6032: 
                   6033: =item * &endbodytag()
                   6034: 
                   6035: Returns a uniform footer for LON-CAPA web pages.
                   6036: 
1.635     raeburn  6037: Inputs: 1 - optional reference to an args hash
                   6038: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6039: a 'Continue' link is not displayed if the page contains an
                   6040: internal redirect in the <head></head> section,
                   6041: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6042: 
                   6043: =cut
                   6044: 
                   6045: sub endbodytag {
1.635     raeburn  6046:     my ($args) = @_;
1.1080    raeburn  6047:     my $endbodytag;
                   6048:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6049:         $endbodytag='</body>';
                   6050:     }
1.315     albertel 6051:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6052:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6053: 	    $endbodytag=
                   6054: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6055: 	        &mt('Continue').'</a>'.
                   6056: 	        $endbodytag;
                   6057:         }
1.315     albertel 6058:     }
1.251     albertel 6059:     return $endbodytag;
                   6060: }
                   6061: 
1.352     albertel 6062: =pod
                   6063: 
                   6064: =item * &standard_css()
                   6065: 
                   6066: Returns a style sheet
                   6067: 
                   6068: Inputs: (all optional)
                   6069:             domain         -> force to color decorate a page for a specific
                   6070:                                domain
                   6071:             function       -> force usage of a specific rolish color scheme
                   6072:             bgcolor        -> override the default page bgcolor
                   6073: 
                   6074: =cut
                   6075: 
1.343     albertel 6076: sub standard_css {
1.345     albertel 6077:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6078:     $function  = &get_users_function() if (!$function);
                   6079:     my $img    = &designparm($function.'.img',   $domain);
                   6080:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6081:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6082:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6083: #second colour for later usage
1.345     albertel 6084:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6085:     my $pgbg_or_bgcolor =
                   6086: 	         $bgcolor ||
1.352     albertel 6087: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6088:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6089:     my $alink  = &designparm($function.'.alink', $domain);
                   6090:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6091:     my $link   = &designparm($function.'.link',  $domain);
                   6092: 
1.602     albertel 6093:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6094:     my $mono                 = 'monospace';
1.850     bisitz   6095:     my $data_table_head      = $sidebg;
                   6096:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6097:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6098:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6099:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6100:     my $mail_new             = '#FFBB77';
                   6101:     my $mail_new_hover       = '#DD9955';
                   6102:     my $mail_read            = '#BBBB77';
                   6103:     my $mail_read_hover      = '#999944';
                   6104:     my $mail_replied         = '#AAAA88';
                   6105:     my $mail_replied_hover   = '#888855';
                   6106:     my $mail_other           = '#99BBBB';
                   6107:     my $mail_other_hover     = '#669999';
1.391     albertel 6108:     my $table_header         = '#DDDDDD';
1.489     raeburn  6109:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6110:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6111:     my $button_hover         = '#BF2317';
1.392     albertel 6112: 
1.608     albertel 6113:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6114:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6115:                                              : '0 3px 0 4px';
1.448     albertel 6116: 
1.523     albertel 6117: 
1.343     albertel 6118:     return <<END;
1.947     droeschl 6119: 
                   6120: /* needed for iframe to allow 100% height in FF */
                   6121: body, html { 
                   6122:     margin: 0;
                   6123:     padding: 0 0.5%;
                   6124:     height: 99%; /* to avoid scrollbars */
                   6125: }
                   6126: 
1.795     www      6127: body {
1.911     bisitz   6128:   font-family: $sans;
                   6129:   line-height:130%;
                   6130:   font-size:0.83em;
                   6131:   color:$font;
1.795     www      6132: }
                   6133: 
1.959     onken    6134: a:focus,
                   6135: a:focus img {
1.795     www      6136:   color: red;
                   6137: }
1.698     harmsja  6138: 
1.911     bisitz   6139: form, .inline {
                   6140:   display: inline;
1.795     www      6141: }
1.721     harmsja  6142: 
1.795     www      6143: .LC_right {
1.911     bisitz   6144:   text-align:right;
1.795     www      6145: }
                   6146: 
                   6147: .LC_middle {
1.911     bisitz   6148:   vertical-align:middle;
1.795     www      6149: }
1.721     harmsja  6150: 
1.1130    raeburn  6151: .LC_floatleft {
                   6152:   float: left;
                   6153: }
                   6154: 
                   6155: .LC_floatright {
                   6156:   float: right;
                   6157: }
                   6158: 
1.911     bisitz   6159: .LC_400Box {
                   6160:   width:400px;
                   6161: }
1.721     harmsja  6162: 
1.947     droeschl 6163: .LC_iframecontainer {
                   6164:     width: 98%;
                   6165:     margin: 0;
                   6166:     position: fixed;
                   6167:     top: 8.5em;
                   6168:     bottom: 0;
                   6169: }
                   6170: 
                   6171: .LC_iframecontainer iframe{
                   6172:     border: none;
                   6173:     width: 100%;
                   6174:     height: 100%;
                   6175: }
                   6176: 
1.778     bisitz   6177: .LC_filename {
                   6178:   font-family: $mono;
                   6179:   white-space:pre;
1.921     bisitz   6180:   font-size: 120%;
1.778     bisitz   6181: }
                   6182: 
                   6183: .LC_fileicon {
                   6184:   border: none;
                   6185:   height: 1.3em;
                   6186:   vertical-align: text-bottom;
                   6187:   margin-right: 0.3em;
                   6188:   text-decoration:none;
                   6189: }
                   6190: 
1.1008    www      6191: .LC_setting {
                   6192:   text-decoration:underline;
                   6193: }
                   6194: 
1.350     albertel 6195: .LC_error {
                   6196:   color: red;
                   6197: }
1.795     www      6198: 
1.1097    bisitz   6199: .LC_warning {
                   6200:   color: darkorange;
                   6201: }
                   6202: 
1.457     albertel 6203: .LC_diff_removed {
1.733     bisitz   6204:   color: red;
1.394     albertel 6205: }
1.532     albertel 6206: 
                   6207: .LC_info,
1.457     albertel 6208: .LC_success,
                   6209: .LC_diff_added {
1.350     albertel 6210:   color: green;
                   6211: }
1.795     www      6212: 
1.802     bisitz   6213: div.LC_confirm_box {
                   6214:   background-color: #FAFAFA;
                   6215:   border: 1px solid $lg_border_color;
                   6216:   margin-right: 0;
                   6217:   padding: 5px;
                   6218: }
                   6219: 
                   6220: div.LC_confirm_box .LC_error img,
                   6221: div.LC_confirm_box .LC_success img {
                   6222:   vertical-align: middle;
                   6223: }
                   6224: 
1.1242    raeburn  6225: .LC_maxwidth {
                   6226:   max-width: 100%;
                   6227:   height: auto;
                   6228: }
                   6229: 
1.1243    raeburn  6230: .LC_textsize_mobile {
                   6231:   \@media only screen and (max-device-width: 480px) {
                   6232:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6233:   }
                   6234: }
                   6235: 
1.440     albertel 6236: .LC_icon {
1.771     droeschl 6237:   border: none;
1.790     droeschl 6238:   vertical-align: middle;
1.771     droeschl 6239: }
                   6240: 
1.543     albertel 6241: .LC_docs_spacer {
                   6242:   width: 25px;
                   6243:   height: 1px;
1.771     droeschl 6244:   border: none;
1.543     albertel 6245: }
1.346     albertel 6246: 
1.532     albertel 6247: .LC_internal_info {
1.735     bisitz   6248:   color: #999999;
1.532     albertel 6249: }
                   6250: 
1.794     www      6251: .LC_discussion {
1.1050    www      6252:   background: $data_table_dark;
1.911     bisitz   6253:   border: 1px solid black;
                   6254:   margin: 2px;
1.794     www      6255: }
                   6256: 
                   6257: .LC_disc_action_left {
1.1050    www      6258:   background: $sidebg;
1.911     bisitz   6259:   text-align: left;
1.1050    www      6260:   padding: 4px;
                   6261:   margin: 2px;
1.794     www      6262: }
                   6263: 
                   6264: .LC_disc_action_right {
1.1050    www      6265:   background: $sidebg;
1.911     bisitz   6266:   text-align: right;
1.1050    www      6267:   padding: 4px;
                   6268:   margin: 2px;
1.794     www      6269: }
                   6270: 
                   6271: .LC_disc_new_item {
1.911     bisitz   6272:   background: white;
                   6273:   border: 2px solid red;
1.1050    www      6274:   margin: 4px;
                   6275:   padding: 4px;
1.794     www      6276: }
                   6277: 
                   6278: .LC_disc_old_item {
1.911     bisitz   6279:   background: white;
1.1050    www      6280:   margin: 4px;
                   6281:   padding: 4px;
1.794     www      6282: }
                   6283: 
1.458     albertel 6284: table.LC_pastsubmission {
                   6285:   border: 1px solid black;
                   6286:   margin: 2px;
                   6287: }
                   6288: 
1.924     bisitz   6289: table#LC_menubuttons {
1.345     albertel 6290:   width: 100%;
                   6291:   background: $pgbg;
1.392     albertel 6292:   border: 2px;
1.402     albertel 6293:   border-collapse: separate;
1.803     bisitz   6294:   padding: 0;
1.345     albertel 6295: }
1.392     albertel 6296: 
1.801     tempelho 6297: table#LC_title_bar a {
                   6298:   color: $fontmenu;
                   6299: }
1.836     bisitz   6300: 
1.807     droeschl 6301: table#LC_title_bar {
1.819     tempelho 6302:   clear: both;
1.836     bisitz   6303:   display: none;
1.807     droeschl 6304: }
                   6305: 
1.795     www      6306: table#LC_title_bar,
1.933     droeschl 6307: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6308: table#LC_title_bar.LC_with_remote {
1.359     albertel 6309:   width: 100%;
1.392     albertel 6310:   border-color: $pgbg;
                   6311:   border-style: solid;
                   6312:   border-width: $border;
1.379     albertel 6313:   background: $pgbg;
1.801     tempelho 6314:   color: $fontmenu;
1.392     albertel 6315:   border-collapse: collapse;
1.803     bisitz   6316:   padding: 0;
1.819     tempelho 6317:   margin: 0;
1.359     albertel 6318: }
1.795     www      6319: 
1.933     droeschl 6320: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6321:     margin: 0;
                   6322:     padding: 0;
1.933     droeschl 6323:     position: relative;
                   6324:     list-style: none;
1.913     droeschl 6325: }
1.933     droeschl 6326: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6327:     display: inline;
                   6328: }
1.933     droeschl 6329: 
                   6330: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6331:     padding: 0;
1.933     droeschl 6332:     margin: 0;
                   6333:     float: left;
1.913     droeschl 6334: }
1.933     droeschl 6335: .LC_breadcrumb_tools_tools {
                   6336:     padding: 0;
                   6337:     margin: 0;
1.913     droeschl 6338:     float: right;
                   6339: }
                   6340: 
1.1240    raeburn  6341: .LC_placement_prog {
                   6342:     padding-right: 20px;
                   6343:     font-weight: bold;
                   6344:     font-size: 90%;
                   6345: }
                   6346: 
1.359     albertel 6347: table#LC_title_bar td {
                   6348:   background: $tabbg;
                   6349: }
1.795     www      6350: 
1.911     bisitz   6351: table#LC_menubuttons img {
1.803     bisitz   6352:   border: none;
1.346     albertel 6353: }
1.795     www      6354: 
1.842     droeschl 6355: .LC_breadcrumbs_component {
1.911     bisitz   6356:   float: right;
                   6357:   margin: 0 1em;
1.357     albertel 6358: }
1.842     droeschl 6359: .LC_breadcrumbs_component img {
1.911     bisitz   6360:   vertical-align: middle;
1.777     tempelho 6361: }
1.795     www      6362: 
1.1243    raeburn  6363: .LC_breadcrumbs_hoverable {
                   6364:   background: $sidebg;
                   6365: }
                   6366: 
1.383     albertel 6367: td.LC_table_cell_checkbox {
                   6368:   text-align: center;
                   6369: }
1.795     www      6370: 
                   6371: .LC_fontsize_small {
1.911     bisitz   6372:   font-size: 70%;
1.705     tempelho 6373: }
                   6374: 
1.844     bisitz   6375: #LC_breadcrumbs {
1.911     bisitz   6376:   clear:both;
                   6377:   background: $sidebg;
                   6378:   border-bottom: 1px solid $lg_border_color;
                   6379:   line-height: 2.5em;
1.933     droeschl 6380:   overflow: hidden;
1.911     bisitz   6381:   margin: 0;
                   6382:   padding: 0;
1.995     raeburn  6383:   text-align: left;
1.819     tempelho 6384: }
1.862     bisitz   6385: 
1.1098    bisitz   6386: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6387:   clear:both;
                   6388:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6389:   border: 1px solid $sidebg;
1.1098    bisitz   6390:   margin: 0 0 10px 0;
1.966     bisitz   6391:   padding: 3px;
1.995     raeburn  6392:   text-align: left;
1.822     bisitz   6393: }
                   6394: 
1.795     www      6395: .LC_fontsize_medium {
1.911     bisitz   6396:   font-size: 85%;
1.705     tempelho 6397: }
                   6398: 
1.795     www      6399: .LC_fontsize_large {
1.911     bisitz   6400:   font-size: 120%;
1.705     tempelho 6401: }
                   6402: 
1.346     albertel 6403: .LC_menubuttons_inline_text {
                   6404:   color: $font;
1.698     harmsja  6405:   font-size: 90%;
1.701     harmsja  6406:   padding-left:3px;
1.346     albertel 6407: }
                   6408: 
1.934     droeschl 6409: .LC_menubuttons_inline_text img{
                   6410:   vertical-align: middle;
                   6411: }
                   6412: 
1.1051    www      6413: li.LC_menubuttons_inline_text img {
1.951     onken    6414:   cursor:pointer;
1.1002    droeschl 6415:   text-decoration: none;
1.951     onken    6416: }
                   6417: 
1.526     www      6418: .LC_menubuttons_link {
                   6419:   text-decoration: none;
                   6420: }
1.795     www      6421: 
1.522     albertel 6422: .LC_menubuttons_category {
1.521     www      6423:   color: $font;
1.526     www      6424:   background: $pgbg;
1.521     www      6425:   font-size: larger;
                   6426:   font-weight: bold;
                   6427: }
                   6428: 
1.346     albertel 6429: td.LC_menubuttons_text {
1.911     bisitz   6430:   color: $font;
1.346     albertel 6431: }
1.706     harmsja  6432: 
1.346     albertel 6433: .LC_current_location {
                   6434:   background: $tabbg;
                   6435: }
1.795     www      6436: 
1.938     bisitz   6437: table.LC_data_table {
1.347     albertel 6438:   border: 1px solid #000000;
1.402     albertel 6439:   border-collapse: separate;
1.426     albertel 6440:   border-spacing: 1px;
1.610     albertel 6441:   background: $pgbg;
1.347     albertel 6442: }
1.795     www      6443: 
1.422     albertel 6444: .LC_data_table_dense {
                   6445:   font-size: small;
                   6446: }
1.795     www      6447: 
1.507     raeburn  6448: table.LC_nested_outer {
                   6449:   border: 1px solid #000000;
1.589     raeburn  6450:   border-collapse: collapse;
1.803     bisitz   6451:   border-spacing: 0;
1.507     raeburn  6452:   width: 100%;
                   6453: }
1.795     www      6454: 
1.879     raeburn  6455: table.LC_innerpickbox,
1.507     raeburn  6456: table.LC_nested {
1.803     bisitz   6457:   border: none;
1.589     raeburn  6458:   border-collapse: collapse;
1.803     bisitz   6459:   border-spacing: 0;
1.507     raeburn  6460:   width: 100%;
                   6461: }
1.795     www      6462: 
1.911     bisitz   6463: table.LC_data_table tr th,
                   6464: table.LC_calendar tr th,
1.879     raeburn  6465: table.LC_prior_tries tr th,
                   6466: table.LC_innerpickbox tr th {
1.349     albertel 6467:   font-weight: bold;
                   6468:   background-color: $data_table_head;
1.801     tempelho 6469:   color:$fontmenu;
1.701     harmsja  6470:   font-size:90%;
1.347     albertel 6471: }
1.795     www      6472: 
1.879     raeburn  6473: table.LC_innerpickbox tr th,
                   6474: table.LC_innerpickbox tr td {
                   6475:   vertical-align: top;
                   6476: }
                   6477: 
1.711     raeburn  6478: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6479:   background-color: #CCCCCC;
1.711     raeburn  6480:   font-weight: bold;
                   6481:   text-align: left;
                   6482: }
1.795     www      6483: 
1.912     bisitz   6484: table.LC_data_table tr.LC_odd_row > td {
                   6485:   background-color: $data_table_light;
                   6486:   padding: 2px;
                   6487:   vertical-align: top;
                   6488: }
                   6489: 
1.809     bisitz   6490: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6491:   background-color: $data_table_light;
1.912     bisitz   6492:   vertical-align: top;
                   6493: }
                   6494: 
                   6495: table.LC_data_table tr.LC_even_row > td {
                   6496:   background-color: $data_table_dark;
1.425     albertel 6497:   padding: 2px;
1.900     bisitz   6498:   vertical-align: top;
1.347     albertel 6499: }
1.795     www      6500: 
1.809     bisitz   6501: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6502:   background-color: $data_table_dark;
1.900     bisitz   6503:   vertical-align: top;
1.347     albertel 6504: }
1.795     www      6505: 
1.425     albertel 6506: table.LC_data_table tr.LC_data_table_highlight td {
                   6507:   background-color: $data_table_darker;
                   6508: }
1.795     www      6509: 
1.639     raeburn  6510: table.LC_data_table tr td.LC_leftcol_header {
                   6511:   background-color: $data_table_head;
                   6512:   font-weight: bold;
                   6513: }
1.795     www      6514: 
1.451     albertel 6515: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6516: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6517:   font-weight: bold;
                   6518:   font-style: italic;
                   6519:   text-align: center;
                   6520:   padding: 8px;
1.347     albertel 6521: }
1.795     www      6522: 
1.1114    raeburn  6523: table.LC_data_table tr.LC_empty_row td,
                   6524: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6525:   background-color: $sidebg;
                   6526: }
                   6527: 
                   6528: table.LC_nested tr.LC_empty_row td {
                   6529:   background-color: #FFFFFF;
                   6530: }
                   6531: 
1.890     droeschl 6532: table.LC_caption {
                   6533: }
                   6534: 
1.507     raeburn  6535: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6536:   padding: 4ex
                   6537: }
1.795     www      6538: 
1.507     raeburn  6539: table.LC_nested_outer tr th {
                   6540:   font-weight: bold;
1.801     tempelho 6541:   color:$fontmenu;
1.507     raeburn  6542:   background-color: $data_table_head;
1.701     harmsja  6543:   font-size: small;
1.507     raeburn  6544:   border-bottom: 1px solid #000000;
                   6545: }
1.795     www      6546: 
1.507     raeburn  6547: table.LC_nested_outer tr td.LC_subheader {
                   6548:   background-color: $data_table_head;
                   6549:   font-weight: bold;
                   6550:   font-size: small;
                   6551:   border-bottom: 1px solid #000000;
                   6552:   text-align: right;
1.451     albertel 6553: }
1.795     www      6554: 
1.507     raeburn  6555: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6556:   background-color: #CCCCCC;
1.451     albertel 6557:   font-weight: bold;
                   6558:   font-size: small;
1.507     raeburn  6559:   text-align: center;
                   6560: }
1.795     www      6561: 
1.589     raeburn  6562: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6563: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6564:   text-align: left;
1.451     albertel 6565: }
1.795     www      6566: 
1.507     raeburn  6567: table.LC_nested td {
1.735     bisitz   6568:   background-color: #FFFFFF;
1.451     albertel 6569:   font-size: small;
1.507     raeburn  6570: }
1.795     www      6571: 
1.507     raeburn  6572: table.LC_nested_outer tr th.LC_right_item,
                   6573: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6574: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6575: table.LC_nested tr td.LC_right_item {
1.451     albertel 6576:   text-align: right;
                   6577: }
                   6578: 
1.507     raeburn  6579: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6580:   background-color: #EEEEEE;
1.451     albertel 6581: }
                   6582: 
1.473     raeburn  6583: table.LC_createuser {
                   6584: }
                   6585: 
                   6586: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6587:   font-size: small;
1.473     raeburn  6588: }
                   6589: 
                   6590: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6591:   background-color: #CCCCCC;
1.473     raeburn  6592:   font-weight: bold;
                   6593:   text-align: center;
                   6594: }
                   6595: 
1.349     albertel 6596: table.LC_calendar {
                   6597:   border: 1px solid #000000;
                   6598:   border-collapse: collapse;
1.917     raeburn  6599:   width: 98%;
1.349     albertel 6600: }
1.795     www      6601: 
1.349     albertel 6602: table.LC_calendar_pickdate {
                   6603:   font-size: xx-small;
                   6604: }
1.795     www      6605: 
1.349     albertel 6606: table.LC_calendar tr td {
                   6607:   border: 1px solid #000000;
                   6608:   vertical-align: top;
1.917     raeburn  6609:   width: 14%;
1.349     albertel 6610: }
1.795     www      6611: 
1.349     albertel 6612: table.LC_calendar tr td.LC_calendar_day_empty {
                   6613:   background-color: $data_table_dark;
                   6614: }
1.795     www      6615: 
1.779     bisitz   6616: table.LC_calendar tr td.LC_calendar_day_current {
                   6617:   background-color: $data_table_highlight;
1.777     tempelho 6618: }
1.795     www      6619: 
1.938     bisitz   6620: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6621:   background-color: $mail_new;
                   6622: }
1.795     www      6623: 
1.938     bisitz   6624: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6625:   background-color: $mail_new_hover;
                   6626: }
1.795     www      6627: 
1.938     bisitz   6628: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6629:   background-color: $mail_read;
                   6630: }
1.795     www      6631: 
1.938     bisitz   6632: /*
                   6633: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6634:   background-color: $mail_read_hover;
                   6635: }
1.938     bisitz   6636: */
1.795     www      6637: 
1.938     bisitz   6638: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6639:   background-color: $mail_replied;
                   6640: }
1.795     www      6641: 
1.938     bisitz   6642: /*
                   6643: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6644:   background-color: $mail_replied_hover;
                   6645: }
1.938     bisitz   6646: */
1.795     www      6647: 
1.938     bisitz   6648: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6649:   background-color: $mail_other;
                   6650: }
1.795     www      6651: 
1.938     bisitz   6652: /*
                   6653: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6654:   background-color: $mail_other_hover;
                   6655: }
1.938     bisitz   6656: */
1.494     raeburn  6657: 
1.777     tempelho 6658: table.LC_data_table tr > td.LC_browser_file,
                   6659: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6660:   background: #AAEE77;
1.389     albertel 6661: }
1.795     www      6662: 
1.777     tempelho 6663: table.LC_data_table tr > td.LC_browser_file_locked,
                   6664: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6665:   background: #FFAA99;
1.387     albertel 6666: }
1.795     www      6667: 
1.777     tempelho 6668: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6669:   background: #888888;
1.779     bisitz   6670: }
1.795     www      6671: 
1.777     tempelho 6672: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6673: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6674:   background: #F8F866;
1.777     tempelho 6675: }
1.795     www      6676: 
1.696     bisitz   6677: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6678:   background: #E0E8FF;
1.387     albertel 6679: }
1.696     bisitz   6680: 
1.707     bisitz   6681: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6682:   /* background: #77FF77; */
1.707     bisitz   6683: }
1.795     www      6684: 
1.707     bisitz   6685: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6686:   border-right: 8px solid #FFFF77;
1.707     bisitz   6687: }
1.795     www      6688: 
1.707     bisitz   6689: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6690:   border-right: 8px solid #FFAA77;
1.707     bisitz   6691: }
1.795     www      6692: 
1.707     bisitz   6693: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6694:   border-right: 8px solid #FF7777;
1.707     bisitz   6695: }
1.795     www      6696: 
1.707     bisitz   6697: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6698:   border-right: 8px solid #AAFF77;
1.707     bisitz   6699: }
1.795     www      6700: 
1.707     bisitz   6701: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6702:   border-right: 8px solid #11CC55;
1.707     bisitz   6703: }
                   6704: 
1.388     albertel 6705: span.LC_current_location {
1.701     harmsja  6706:   font-size:larger;
1.388     albertel 6707:   background: $pgbg;
                   6708: }
1.387     albertel 6709: 
1.1029    www      6710: span.LC_current_nav_location {
                   6711:   font-weight:bold;
                   6712:   background: $sidebg;
                   6713: }
                   6714: 
1.395     albertel 6715: span.LC_parm_menu_item {
                   6716:   font-size: larger;
                   6717: }
1.795     www      6718: 
1.395     albertel 6719: span.LC_parm_scope_all {
                   6720:   color: red;
                   6721: }
1.795     www      6722: 
1.395     albertel 6723: span.LC_parm_scope_folder {
                   6724:   color: green;
                   6725: }
1.795     www      6726: 
1.395     albertel 6727: span.LC_parm_scope_resource {
                   6728:   color: orange;
                   6729: }
1.795     www      6730: 
1.395     albertel 6731: span.LC_parm_part {
                   6732:   color: blue;
                   6733: }
1.795     www      6734: 
1.911     bisitz   6735: span.LC_parm_folder,
                   6736: span.LC_parm_symb {
1.395     albertel 6737:   font-size: x-small;
                   6738:   font-family: $mono;
                   6739:   color: #AAAAAA;
                   6740: }
                   6741: 
1.977     bisitz   6742: ul.LC_parm_parmlist li {
                   6743:   display: inline-block;
                   6744:   padding: 0.3em 0.8em;
                   6745:   vertical-align: top;
                   6746:   width: 150px;
                   6747:   border-top:1px solid $lg_border_color;
                   6748: }
                   6749: 
1.795     www      6750: td.LC_parm_overview_level_menu,
                   6751: td.LC_parm_overview_map_menu,
                   6752: td.LC_parm_overview_parm_selectors,
                   6753: td.LC_parm_overview_restrictions  {
1.396     albertel 6754:   border: 1px solid black;
                   6755:   border-collapse: collapse;
                   6756: }
1.795     www      6757: 
1.396     albertel 6758: table.LC_parm_overview_restrictions td {
                   6759:   border-width: 1px 4px 1px 4px;
                   6760:   border-style: solid;
                   6761:   border-color: $pgbg;
                   6762:   text-align: center;
                   6763: }
1.795     www      6764: 
1.396     albertel 6765: table.LC_parm_overview_restrictions th {
                   6766:   background: $tabbg;
                   6767:   border-width: 1px 4px 1px 4px;
                   6768:   border-style: solid;
                   6769:   border-color: $pgbg;
                   6770: }
1.795     www      6771: 
1.398     albertel 6772: table#LC_helpmenu {
1.803     bisitz   6773:   border: none;
1.398     albertel 6774:   height: 55px;
1.803     bisitz   6775:   border-spacing: 0;
1.398     albertel 6776: }
                   6777: 
                   6778: table#LC_helpmenu fieldset legend {
                   6779:   font-size: larger;
                   6780: }
1.795     www      6781: 
1.397     albertel 6782: table#LC_helpmenu_links {
                   6783:   width: 100%;
                   6784:   border: 1px solid black;
                   6785:   background: $pgbg;
1.803     bisitz   6786:   padding: 0;
1.397     albertel 6787:   border-spacing: 1px;
                   6788: }
1.795     www      6789: 
1.397     albertel 6790: table#LC_helpmenu_links tr td {
                   6791:   padding: 1px;
                   6792:   background: $tabbg;
1.399     albertel 6793:   text-align: center;
                   6794:   font-weight: bold;
1.397     albertel 6795: }
1.396     albertel 6796: 
1.795     www      6797: table#LC_helpmenu_links a:link,
                   6798: table#LC_helpmenu_links a:visited,
1.397     albertel 6799: table#LC_helpmenu_links a:active {
                   6800:   text-decoration: none;
                   6801:   color: $font;
                   6802: }
1.795     www      6803: 
1.397     albertel 6804: table#LC_helpmenu_links a:hover {
                   6805:   text-decoration: underline;
                   6806:   color: $vlink;
                   6807: }
1.396     albertel 6808: 
1.417     albertel 6809: .LC_chrt_popup_exists {
                   6810:   border: 1px solid #339933;
                   6811:   margin: -1px;
                   6812: }
1.795     www      6813: 
1.417     albertel 6814: .LC_chrt_popup_up {
                   6815:   border: 1px solid yellow;
                   6816:   margin: -1px;
                   6817: }
1.795     www      6818: 
1.417     albertel 6819: .LC_chrt_popup {
                   6820:   border: 1px solid #8888FF;
                   6821:   background: #CCCCFF;
                   6822: }
1.795     www      6823: 
1.421     albertel 6824: table.LC_pick_box {
                   6825:   border-collapse: separate;
                   6826:   background: white;
                   6827:   border: 1px solid black;
                   6828:   border-spacing: 1px;
                   6829: }
1.795     www      6830: 
1.421     albertel 6831: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6832:   background: $sidebg;
1.421     albertel 6833:   font-weight: bold;
1.900     bisitz   6834:   text-align: left;
1.740     bisitz   6835:   vertical-align: top;
1.421     albertel 6836:   width: 184px;
                   6837:   padding: 8px;
                   6838: }
1.795     www      6839: 
1.579     raeburn  6840: table.LC_pick_box td.LC_pick_box_value {
                   6841:   text-align: left;
                   6842:   padding: 8px;
                   6843: }
1.795     www      6844: 
1.579     raeburn  6845: table.LC_pick_box td.LC_pick_box_select {
                   6846:   text-align: left;
                   6847:   padding: 8px;
                   6848: }
1.795     www      6849: 
1.424     albertel 6850: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6851:   padding: 0;
1.421     albertel 6852:   height: 1px;
                   6853:   background: black;
                   6854: }
1.795     www      6855: 
1.421     albertel 6856: table.LC_pick_box td.LC_pick_box_submit {
                   6857:   text-align: right;
                   6858: }
1.795     www      6859: 
1.579     raeburn  6860: table.LC_pick_box td.LC_evenrow_value {
                   6861:   text-align: left;
                   6862:   padding: 8px;
                   6863:   background-color: $data_table_light;
                   6864: }
1.795     www      6865: 
1.579     raeburn  6866: table.LC_pick_box td.LC_oddrow_value {
                   6867:   text-align: left;
                   6868:   padding: 8px;
                   6869:   background-color: $data_table_light;
                   6870: }
1.795     www      6871: 
1.579     raeburn  6872: span.LC_helpform_receipt_cat {
                   6873:   font-weight: bold;
                   6874: }
1.795     www      6875: 
1.424     albertel 6876: table.LC_group_priv_box {
                   6877:   background: white;
                   6878:   border: 1px solid black;
                   6879:   border-spacing: 1px;
                   6880: }
1.795     www      6881: 
1.424     albertel 6882: table.LC_group_priv_box td.LC_pick_box_title {
                   6883:   background: $tabbg;
                   6884:   font-weight: bold;
                   6885:   text-align: right;
                   6886:   width: 184px;
                   6887: }
1.795     www      6888: 
1.424     albertel 6889: table.LC_group_priv_box td.LC_groups_fixed {
                   6890:   background: $data_table_light;
                   6891:   text-align: center;
                   6892: }
1.795     www      6893: 
1.424     albertel 6894: table.LC_group_priv_box td.LC_groups_optional {
                   6895:   background: $data_table_dark;
                   6896:   text-align: center;
                   6897: }
1.795     www      6898: 
1.424     albertel 6899: table.LC_group_priv_box td.LC_groups_functionality {
                   6900:   background: $data_table_darker;
                   6901:   text-align: center;
                   6902:   font-weight: bold;
                   6903: }
1.795     www      6904: 
1.424     albertel 6905: table.LC_group_priv td {
                   6906:   text-align: left;
1.803     bisitz   6907:   padding: 0;
1.424     albertel 6908: }
                   6909: 
                   6910: .LC_navbuttons {
                   6911:   margin: 2ex 0ex 2ex 0ex;
                   6912: }
1.795     www      6913: 
1.423     albertel 6914: .LC_topic_bar {
                   6915:   font-weight: bold;
                   6916:   background: $tabbg;
1.918     wenzelju 6917:   margin: 1em 0em 1em 2em;
1.805     bisitz   6918:   padding: 3px;
1.918     wenzelju 6919:   font-size: 1.2em;
1.423     albertel 6920: }
1.795     www      6921: 
1.423     albertel 6922: .LC_topic_bar span {
1.918     wenzelju 6923:   left: 0.5em;
                   6924:   position: absolute;
1.423     albertel 6925:   vertical-align: middle;
1.918     wenzelju 6926:   font-size: 1.2em;
1.423     albertel 6927: }
1.795     www      6928: 
1.423     albertel 6929: table.LC_course_group_status {
                   6930:   margin: 20px;
                   6931: }
1.795     www      6932: 
1.423     albertel 6933: table.LC_status_selector td {
                   6934:   vertical-align: top;
                   6935:   text-align: center;
1.424     albertel 6936:   padding: 4px;
                   6937: }
1.795     www      6938: 
1.599     albertel 6939: div.LC_feedback_link {
1.616     albertel 6940:   clear: both;
1.829     kalberla 6941:   background: $sidebg;
1.779     bisitz   6942:   width: 100%;
1.829     kalberla 6943:   padding-bottom: 10px;
                   6944:   border: 1px $tabbg solid;
1.833     kalberla 6945:   height: 22px;
                   6946:   line-height: 22px;
                   6947:   padding-top: 5px;
                   6948: }
                   6949: 
                   6950: div.LC_feedback_link img {
                   6951:   height: 22px;
1.867     kalberla 6952:   vertical-align:middle;
1.829     kalberla 6953: }
                   6954: 
1.911     bisitz   6955: div.LC_feedback_link a {
1.829     kalberla 6956:   text-decoration: none;
1.489     raeburn  6957: }
1.795     www      6958: 
1.867     kalberla 6959: div.LC_comblock {
1.911     bisitz   6960:   display:inline;
1.867     kalberla 6961:   color:$font;
                   6962:   font-size:90%;
                   6963: }
                   6964: 
                   6965: div.LC_feedback_link div.LC_comblock {
                   6966:   padding-left:5px;
                   6967: }
                   6968: 
                   6969: div.LC_feedback_link div.LC_comblock a {
                   6970:   color:$font;
                   6971: }
                   6972: 
1.489     raeburn  6973: span.LC_feedback_link {
1.858     bisitz   6974:   /* background: $feedback_link_bg; */
1.599     albertel 6975:   font-size: larger;
                   6976: }
1.795     www      6977: 
1.599     albertel 6978: span.LC_message_link {
1.858     bisitz   6979:   /* background: $feedback_link_bg; */
1.599     albertel 6980:   font-size: larger;
                   6981:   position: absolute;
                   6982:   right: 1em;
1.489     raeburn  6983: }
1.421     albertel 6984: 
1.515     albertel 6985: table.LC_prior_tries {
1.524     albertel 6986:   border: 1px solid #000000;
                   6987:   border-collapse: separate;
                   6988:   border-spacing: 1px;
1.515     albertel 6989: }
1.523     albertel 6990: 
1.515     albertel 6991: table.LC_prior_tries td {
1.524     albertel 6992:   padding: 2px;
1.515     albertel 6993: }
1.523     albertel 6994: 
                   6995: .LC_answer_correct {
1.795     www      6996:   background: lightgreen;
                   6997:   color: darkgreen;
                   6998:   padding: 6px;
1.523     albertel 6999: }
1.795     www      7000: 
1.523     albertel 7001: .LC_answer_charged_try {
1.797     www      7002:   background: #FFAAAA;
1.795     www      7003:   color: darkred;
                   7004:   padding: 6px;
1.523     albertel 7005: }
1.795     www      7006: 
1.779     bisitz   7007: .LC_answer_not_charged_try,
1.523     albertel 7008: .LC_answer_no_grade,
                   7009: .LC_answer_late {
1.795     www      7010:   background: lightyellow;
1.523     albertel 7011:   color: black;
1.795     www      7012:   padding: 6px;
1.523     albertel 7013: }
1.795     www      7014: 
1.523     albertel 7015: .LC_answer_previous {
1.795     www      7016:   background: lightblue;
                   7017:   color: darkblue;
                   7018:   padding: 6px;
1.523     albertel 7019: }
1.795     www      7020: 
1.779     bisitz   7021: .LC_answer_no_message {
1.777     tempelho 7022:   background: #FFFFFF;
                   7023:   color: black;
1.795     www      7024:   padding: 6px;
1.779     bisitz   7025: }
1.795     www      7026: 
1.779     bisitz   7027: .LC_answer_unknown {
                   7028:   background: orange;
                   7029:   color: black;
1.795     www      7030:   padding: 6px;
1.777     tempelho 7031: }
1.795     www      7032: 
1.529     albertel 7033: span.LC_prior_numerical,
                   7034: span.LC_prior_string,
                   7035: span.LC_prior_custom,
                   7036: span.LC_prior_reaction,
                   7037: span.LC_prior_math {
1.925     bisitz   7038:   font-family: $mono;
1.523     albertel 7039:   white-space: pre;
                   7040: }
                   7041: 
1.525     albertel 7042: span.LC_prior_string {
1.925     bisitz   7043:   font-family: $mono;
1.525     albertel 7044:   white-space: pre;
                   7045: }
                   7046: 
1.523     albertel 7047: table.LC_prior_option {
                   7048:   width: 100%;
                   7049:   border-collapse: collapse;
                   7050: }
1.795     www      7051: 
1.911     bisitz   7052: table.LC_prior_rank,
1.795     www      7053: table.LC_prior_match {
1.528     albertel 7054:   border-collapse: collapse;
                   7055: }
1.795     www      7056: 
1.528     albertel 7057: table.LC_prior_option tr td,
                   7058: table.LC_prior_rank tr td,
                   7059: table.LC_prior_match tr td {
1.524     albertel 7060:   border: 1px solid #000000;
1.515     albertel 7061: }
                   7062: 
1.855     bisitz   7063: .LC_nobreak {
1.544     albertel 7064:   white-space: nowrap;
1.519     raeburn  7065: }
                   7066: 
1.576     raeburn  7067: span.LC_cusr_emph {
                   7068:   font-style: italic;
                   7069: }
                   7070: 
1.633     raeburn  7071: span.LC_cusr_subheading {
                   7072:   font-weight: normal;
                   7073:   font-size: 85%;
                   7074: }
                   7075: 
1.861     bisitz   7076: div.LC_docs_entry_move {
1.859     bisitz   7077:   border: 1px solid #BBBBBB;
1.545     albertel 7078:   background: #DDDDDD;
1.861     bisitz   7079:   width: 22px;
1.859     bisitz   7080:   padding: 1px;
                   7081:   margin: 0;
1.545     albertel 7082: }
                   7083: 
1.861     bisitz   7084: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7085: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7086:   font-size: x-small;
                   7087: }
1.795     www      7088: 
1.861     bisitz   7089: .LC_docs_entry_parameter {
                   7090:   white-space: nowrap;
                   7091: }
                   7092: 
1.544     albertel 7093: .LC_docs_copy {
1.545     albertel 7094:   color: #000099;
1.544     albertel 7095: }
1.795     www      7096: 
1.544     albertel 7097: .LC_docs_cut {
1.545     albertel 7098:   color: #550044;
1.544     albertel 7099: }
1.795     www      7100: 
1.544     albertel 7101: .LC_docs_rename {
1.545     albertel 7102:   color: #009900;
1.544     albertel 7103: }
1.795     www      7104: 
1.544     albertel 7105: .LC_docs_remove {
1.545     albertel 7106:   color: #990000;
                   7107: }
                   7108: 
1.547     albertel 7109: .LC_docs_reinit_warn,
                   7110: .LC_docs_ext_edit {
                   7111:   font-size: x-small;
                   7112: }
                   7113: 
1.545     albertel 7114: table.LC_docs_adddocs td,
                   7115: table.LC_docs_adddocs th {
                   7116:   border: 1px solid #BBBBBB;
                   7117:   padding: 4px;
                   7118:   background: #DDDDDD;
1.543     albertel 7119: }
                   7120: 
1.584     albertel 7121: table.LC_sty_begin {
                   7122:   background: #BBFFBB;
                   7123: }
1.795     www      7124: 
1.584     albertel 7125: table.LC_sty_end {
                   7126:   background: #FFBBBB;
                   7127: }
                   7128: 
1.589     raeburn  7129: table.LC_double_column {
1.803     bisitz   7130:   border-width: 0;
1.589     raeburn  7131:   border-collapse: collapse;
                   7132:   width: 100%;
                   7133:   padding: 2px;
                   7134: }
                   7135: 
                   7136: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7137:   top: 2px;
1.589     raeburn  7138:   left: 2px;
                   7139:   width: 47%;
                   7140:   vertical-align: top;
                   7141: }
                   7142: 
                   7143: table.LC_double_column tr td.LC_right_col {
                   7144:   top: 2px;
1.779     bisitz   7145:   right: 2px;
1.589     raeburn  7146:   width: 47%;
                   7147:   vertical-align: top;
                   7148: }
                   7149: 
1.591     raeburn  7150: div.LC_left_float {
                   7151:   float: left;
                   7152:   padding-right: 5%;
1.597     albertel 7153:   padding-bottom: 4px;
1.591     raeburn  7154: }
                   7155: 
                   7156: div.LC_clear_float_header {
1.597     albertel 7157:   padding-bottom: 2px;
1.591     raeburn  7158: }
                   7159: 
                   7160: div.LC_clear_float_footer {
1.597     albertel 7161:   padding-top: 10px;
1.591     raeburn  7162:   clear: both;
                   7163: }
                   7164: 
1.597     albertel 7165: div.LC_grade_show_user {
1.941     bisitz   7166: /*  border-left: 5px solid $sidebg; */
                   7167:   border-top: 5px solid #000000;
                   7168:   margin: 50px 0 0 0;
1.936     bisitz   7169:   padding: 15px 0 5px 10px;
1.597     albertel 7170: }
1.795     www      7171: 
1.936     bisitz   7172: div.LC_grade_show_user_odd_row {
1.941     bisitz   7173: /*  border-left: 5px solid #000000; */
                   7174: }
                   7175: 
                   7176: div.LC_grade_show_user div.LC_Box {
                   7177:   margin-right: 50px;
1.597     albertel 7178: }
                   7179: 
                   7180: div.LC_grade_submissions,
                   7181: div.LC_grade_message_center,
1.936     bisitz   7182: div.LC_grade_info_links {
1.597     albertel 7183:   margin: 5px;
                   7184:   width: 99%;
                   7185:   background: #FFFFFF;
                   7186: }
1.795     www      7187: 
1.597     albertel 7188: div.LC_grade_submissions_header,
1.936     bisitz   7189: div.LC_grade_message_center_header {
1.705     tempelho 7190:   font-weight: bold;
                   7191:   font-size: large;
1.597     albertel 7192: }
1.795     www      7193: 
1.597     albertel 7194: div.LC_grade_submissions_body,
1.936     bisitz   7195: div.LC_grade_message_center_body {
1.597     albertel 7196:   border: 1px solid black;
                   7197:   width: 99%;
                   7198:   background: #FFFFFF;
                   7199: }
1.795     www      7200: 
1.613     albertel 7201: table.LC_scantron_action {
                   7202:   width: 100%;
                   7203: }
1.795     www      7204: 
1.613     albertel 7205: table.LC_scantron_action tr th {
1.698     harmsja  7206:   font-weight:bold;
                   7207:   font-style:normal;
1.613     albertel 7208: }
1.795     www      7209: 
1.779     bisitz   7210: .LC_edit_problem_header,
1.614     albertel 7211: div.LC_edit_problem_footer {
1.705     tempelho 7212:   font-weight: normal;
                   7213:   font-size:  medium;
1.602     albertel 7214:   margin: 2px;
1.1060    bisitz   7215:   background-color: $sidebg;
1.600     albertel 7216: }
1.795     www      7217: 
1.600     albertel 7218: div.LC_edit_problem_header,
1.602     albertel 7219: div.LC_edit_problem_header div,
1.614     albertel 7220: div.LC_edit_problem_footer,
                   7221: div.LC_edit_problem_footer div,
1.602     albertel 7222: div.LC_edit_problem_editxml_header,
                   7223: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7224:   z-index: 100;
1.600     albertel 7225: }
1.795     www      7226: 
1.600     albertel 7227: div.LC_edit_problem_header_title {
1.705     tempelho 7228:   font-weight: bold;
                   7229:   font-size: larger;
1.602     albertel 7230:   background: $tabbg;
                   7231:   padding: 3px;
1.1060    bisitz   7232:   margin: 0 0 5px 0;
1.602     albertel 7233: }
1.795     www      7234: 
1.602     albertel 7235: table.LC_edit_problem_header_title {
                   7236:   width: 100%;
1.600     albertel 7237:   background: $tabbg;
1.602     albertel 7238: }
                   7239: 
1.1205    golterma 7240: div.LC_edit_actionbar {
                   7241:     background-color: $sidebg;
1.1218    droeschl 7242:     margin: 0;
                   7243:     padding: 0;
                   7244:     line-height: 200%;
1.602     albertel 7245: }
1.795     www      7246: 
1.1218    droeschl 7247: div.LC_edit_actionbar div{
                   7248:     padding: 0;
                   7249:     margin: 0;
                   7250:     display: inline-block;
1.600     albertel 7251: }
1.795     www      7252: 
1.1124    bisitz   7253: .LC_edit_opt {
                   7254:   padding-left: 1em;
                   7255:   white-space: nowrap;
                   7256: }
                   7257: 
1.1152    golterma 7258: .LC_edit_problem_latexhelper{
                   7259:     text-align: right;
                   7260: }
                   7261: 
                   7262: #LC_edit_problem_colorful div{
                   7263:     margin-left: 40px;
                   7264: }
                   7265: 
1.1205    golterma 7266: #LC_edit_problem_codemirror div{
                   7267:     margin-left: 0px;
                   7268: }
                   7269: 
1.911     bisitz   7270: img.stift {
1.803     bisitz   7271:   border-width: 0;
                   7272:   vertical-align: middle;
1.677     riegler  7273: }
1.680     riegler  7274: 
1.923     bisitz   7275: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7276:   vertical-align: top;
1.777     tempelho 7277: }
1.795     www      7278: 
1.716     raeburn  7279: div.LC_createcourse {
1.911     bisitz   7280:   margin: 10px 10px 10px 10px;
1.716     raeburn  7281: }
                   7282: 
1.917     raeburn  7283: .LC_dccid {
1.1130    raeburn  7284:   float: right;
1.917     raeburn  7285:   margin: 0.2em 0 0 0;
                   7286:   padding: 0;
                   7287:   font-size: 90%;
                   7288:   display:none;
                   7289: }
                   7290: 
1.897     wenzelju 7291: ol.LC_primary_menu a:hover,
1.721     harmsja  7292: ol#LC_MenuBreadcrumbs a:hover,
                   7293: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7294: ul#LC_secondary_menu a:hover,
1.721     harmsja  7295: .LC_FormSectionClearButton input:hover
1.795     www      7296: ul.LC_TabContent   li:hover a {
1.952     onken    7297:   color:$button_hover;
1.911     bisitz   7298:   text-decoration:none;
1.693     droeschl 7299: }
                   7300: 
1.779     bisitz   7301: h1 {
1.911     bisitz   7302:   padding: 0;
                   7303:   line-height:130%;
1.693     droeschl 7304: }
1.698     harmsja  7305: 
1.911     bisitz   7306: h2,
                   7307: h3,
                   7308: h4,
                   7309: h5,
                   7310: h6 {
                   7311:   margin: 5px 0 5px 0;
                   7312:   padding: 0;
                   7313:   line-height:130%;
1.693     droeschl 7314: }
1.795     www      7315: 
                   7316: .LC_hcell {
1.911     bisitz   7317:   padding:3px 15px 3px 15px;
                   7318:   margin: 0;
                   7319:   background-color:$tabbg;
                   7320:   color:$fontmenu;
                   7321:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7322: }
1.795     www      7323: 
1.840     bisitz   7324: .LC_Box > .LC_hcell {
1.911     bisitz   7325:   margin: 0 -10px 10px -10px;
1.835     bisitz   7326: }
                   7327: 
1.721     harmsja  7328: .LC_noBorder {
1.911     bisitz   7329:   border: 0;
1.698     harmsja  7330: }
1.693     droeschl 7331: 
1.721     harmsja  7332: .LC_FormSectionClearButton input {
1.911     bisitz   7333:   background-color:transparent;
                   7334:   border: none;
                   7335:   cursor:pointer;
                   7336:   text-decoration:underline;
1.693     droeschl 7337: }
1.763     bisitz   7338: 
                   7339: .LC_help_open_topic {
1.911     bisitz   7340:   color: #FFFFFF;
                   7341:   background-color: #EEEEFF;
                   7342:   margin: 1px;
                   7343:   padding: 4px;
                   7344:   border: 1px solid #000033;
                   7345:   white-space: nowrap;
                   7346:   /* vertical-align: middle; */
1.759     neumanie 7347: }
1.693     droeschl 7348: 
1.911     bisitz   7349: dl,
                   7350: ul,
                   7351: div,
                   7352: fieldset {
                   7353:   margin: 10px 10px 10px 0;
                   7354:   /* overflow: hidden; */
1.693     droeschl 7355: }
1.795     www      7356: 
1.1211    raeburn  7357: article.geogebraweb div {
                   7358:     margin: 0;
                   7359: }
                   7360: 
1.838     bisitz   7361: fieldset > legend {
1.911     bisitz   7362:   font-weight: bold;
                   7363:   padding: 0 5px 0 5px;
1.838     bisitz   7364: }
                   7365: 
1.813     bisitz   7366: #LC_nav_bar {
1.911     bisitz   7367:   float: left;
1.995     raeburn  7368:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7369:   margin: 0 0 2px 0;
1.807     droeschl 7370: }
                   7371: 
1.916     droeschl 7372: #LC_realm {
                   7373:   margin: 0.2em 0 0 0;
                   7374:   padding: 0;
                   7375:   font-weight: bold;
                   7376:   text-align: center;
1.995     raeburn  7377:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7378: }
                   7379: 
1.911     bisitz   7380: #LC_nav_bar em {
                   7381:   font-weight: bold;
                   7382:   font-style: normal;
1.807     droeschl 7383: }
                   7384: 
1.897     wenzelju 7385: ol.LC_primary_menu {
1.934     droeschl 7386:   margin: 0;
1.1076    raeburn  7387:   padding: 0;
1.807     droeschl 7388: }
                   7389: 
1.852     droeschl 7390: ol#LC_PathBreadcrumbs {
1.911     bisitz   7391:   margin: 0;
1.693     droeschl 7392: }
                   7393: 
1.897     wenzelju 7394: ol.LC_primary_menu li {
1.1076    raeburn  7395:   color: RGB(80, 80, 80);
                   7396:   vertical-align: middle;
                   7397:   text-align: left;
                   7398:   list-style: none;
1.1205    golterma 7399:   position: relative;
1.1076    raeburn  7400:   float: left;
1.1205    golterma 7401:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7402:   line-height: 1.5em;
1.1076    raeburn  7403: }
                   7404: 
1.1205    golterma 7405: ol.LC_primary_menu li a,
                   7406: ol.LC_primary_menu li p {
1.1076    raeburn  7407:   display: block;
                   7408:   margin: 0;
                   7409:   padding: 0 5px 0 10px;
                   7410:   text-decoration: none;
                   7411: }
                   7412: 
1.1205    golterma 7413: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7414:   display: inline-block;
                   7415:   width: 95%;
                   7416:   text-align: left;
                   7417: }
                   7418: 
                   7419: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7420:   display: inline-block;	
                   7421:   width: 5%;
                   7422:   float: right;
                   7423:   text-align: right;
                   7424:   font-size: 70%;
                   7425: }
                   7426: 
                   7427: ol.LC_primary_menu ul {
1.1076    raeburn  7428:   display: none;
1.1205    golterma 7429:   width: 15em;
1.1076    raeburn  7430:   background-color: $data_table_light;
1.1205    golterma 7431:   position: absolute;
                   7432:   top: 100%;
1.1076    raeburn  7433: }
                   7434: 
1.1205    golterma 7435: ol.LC_primary_menu ul ul {
                   7436:   left: 100%;
                   7437:   top: 0;
                   7438: }
                   7439: 
                   7440: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7441:   display: block;
                   7442:   position: absolute;
                   7443:   margin: 0;
                   7444:   padding: 0;
1.1078    raeburn  7445:   z-index: 2;
1.1076    raeburn  7446: }
                   7447: 
                   7448: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7449: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7450:   font-size: 90%;
1.911     bisitz   7451:   vertical-align: top;
1.1076    raeburn  7452:   float: none;
1.1079    raeburn  7453:   border-left: 1px solid black;
                   7454:   border-right: 1px solid black;
1.1205    golterma 7455: /* A dark bottom border to visualize different menu options; 
                   7456: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7457:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7458: }
                   7459: 
1.1205    golterma 7460: ol.LC_primary_menu li li p:hover {
                   7461:   color:$button_hover;
                   7462:   text-decoration:none;
                   7463:   background-color:$data_table_dark;
1.1076    raeburn  7464: }
                   7465: 
                   7466: ol.LC_primary_menu li li a:hover {
                   7467:    color:$button_hover;
                   7468:    background-color:$data_table_dark;
1.693     droeschl 7469: }
                   7470: 
1.1205    golterma 7471: /* Font-size equal to the size of the predecessors*/
                   7472: ol.LC_primary_menu li:hover li li {
                   7473:   font-size: 100%;
                   7474: }
                   7475: 
1.897     wenzelju 7476: ol.LC_primary_menu li img {
1.911     bisitz   7477:   vertical-align: bottom;
1.934     droeschl 7478:   height: 1.1em;
1.1077    raeburn  7479:   margin: 0.2em 0 0 0;
1.693     droeschl 7480: }
                   7481: 
1.897     wenzelju 7482: ol.LC_primary_menu a {
1.911     bisitz   7483:   color: RGB(80, 80, 80);
                   7484:   text-decoration: none;
1.693     droeschl 7485: }
1.795     www      7486: 
1.949     droeschl 7487: ol.LC_primary_menu a.LC_new_message {
                   7488:   font-weight:bold;
                   7489:   color: darkred;
                   7490: }
                   7491: 
1.975     raeburn  7492: ol.LC_docs_parameters {
                   7493:   margin-left: 0;
                   7494:   padding: 0;
                   7495:   list-style: none;
                   7496: }
                   7497: 
                   7498: ol.LC_docs_parameters li {
                   7499:   margin: 0;
                   7500:   padding-right: 20px;
                   7501:   display: inline;
                   7502: }
                   7503: 
1.976     raeburn  7504: ol.LC_docs_parameters li:before {
                   7505:   content: "\\002022 \\0020";
                   7506: }
                   7507: 
                   7508: li.LC_docs_parameters_title {
                   7509:   font-weight: bold;
                   7510: }
                   7511: 
                   7512: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7513:   content: "";
                   7514: }
                   7515: 
1.897     wenzelju 7516: ul#LC_secondary_menu {
1.1107    raeburn  7517:   clear: right;
1.911     bisitz   7518:   color: $fontmenu;
                   7519:   background: $tabbg;
                   7520:   list-style: none;
                   7521:   padding: 0;
                   7522:   margin: 0;
                   7523:   width: 100%;
1.995     raeburn  7524:   text-align: left;
1.1107    raeburn  7525:   float: left;
1.808     droeschl 7526: }
                   7527: 
1.897     wenzelju 7528: ul#LC_secondary_menu li {
1.911     bisitz   7529:   font-weight: bold;
                   7530:   line-height: 1.8em;
1.1107    raeburn  7531:   border-right: 1px solid black;
                   7532:   float: left;
                   7533: }
                   7534: 
                   7535: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7536:   background-color: $data_table_light;
                   7537: }
                   7538: 
                   7539: ul#LC_secondary_menu li a {
1.911     bisitz   7540:   padding: 0 0.8em;
1.1107    raeburn  7541: }
                   7542: 
                   7543: ul#LC_secondary_menu li ul {
                   7544:   display: none;
                   7545: }
                   7546: 
                   7547: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7548:   display: block;
                   7549:   position: absolute;
                   7550:   margin: 0;
                   7551:   padding: 0;
                   7552:   list-style:none;
                   7553:   float: none;
                   7554:   background-color: $data_table_light;
                   7555:   z-index: 2;
                   7556:   margin-left: -1px;
                   7557: }
                   7558: 
                   7559: ul#LC_secondary_menu li ul li {
                   7560:   font-size: 90%;
                   7561:   vertical-align: top;
                   7562:   border-left: 1px solid black;
1.911     bisitz   7563:   border-right: 1px solid black;
1.1119    raeburn  7564:   background-color: $data_table_light;
1.1107    raeburn  7565:   list-style:none;
                   7566:   float: none;
                   7567: }
                   7568: 
                   7569: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7570:   background-color: $data_table_dark;
1.807     droeschl 7571: }
                   7572: 
1.847     tempelho 7573: ul.LC_TabContent {
1.911     bisitz   7574:   display:block;
                   7575:   background: $sidebg;
                   7576:   border-bottom: solid 1px $lg_border_color;
                   7577:   list-style:none;
1.1020    raeburn  7578:   margin: -1px -10px 0 -10px;
1.911     bisitz   7579:   padding: 0;
1.693     droeschl 7580: }
                   7581: 
1.795     www      7582: ul.LC_TabContent li,
                   7583: ul.LC_TabContentBigger li {
1.911     bisitz   7584:   float:left;
1.741     harmsja  7585: }
1.795     www      7586: 
1.897     wenzelju 7587: ul#LC_secondary_menu li a {
1.911     bisitz   7588:   color: $fontmenu;
                   7589:   text-decoration: none;
1.693     droeschl 7590: }
1.795     www      7591: 
1.721     harmsja  7592: ul.LC_TabContent {
1.952     onken    7593:   min-height:20px;
1.721     harmsja  7594: }
1.795     www      7595: 
                   7596: ul.LC_TabContent li {
1.911     bisitz   7597:   vertical-align:middle;
1.959     onken    7598:   padding: 0 16px 0 10px;
1.911     bisitz   7599:   background-color:$tabbg;
                   7600:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7601:   border-left: solid 1px $font;
1.721     harmsja  7602: }
1.795     www      7603: 
1.847     tempelho 7604: ul.LC_TabContent .right {
1.911     bisitz   7605:   float:right;
1.847     tempelho 7606: }
                   7607: 
1.911     bisitz   7608: ul.LC_TabContent li a,
                   7609: ul.LC_TabContent li {
                   7610:   color:rgb(47,47,47);
                   7611:   text-decoration:none;
                   7612:   font-size:95%;
                   7613:   font-weight:bold;
1.952     onken    7614:   min-height:20px;
                   7615: }
                   7616: 
1.959     onken    7617: ul.LC_TabContent li a:hover,
                   7618: ul.LC_TabContent li a:focus {
1.952     onken    7619:   color: $button_hover;
1.959     onken    7620:   background:none;
                   7621:   outline:none;
1.952     onken    7622: }
                   7623: 
                   7624: ul.LC_TabContent li:hover {
                   7625:   color: $button_hover;
                   7626:   cursor:pointer;
1.721     harmsja  7627: }
1.795     www      7628: 
1.911     bisitz   7629: ul.LC_TabContent li.active {
1.952     onken    7630:   color: $font;
1.911     bisitz   7631:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7632:   border-bottom:solid 1px #FFFFFF;
                   7633:   cursor: default;
1.744     ehlerst  7634: }
1.795     www      7635: 
1.959     onken    7636: ul.LC_TabContent li.active a {
                   7637:   color:$font;
                   7638:   background:#FFFFFF;
                   7639:   outline: none;
                   7640: }
1.1047    raeburn  7641: 
                   7642: ul.LC_TabContent li.goback {
                   7643:   float: left;
                   7644:   border-left: none;
                   7645: }
                   7646: 
1.870     tempelho 7647: #maincoursedoc {
1.911     bisitz   7648:   clear:both;
1.870     tempelho 7649: }
                   7650: 
                   7651: ul.LC_TabContentBigger {
1.911     bisitz   7652:   display:block;
                   7653:   list-style:none;
                   7654:   padding: 0;
1.870     tempelho 7655: }
                   7656: 
1.795     www      7657: ul.LC_TabContentBigger li {
1.911     bisitz   7658:   vertical-align:bottom;
                   7659:   height: 30px;
                   7660:   font-size:110%;
                   7661:   font-weight:bold;
                   7662:   color: #737373;
1.841     tempelho 7663: }
                   7664: 
1.957     onken    7665: ul.LC_TabContentBigger li.active {
                   7666:   position: relative;
                   7667:   top: 1px;
                   7668: }
                   7669: 
1.870     tempelho 7670: ul.LC_TabContentBigger li a {
1.911     bisitz   7671:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7672:   height: 30px;
                   7673:   line-height: 30px;
                   7674:   text-align: center;
                   7675:   display: block;
                   7676:   text-decoration: none;
1.958     onken    7677:   outline: none;  
1.741     harmsja  7678: }
1.795     www      7679: 
1.870     tempelho 7680: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7681:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7682:   color:$font;
1.744     ehlerst  7683: }
1.795     www      7684: 
1.870     tempelho 7685: ul.LC_TabContentBigger li b {
1.911     bisitz   7686:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7687:   display: block;
                   7688:   float: left;
                   7689:   padding: 0 30px;
1.957     onken    7690:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7691: }
                   7692: 
1.956     onken    7693: ul.LC_TabContentBigger li:hover b {
                   7694:   color:$button_hover;
                   7695: }
                   7696: 
1.870     tempelho 7697: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7698:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7699:   color:$font;
1.957     onken    7700:   border: 0;
1.741     harmsja  7701: }
1.693     droeschl 7702: 
1.870     tempelho 7703: 
1.862     bisitz   7704: ul.LC_CourseBreadcrumbs {
                   7705:   background: $sidebg;
1.1020    raeburn  7706:   height: 2em;
1.862     bisitz   7707:   padding-left: 10px;
1.1020    raeburn  7708:   margin: 0;
1.862     bisitz   7709:   list-style-position: inside;
                   7710: }
                   7711: 
1.911     bisitz   7712: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7713: ol#LC_PathBreadcrumbs {
1.911     bisitz   7714:   padding-left: 10px;
                   7715:   margin: 0;
1.933     droeschl 7716:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7717: }
                   7718: 
1.911     bisitz   7719: ol#LC_MenuBreadcrumbs li,
                   7720: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7721: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7722:   display: inline;
1.933     droeschl 7723:   white-space: normal;  
1.693     droeschl 7724: }
                   7725: 
1.823     bisitz   7726: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7727: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7728:   text-decoration: none;
                   7729:   font-size:90%;
1.693     droeschl 7730: }
1.795     www      7731: 
1.969     droeschl 7732: ol#LC_MenuBreadcrumbs h1 {
                   7733:   display: inline;
                   7734:   font-size: 90%;
                   7735:   line-height: 2.5em;
                   7736:   margin: 0;
                   7737:   padding: 0;
                   7738: }
                   7739: 
1.795     www      7740: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7741:   text-decoration:none;
                   7742:   font-size:100%;
                   7743:   font-weight:bold;
1.693     droeschl 7744: }
1.795     www      7745: 
1.840     bisitz   7746: .LC_Box {
1.911     bisitz   7747:   border: solid 1px $lg_border_color;
                   7748:   padding: 0 10px 10px 10px;
1.746     neumanie 7749: }
1.795     www      7750: 
1.1020    raeburn  7751: .LC_DocsBox {
                   7752:   border: solid 1px $lg_border_color;
                   7753:   padding: 0 0 10px 10px;
                   7754: }
                   7755: 
1.795     www      7756: .LC_AboutMe_Image {
1.911     bisitz   7757:   float:left;
                   7758:   margin-right:10px;
1.747     neumanie 7759: }
1.795     www      7760: 
                   7761: .LC_Clear_AboutMe_Image {
1.911     bisitz   7762:   clear:left;
1.747     neumanie 7763: }
1.795     www      7764: 
1.721     harmsja  7765: dl.LC_ListStyleClean dt {
1.911     bisitz   7766:   padding-right: 5px;
                   7767:   display: table-header-group;
1.693     droeschl 7768: }
                   7769: 
1.721     harmsja  7770: dl.LC_ListStyleClean dd {
1.911     bisitz   7771:   display: table-row;
1.693     droeschl 7772: }
                   7773: 
1.721     harmsja  7774: .LC_ListStyleClean,
                   7775: .LC_ListStyleSimple,
                   7776: .LC_ListStyleNormal,
1.795     www      7777: .LC_ListStyleSpecial {
1.911     bisitz   7778:   /* display:block; */
                   7779:   list-style-position: inside;
                   7780:   list-style-type: none;
                   7781:   overflow: hidden;
                   7782:   padding: 0;
1.693     droeschl 7783: }
                   7784: 
1.721     harmsja  7785: .LC_ListStyleSimple li,
                   7786: .LC_ListStyleSimple dd,
                   7787: .LC_ListStyleNormal li,
                   7788: .LC_ListStyleNormal dd,
                   7789: .LC_ListStyleSpecial li,
1.795     www      7790: .LC_ListStyleSpecial dd {
1.911     bisitz   7791:   margin: 0;
                   7792:   padding: 5px 5px 5px 10px;
                   7793:   clear: both;
1.693     droeschl 7794: }
                   7795: 
1.721     harmsja  7796: .LC_ListStyleClean li,
                   7797: .LC_ListStyleClean dd {
1.911     bisitz   7798:   padding-top: 0;
                   7799:   padding-bottom: 0;
1.693     droeschl 7800: }
                   7801: 
1.721     harmsja  7802: .LC_ListStyleSimple dd,
1.795     www      7803: .LC_ListStyleSimple li {
1.911     bisitz   7804:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7805: }
                   7806: 
1.721     harmsja  7807: .LC_ListStyleSpecial li,
                   7808: .LC_ListStyleSpecial dd {
1.911     bisitz   7809:   list-style-type: none;
                   7810:   background-color: RGB(220, 220, 220);
                   7811:   margin-bottom: 4px;
1.693     droeschl 7812: }
                   7813: 
1.721     harmsja  7814: table.LC_SimpleTable {
1.911     bisitz   7815:   margin:5px;
                   7816:   border:solid 1px $lg_border_color;
1.795     www      7817: }
1.693     droeschl 7818: 
1.721     harmsja  7819: table.LC_SimpleTable tr {
1.911     bisitz   7820:   padding: 0;
                   7821:   border:solid 1px $lg_border_color;
1.693     droeschl 7822: }
1.795     www      7823: 
                   7824: table.LC_SimpleTable thead {
1.911     bisitz   7825:   background:rgb(220,220,220);
1.693     droeschl 7826: }
                   7827: 
1.721     harmsja  7828: div.LC_columnSection {
1.911     bisitz   7829:   display: block;
                   7830:   clear: both;
                   7831:   overflow: hidden;
                   7832:   margin: 0;
1.693     droeschl 7833: }
                   7834: 
1.721     harmsja  7835: div.LC_columnSection>* {
1.911     bisitz   7836:   float: left;
                   7837:   margin: 10px 20px 10px 0;
                   7838:   overflow:hidden;
1.693     droeschl 7839: }
1.721     harmsja  7840: 
1.795     www      7841: table em {
1.911     bisitz   7842:   font-weight: bold;
                   7843:   font-style: normal;
1.748     schulted 7844: }
1.795     www      7845: 
1.779     bisitz   7846: table.LC_tableBrowseRes,
1.795     www      7847: table.LC_tableOfContent {
1.911     bisitz   7848:   border:none;
                   7849:   border-spacing: 1px;
                   7850:   padding: 3px;
                   7851:   background-color: #FFFFFF;
                   7852:   font-size: 90%;
1.753     droeschl 7853: }
1.789     droeschl 7854: 
1.911     bisitz   7855: table.LC_tableOfContent {
                   7856:   border-collapse: collapse;
1.789     droeschl 7857: }
                   7858: 
1.771     droeschl 7859: table.LC_tableBrowseRes a,
1.768     schulted 7860: table.LC_tableOfContent a {
1.911     bisitz   7861:   background-color: transparent;
                   7862:   text-decoration: none;
1.753     droeschl 7863: }
                   7864: 
1.795     www      7865: table.LC_tableOfContent img {
1.911     bisitz   7866:   border: none;
                   7867:   height: 1.3em;
                   7868:   vertical-align: text-bottom;
                   7869:   margin-right: 0.3em;
1.753     droeschl 7870: }
1.757     schulted 7871: 
1.795     www      7872: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7873:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7874: }
                   7875: 
1.795     www      7876: a#LC_content_toolbar_everything {
1.911     bisitz   7877:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7878: }
                   7879: 
1.795     www      7880: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7881:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7882: }
                   7883: 
1.795     www      7884: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7885:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7886: }
                   7887: 
1.795     www      7888: a#LC_content_toolbar_changefolder {
1.911     bisitz   7889:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7890: }
                   7891: 
1.795     www      7892: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7893:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7894: }
                   7895: 
1.1043    raeburn  7896: a#LC_content_toolbar_edittoplevel {
                   7897:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7898: }
                   7899: 
1.795     www      7900: ul#LC_toolbar li a:hover {
1.911     bisitz   7901:   background-position: bottom center;
1.757     schulted 7902: }
                   7903: 
1.795     www      7904: ul#LC_toolbar {
1.911     bisitz   7905:   padding: 0;
                   7906:   margin: 2px;
                   7907:   list-style:none;
                   7908:   position:relative;
                   7909:   background-color:white;
1.1082    raeburn  7910:   overflow: auto;
1.757     schulted 7911: }
                   7912: 
1.795     www      7913: ul#LC_toolbar li {
1.911     bisitz   7914:   border:1px solid white;
                   7915:   padding: 0;
                   7916:   margin: 0;
                   7917:   float: left;
                   7918:   display:inline;
                   7919:   vertical-align:middle;
1.1082    raeburn  7920:   white-space: nowrap;
1.911     bisitz   7921: }
1.757     schulted 7922: 
1.783     amueller 7923: 
1.795     www      7924: a.LC_toolbarItem {
1.911     bisitz   7925:   display:block;
                   7926:   padding: 0;
                   7927:   margin: 0;
                   7928:   height: 32px;
                   7929:   width: 32px;
                   7930:   color:white;
                   7931:   border: none;
                   7932:   background-repeat:no-repeat;
                   7933:   background-color:transparent;
1.757     schulted 7934: }
                   7935: 
1.915     droeschl 7936: ul.LC_funclist {
                   7937:     margin: 0;
                   7938:     padding: 0.5em 1em 0.5em 0;
                   7939: }
                   7940: 
1.933     droeschl 7941: ul.LC_funclist > li:first-child {
                   7942:     font-weight:bold; 
                   7943:     margin-left:0.8em;
                   7944: }
                   7945: 
1.915     droeschl 7946: ul.LC_funclist + ul.LC_funclist {
                   7947:     /* 
                   7948:        left border as a seperator if we have more than
                   7949:        one list 
                   7950:     */
                   7951:     border-left: 1px solid $sidebg;
                   7952:     /* 
                   7953:        this hides the left border behind the border of the 
                   7954:        outer box if element is wrapped to the next 'line' 
                   7955:     */
                   7956:     margin-left: -1px;
                   7957: }
                   7958: 
1.843     bisitz   7959: ul.LC_funclist li {
1.915     droeschl 7960:   display: inline;
1.782     bisitz   7961:   white-space: nowrap;
1.915     droeschl 7962:   margin: 0 0 0 25px;
                   7963:   line-height: 150%;
1.782     bisitz   7964: }
                   7965: 
1.974     wenzelju 7966: .LC_hidden {
                   7967:   display: none;
                   7968: }
                   7969: 
1.1030    www      7970: .LCmodal-overlay {
                   7971: 		position:fixed;
                   7972: 		top:0;
                   7973: 		right:0;
                   7974: 		bottom:0;
                   7975: 		left:0;
                   7976: 		height:100%;
                   7977: 		width:100%;
                   7978: 		margin:0;
                   7979: 		padding:0;
                   7980: 		background:#999;
                   7981: 		opacity:.75;
                   7982: 		filter: alpha(opacity=75);
                   7983: 		-moz-opacity: 0.75;
                   7984: 		z-index:101;
                   7985: }
                   7986: 
                   7987: * html .LCmodal-overlay {   
                   7988: 		position: absolute;
                   7989: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7990: }
                   7991: 
                   7992: .LCmodal-window {
                   7993: 		position:fixed;
                   7994: 		top:50%;
                   7995: 		left:50%;
                   7996: 		margin:0;
                   7997: 		padding:0;
                   7998: 		z-index:102;
                   7999: 	}
                   8000: 
                   8001: * html .LCmodal-window {
                   8002: 		position:absolute;
                   8003: }
                   8004: 
                   8005: .LCclose-window {
                   8006: 		position:absolute;
                   8007: 		width:32px;
                   8008: 		height:32px;
                   8009: 		right:8px;
                   8010: 		top:8px;
                   8011: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8012: 		text-indent:-99999px;
                   8013: 		overflow:hidden;
                   8014: 		cursor:pointer;
                   8015: }
                   8016: 
1.1100    raeburn  8017: /*
1.1231    damieng  8018:   styles used for response display
                   8019: */
                   8020: div.LC_radiofoil, div.LC_rankfoil {
                   8021:   margin: .5em 0em .5em 0em;
                   8022: }
                   8023: table.LC_itemgroup {
                   8024:   margin-top: 1em;
                   8025: }
                   8026: 
                   8027: /*
1.1100    raeburn  8028:   styles used by TTH when "Default set of options to pass to tth/m
                   8029:   when converting TeX" in course settings has been set
                   8030: 
                   8031:   option passed: -t
                   8032: 
                   8033: */
                   8034: 
                   8035: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8036: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8037: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8038: td div.norm {line-height:normal;}
                   8039: 
                   8040: /*
                   8041:   option passed -y3
                   8042: */
                   8043: 
                   8044: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8045: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8046: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8047: 
1.1230    damieng  8048: /*
                   8049:   sections with roles, for content only
                   8050: */
                   8051: section[class^="role-"] {
                   8052:   padding-left: 10px;
                   8053:   padding-right: 5px;
                   8054:   margin-top: 8px;
                   8055:   margin-bottom: 8px;
                   8056:   border: 1px solid #2A4;
                   8057:   border-radius: 5px;
                   8058:   box-shadow: 0px 1px 1px #BBB;
                   8059: }
                   8060: section[class^="role-"]>h1 {
                   8061:   position: relative;
                   8062:   margin: 0px;
                   8063:   padding-top: 10px;
                   8064:   padding-left: 40px;
                   8065: }
                   8066: section[class^="role-"]>h1:before {
                   8067:   position: absolute;
                   8068:   left: -5px;
                   8069:   top: 5px;
                   8070: }
                   8071: section.role-activity>h1:before {
                   8072:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8073: }
                   8074: section.role-advice>h1:before {
                   8075:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8076: }
                   8077: section.role-bibliography>h1:before {
                   8078:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8079: }
                   8080: section.role-citation>h1:before {
                   8081:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8082: }
                   8083: section.role-conclusion>h1:before {
                   8084:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8085: }
                   8086: section.role-definition>h1:before {
                   8087:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8088: }
                   8089: section.role-demonstration>h1:before {
                   8090:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8091: }
                   8092: section.role-example>h1:before {
                   8093:   content:url('/adm/daxe/images/section_icons/example.png');
                   8094: }
                   8095: section.role-explanation>h1:before {
                   8096:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8097: }
                   8098: section.role-introduction>h1:before {
                   8099:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8100: }
                   8101: section.role-method>h1:before {
                   8102:   content:url('/adm/daxe/images/section_icons/method.png');
                   8103: }
                   8104: section.role-more_information>h1:before {
                   8105:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8106: }
                   8107: section.role-objectives>h1:before {
                   8108:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8109: }
                   8110: section.role-prerequisites>h1:before {
                   8111:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8112: }
                   8113: section.role-remark>h1:before {
                   8114:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8115: }
                   8116: section.role-reminder>h1:before {
                   8117:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8118: }
                   8119: section.role-summary>h1:before {
                   8120:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8121: }
                   8122: section.role-syntax>h1:before {
                   8123:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8124: }
                   8125: section.role-warning>h1:before {
                   8126:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8127: }
                   8128: 
1.1269  ! raeburn  8129: #LC_minitab_header {
        !          8130:   float:left;
        !          8131:   width:100%;
        !          8132:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
        !          8133:   font-size:93%;
        !          8134:   line-height:normal;
        !          8135:   margin: 0.5em 0 0.5em 0;
        !          8136: }
        !          8137: #LC_minitab_header ul {
        !          8138:   margin:0;
        !          8139:   padding:10px 10px 0;
        !          8140:   list-style:none;
        !          8141: }
        !          8142: #LC_minitab_header li {
        !          8143:   float:left;
        !          8144:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
        !          8145:   margin:0;
        !          8146:   padding:0 0 0 9px;
        !          8147: }
        !          8148: #LC_minitab_header a {
        !          8149:   display:block;
        !          8150:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
        !          8151:   padding:5px 15px 4px 6px;
        !          8152: }
        !          8153: #LC_minitab_header #LC_current_minitab {
        !          8154:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
        !          8155: }
        !          8156: #LC_minitab_header #LC_current_minitab a {
        !          8157:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
        !          8158:   padding-bottom:5px;
        !          8159: }
        !          8160: 
        !          8161: 
1.343     albertel 8162: END
                   8163: }
                   8164: 
1.306     albertel 8165: =pod
                   8166: 
                   8167: =item * &headtag()
                   8168: 
                   8169: Returns a uniform footer for LON-CAPA web pages.
                   8170: 
1.307     albertel 8171: Inputs: $title - optional title for the head
                   8172:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8173:         $args - optional arguments
1.319     albertel 8174:             force_register - if is true call registerurl so the remote is 
                   8175:                              informed
1.415     albertel 8176:             redirect       -> array ref of
                   8177:                                    1- seconds before redirect occurs
                   8178:                                    2- url to redirect to
                   8179:                                    3- whether the side effect should occur
1.315     albertel 8180:                            (side effect of setting 
                   8181:                                $env{'internal.head.redirect'} to the url 
                   8182:                                redirected too)
1.352     albertel 8183:             domain         -> force to color decorate a page for a specific
                   8184:                                domain
                   8185:             function       -> force usage of a specific rolish color scheme
                   8186:             bgcolor        -> override the default page bgcolor
1.460     albertel 8187:             no_auto_mt_title
                   8188:                            -> prevent &mt()ing the title arg
1.464     albertel 8189: 
1.306     albertel 8190: =cut
                   8191: 
                   8192: sub headtag {
1.313     albertel 8193:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8194:     
1.363     albertel 8195:     my $function = $args->{'function'} || &get_users_function();
                   8196:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8197:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8198:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8199:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8200: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8201: 		   #time(),
1.418     albertel 8202: 		   $env{'environment.color.timestamp'},
1.363     albertel 8203: 		   $function,$domain,$bgcolor);
                   8204: 
1.369     www      8205:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8206: 
1.308     albertel 8207:     my $result =
                   8208: 	'<head>'.
1.1160    raeburn  8209: 	&font_settings($args);
1.319     albertel 8210: 
1.1188    raeburn  8211:     my $inhibitprint;
                   8212:     if ($args->{'print_suppress'}) {
                   8213:         $inhibitprint = &print_suppression();
                   8214:     }
1.1064    raeburn  8215: 
1.461     albertel 8216:     if (!$args->{'frameset'}) {
                   8217: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8218:     }
1.962     droeschl 8219:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8220:         $result .= Apache::lonxml::display_title();
1.319     albertel 8221:     }
1.436     albertel 8222:     if (!$args->{'no_nav_bar'} 
                   8223: 	&& !$args->{'only_body'}
                   8224: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8225: 	$result .= &help_menu_js($httphost);
1.1032    www      8226:         $result.=&modal_window();
1.1038    www      8227:         $result.=&togglebox_script();
1.1034    www      8228:         $result.=&wishlist_window();
1.1041    www      8229:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8230:     } else {
                   8231:         if ($args->{'add_modal'}) {
                   8232:            $result.=&modal_window();
                   8233:         }
                   8234:         if ($args->{'add_wishlist'}) {
                   8235:            $result.=&wishlist_window();
                   8236:         }
1.1038    www      8237:         if ($args->{'add_togglebox'}) {
                   8238:            $result.=&togglebox_script();
                   8239:         }
1.1041    www      8240:         if ($args->{'add_progressbar'}) {
                   8241:            $result.=&LCprogressbarUpdate_script();
                   8242:         }
1.436     albertel 8243:     }
1.314     albertel 8244:     if (ref($args->{'redirect'})) {
1.414     albertel 8245: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8246: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8247: 	if (!$inhibit_continue) {
                   8248: 	    $env{'internal.head.redirect'} = $url;
                   8249: 	}
1.313     albertel 8250: 	$result.=<<ADDMETA
                   8251: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8252: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8253: ADDMETA
1.1210    raeburn  8254:     } else {
                   8255:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8256:             my $requrl = $env{'request.uri'};
                   8257:             if ($requrl eq '') {
                   8258:                 $requrl = $ENV{'REQUEST_URI'};
                   8259:                 $requrl =~ s/\?.+$//;
                   8260:             }
                   8261:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8262:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8263:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8264:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8265:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8266:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   8267:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8268:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   8269:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   8270:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8271:                             if (($newserver) && ($newserver ne $lonhost)) {
                   8272:                                 my $numsec = 5;
                   8273:                                 my $timeout = $numsec * 1000;
                   8274:                                 my ($newurl,$locknum,%locks,$msg);
                   8275:                                 if ($env{'request.role.adv'}) {
                   8276:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8277:                                 }
                   8278:                                 my $disable_submit = 0;
                   8279:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   8280:                                     $disable_submit = 1;
                   8281:                                 }
                   8282:                                 if ($locknum) {
                   8283:                                     my @lockinfo = sort(values(%locks));
                   8284:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   8285:                                            join(", ",sort(values(%locks)))."\\n".
                   8286:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   8287:                                 } else {
                   8288:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8289:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   8290:                                     }
                   8291:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8292:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8293:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8294:                                         $newurl .= '&role='.$env{'request.role'};
                   8295:                                     }
                   8296:                                     if ($env{'request.symb'}) {
                   8297:                                         $newurl .= '&symb='.$env{'request.symb'};
                   8298:                                     } else {
                   8299:                                         $newurl .= '&origurl='.$requrl;
                   8300:                                     }
                   8301:                                 }
1.1222    damieng  8302:                                 &js_escape(\$msg);
1.1210    raeburn  8303:                                 $result.=<<OFFLOAD
                   8304: <meta http-equiv="pragma" content="no-cache" />
                   8305: <script type="text/javascript">
1.1215    raeburn  8306: // <![CDATA[
1.1210    raeburn  8307: function LC_Offload_Now() {
                   8308:     var dest = "$newurl";
                   8309:     if (dest != '') {
                   8310:         window.location.href="$newurl";
                   8311:     }
                   8312: }
1.1214    raeburn  8313: \$(document).ready(function () {
                   8314:     window.alert('$msg');
                   8315:     if ($disable_submit) {
1.1210    raeburn  8316:         \$(".LC_hwk_submit").prop("disabled", true);
                   8317:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8318:     }
                   8319:     setTimeout('LC_Offload_Now()', $timeout);
                   8320: });
1.1215    raeburn  8321: // ]]>
1.1210    raeburn  8322: </script>
                   8323: OFFLOAD
                   8324:                             }
                   8325:                         }
                   8326:                     }
                   8327:                 }
                   8328:             }
                   8329:         }
1.313     albertel 8330:     }
1.306     albertel 8331:     if (!defined($title)) {
                   8332: 	$title = 'The LearningOnline Network with CAPA';
                   8333:     }
1.460     albertel 8334:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8335:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8336: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8337:     if (!$args->{'frameset'}) {
                   8338:         $result .= ' /';
                   8339:     }
                   8340:     $result .= '>' 
1.1064    raeburn  8341:         .$inhibitprint
1.414     albertel 8342: 	.$head_extra;
1.1242    raeburn  8343:     my $clientmobile;
                   8344:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8345:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8346:     } else {
                   8347:         $clientmobile = $env{'browser.mobile'};
                   8348:     }
                   8349:     if ($clientmobile) {
1.1137    raeburn  8350:         $result .= '
                   8351: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8352: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8353:     }
1.962     droeschl 8354:     return $result.'</head>';
1.306     albertel 8355: }
                   8356: 
                   8357: =pod
                   8358: 
1.340     albertel 8359: =item * &font_settings()
                   8360: 
                   8361: Returns neccessary <meta> to set the proper encoding
                   8362: 
1.1160    raeburn  8363: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8364: 
                   8365: =cut
                   8366: 
                   8367: sub font_settings {
1.1160    raeburn  8368:     my ($args) = @_;
1.340     albertel 8369:     my $headerstring='';
1.1160    raeburn  8370:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8371:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8372:         $headerstring.=
                   8373:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8374:         if (!$args->{'frameset'}) {
                   8375: 	    $headerstring.= ' /';
                   8376:         }
                   8377: 	$headerstring .= '>'."\n";
1.340     albertel 8378:     }
                   8379:     return $headerstring;
                   8380: }
                   8381: 
1.341     albertel 8382: =pod
                   8383: 
1.1064    raeburn  8384: =item * &print_suppression()
                   8385: 
                   8386: In course context returns css which causes the body to be blank when media="print",
                   8387: if printout generation is unavailable for the current resource.
                   8388: 
                   8389: This could be because:
                   8390: 
                   8391: (a) printstartdate is in the future
                   8392: 
                   8393: (b) printenddate is in the past
                   8394: 
                   8395: (c) there is an active exam block with "printout"
                   8396: functionality blocked
                   8397: 
                   8398: Users with pav, pfo or evb privileges are exempt.
                   8399: 
                   8400: Inputs: none
                   8401: 
                   8402: =cut
                   8403: 
                   8404: 
                   8405: sub print_suppression {
                   8406:     my $noprint;
                   8407:     if ($env{'request.course.id'}) {
                   8408:         my $scope = $env{'request.course.id'};
                   8409:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8410:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8411:             return;
                   8412:         }
                   8413:         if ($env{'request.course.sec'} ne '') {
                   8414:             $scope .= "/$env{'request.course.sec'}";
                   8415:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8416:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8417:                 return;
1.1064    raeburn  8418:             }
                   8419:         }
                   8420:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8421:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8422:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8423:         if ($blocked) {
                   8424:             my $checkrole = "cm./$cdom/$cnum";
                   8425:             if ($env{'request.course.sec'} ne '') {
                   8426:                 $checkrole .= "/$env{'request.course.sec'}";
                   8427:             }
                   8428:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8429:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8430:                 $noprint = 1;
                   8431:             }
                   8432:         }
                   8433:         unless ($noprint) {
                   8434:             my $symb = &Apache::lonnet::symbread();
                   8435:             if ($symb ne '') {
                   8436:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8437:                 if (ref($navmap)) {
                   8438:                     my $res = $navmap->getBySymb($symb);
                   8439:                     if (ref($res)) {
                   8440:                         if (!$res->resprintable()) {
                   8441:                             $noprint = 1;
                   8442:                         }
                   8443:                     }
                   8444:                 }
                   8445:             }
                   8446:         }
                   8447:         if ($noprint) {
                   8448:             return <<"ENDSTYLE";
                   8449: <style type="text/css" media="print">
                   8450:     body { display:none }
                   8451: </style>
                   8452: ENDSTYLE
                   8453:         }
                   8454:     }
                   8455:     return;
                   8456: }
                   8457: 
                   8458: =pod
                   8459: 
1.341     albertel 8460: =item * &xml_begin()
                   8461: 
                   8462: Returns the needed doctype and <html>
                   8463: 
                   8464: Inputs: none
                   8465: 
                   8466: =cut
                   8467: 
                   8468: sub xml_begin {
1.1168    raeburn  8469:     my ($is_frameset) = @_;
1.341     albertel 8470:     my $output='';
                   8471: 
                   8472:     if ($env{'browser.mathml'}) {
                   8473: 	$output='<?xml version="1.0"?>'
                   8474:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8475: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8476:             
                   8477: #	    .'<!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">] >'
                   8478: 	    .'<!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">'
                   8479:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8480: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8481:     } elsif ($is_frameset) {
                   8482:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8483:                 '<html>'."\n";
1.341     albertel 8484:     } else {
1.1168    raeburn  8485: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8486:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8487:     }
                   8488:     return $output;
                   8489: }
1.340     albertel 8490: 
                   8491: =pod
                   8492: 
1.306     albertel 8493: =item * &start_page()
                   8494: 
                   8495: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8496: 
1.648     raeburn  8497: Inputs:
                   8498: 
                   8499: =over 4
                   8500: 
                   8501: $title - optional title for the page
                   8502: 
                   8503: $head_extra - optional extra HTML to incude inside the <head>
                   8504: 
                   8505: $args - additional optional args supported are:
                   8506: 
                   8507: =over 8
                   8508: 
                   8509:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8510:                                     arg on
1.814     bisitz   8511:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8512:              add_entries    -> additional attributes to add to the  <body>
                   8513:              domain         -> force to color decorate a page for a 
1.317     albertel 8514:                                     specific domain
1.648     raeburn  8515:              function       -> force usage of a specific rolish color
1.317     albertel 8516:                                     scheme
1.648     raeburn  8517:              redirect       -> see &headtag()
                   8518:              bgcolor        -> override the default page bg color
                   8519:              js_ready       -> return a string ready for being used in 
1.317     albertel 8520:                                     a javascript writeln
1.648     raeburn  8521:              html_encode    -> return a string ready for being used in 
1.320     albertel 8522:                                     a html attribute
1.648     raeburn  8523:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8524:                                     $forcereg arg
1.648     raeburn  8525:              frameset       -> if true will start with a <frameset>
1.330     albertel 8526:                                     rather than <body>
1.648     raeburn  8527:              skip_phases    -> hash ref of 
1.338     albertel 8528:                                     head -> skip the <html><head> generation
                   8529:                                     body -> skip all <body> generation
1.648     raeburn  8530:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8531:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8532:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  8533:              group          -> includes the current group, if page is for a 
                   8534:                                specific group  
1.361     albertel 8535: 
1.648     raeburn  8536: =back
1.460     albertel 8537: 
1.648     raeburn  8538: =back
1.562     albertel 8539: 
1.306     albertel 8540: =cut
                   8541: 
                   8542: sub start_page {
1.309     albertel 8543:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8544:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8545: 
1.315     albertel 8546:     $env{'internal.start_page'}++;
1.1096    raeburn  8547:     my ($result,@advtools);
1.964     droeschl 8548: 
1.338     albertel 8549:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8550:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8551:     }
                   8552:     
                   8553:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8554: 	if ($args->{'frameset'}) {
                   8555: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8556: 						$args->{'add_entries'});
                   8557: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8558:         } else {
                   8559:             $result .=
                   8560:                 &bodytag($title, 
                   8561:                          $args->{'function'},       $args->{'add_entries'},
                   8562:                          $args->{'only_body'},      $args->{'domain'},
                   8563:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8564:                          $args->{'bgcolor'},        $args,
                   8565:                          \@advtools);
1.831     bisitz   8566:         }
1.330     albertel 8567:     }
1.338     albertel 8568: 
1.315     albertel 8569:     if ($args->{'js_ready'}) {
1.713     kaisler  8570: 		$result = &js_ready($result);
1.315     albertel 8571:     }
1.320     albertel 8572:     if ($args->{'html_encode'}) {
1.713     kaisler  8573: 		$result = &html_encode($result);
                   8574:     }
                   8575: 
1.813     bisitz   8576:     # Preparation for new and consistent functionlist at top of screen
                   8577:     # if ($args->{'functionlist'}) {
                   8578:     #            $result .= &build_functionlist();
                   8579:     #}
                   8580: 
1.964     droeschl 8581:     # Don't add anything more if only_body wanted or in const space
                   8582:     return $result if    $args->{'only_body'} 
                   8583:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8584: 
                   8585:     #Breadcrumbs
1.758     kaisler  8586:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8587: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8588: 		#if any br links exists, add them to the breadcrumbs
                   8589: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8590: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8591: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8592: 			}
                   8593: 		}
1.1096    raeburn  8594:                 # if @advtools array contains items add then to the breadcrumbs
                   8595:                 if (@advtools > 0) {
                   8596:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8597:                 }
1.758     kaisler  8598: 
                   8599: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8600: 		if(exists($args->{'bread_crumbs_component'})){
                   8601: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
1.1237    raeburn  8602: 		} elsif ($args->{'crstype'} eq 'Placement') {
                   8603: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','','','','','','','','',
                   8604:                                                                        $args->{'crstype'});
                   8605:                 } else {
1.758     kaisler  8606: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   8607: 		}
1.320     albertel 8608:     }
1.315     albertel 8609:     return $result;
1.306     albertel 8610: }
                   8611: 
                   8612: sub end_page {
1.315     albertel 8613:     my ($args) = @_;
                   8614:     $env{'internal.end_page'}++;
1.330     albertel 8615:     my $result;
1.335     albertel 8616:     if ($args->{'discussion'}) {
                   8617: 	my ($target,$parser);
                   8618: 	if (ref($args->{'discussion'})) {
                   8619: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8620: 				$args->{'discussion'}{'parser'});
                   8621: 	}
                   8622: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8623:     }
1.330     albertel 8624:     if ($args->{'frameset'}) {
                   8625: 	$result .= '</frameset>';
                   8626:     } else {
1.635     raeburn  8627: 	$result .= &endbodytag($args);
1.330     albertel 8628:     }
1.1080    raeburn  8629:     unless ($args->{'notbody'}) {
                   8630:         $result .= "\n</html>";
                   8631:     }
1.330     albertel 8632: 
1.315     albertel 8633:     if ($args->{'js_ready'}) {
1.317     albertel 8634: 	$result = &js_ready($result);
1.315     albertel 8635:     }
1.335     albertel 8636: 
1.320     albertel 8637:     if ($args->{'html_encode'}) {
                   8638: 	$result = &html_encode($result);
                   8639:     }
1.335     albertel 8640: 
1.315     albertel 8641:     return $result;
                   8642: }
                   8643: 
1.1034    www      8644: sub wishlist_window {
                   8645:     return(<<'ENDWISHLIST');
1.1046    raeburn  8646: <script type="text/javascript">
1.1034    www      8647: // <![CDATA[
                   8648: // <!-- BEGIN LON-CAPA Internal
                   8649: function set_wishlistlink(title, path) {
                   8650:     if (!title) {
                   8651:         title = document.title;
                   8652:         title = title.replace(/^LON-CAPA /,'');
                   8653:     }
1.1175    raeburn  8654:     title = encodeURIComponent(title);
1.1203    raeburn  8655:     title = title.replace("'","\\\'");
1.1034    www      8656:     if (!path) {
                   8657:         path = location.pathname;
                   8658:     }
1.1175    raeburn  8659:     path = encodeURIComponent(path);
1.1203    raeburn  8660:     path = path.replace("'","\\\'");
1.1034    www      8661:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8662:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8663: }
                   8664: // END LON-CAPA Internal -->
                   8665: // ]]>
                   8666: </script>
                   8667: ENDWISHLIST
                   8668: }
                   8669: 
1.1030    www      8670: sub modal_window {
                   8671:     return(<<'ENDMODAL');
1.1046    raeburn  8672: <script type="text/javascript">
1.1030    www      8673: // <![CDATA[
                   8674: // <!-- BEGIN LON-CAPA Internal
                   8675: var modalWindow = {
                   8676: 	parent:"body",
                   8677: 	windowId:null,
                   8678: 	content:null,
                   8679: 	width:null,
                   8680: 	height:null,
                   8681: 	close:function()
                   8682: 	{
                   8683: 	        $(".LCmodal-window").remove();
                   8684: 	        $(".LCmodal-overlay").remove();
                   8685: 	},
                   8686: 	open:function()
                   8687: 	{
                   8688: 		var modal = "";
                   8689: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8690: 		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;\">";
                   8691: 		modal += this.content;
                   8692: 		modal += "</div>";	
                   8693: 
                   8694: 		$(this.parent).append(modal);
                   8695: 
                   8696: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8697: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8698: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8699: 	}
                   8700: };
1.1140    raeburn  8701: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8702: 	{
1.1266    raeburn  8703:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8704: 		modalWindow.windowId = "myModal";
                   8705: 		modalWindow.width = width;
                   8706: 		modalWindow.height = height;
1.1196    raeburn  8707: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8708: 		modalWindow.open();
1.1208    raeburn  8709: 	};
1.1030    www      8710: // END LON-CAPA Internal -->
                   8711: // ]]>
                   8712: </script>
                   8713: ENDMODAL
                   8714: }
                   8715: 
                   8716: sub modal_link {
1.1140    raeburn  8717:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8718:     unless ($width) { $width=480; }
                   8719:     unless ($height) { $height=400; }
1.1031    www      8720:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8721:     unless ($transparency) { $transparency='true'; }
                   8722: 
1.1074    raeburn  8723:     my $target_attr;
                   8724:     if (defined($target)) {
                   8725:         $target_attr = 'target="'.$target.'"';
                   8726:     }
                   8727:     return <<"ENDLINK";
1.1140    raeburn  8728: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8729:            $linktext</a>
                   8730: ENDLINK
1.1030    www      8731: }
                   8732: 
1.1032    www      8733: sub modal_adhoc_script {
                   8734:     my ($funcname,$width,$height,$content)=@_;
                   8735:     return (<<ENDADHOC);
1.1046    raeburn  8736: <script type="text/javascript">
1.1032    www      8737: // <![CDATA[
                   8738:         var $funcname = function()
                   8739:         {
                   8740:                 modalWindow.windowId = "myModal";
                   8741:                 modalWindow.width = $width;
                   8742:                 modalWindow.height = $height;
                   8743:                 modalWindow.content = '$content';
                   8744:                 modalWindow.open();
                   8745:         };  
                   8746: // ]]>
                   8747: </script>
                   8748: ENDADHOC
                   8749: }
                   8750: 
1.1041    www      8751: sub modal_adhoc_inner {
                   8752:     my ($funcname,$width,$height,$content)=@_;
                   8753:     my $innerwidth=$width-20;
                   8754:     $content=&js_ready(
1.1140    raeburn  8755:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8756:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8757:                  $content.
1.1041    www      8758:                  &end_scrollbox().
1.1140    raeburn  8759:                  &end_page()
1.1041    www      8760:              );
                   8761:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8762: }
                   8763: 
                   8764: sub modal_adhoc_window {
                   8765:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8766:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8767:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8768: }
                   8769: 
                   8770: sub modal_adhoc_launch {
                   8771:     my ($funcname,$width,$height,$content)=@_;
                   8772:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8773: <script type="text/javascript">
                   8774: // <![CDATA[
                   8775: $funcname();
                   8776: // ]]>
                   8777: </script>
                   8778: ENDLAUNCH
                   8779: }
                   8780: 
                   8781: sub modal_adhoc_close {
                   8782:     return (<<ENDCLOSE);
                   8783: <script type="text/javascript">
                   8784: // <![CDATA[
                   8785: modalWindow.close();
                   8786: // ]]>
                   8787: </script>
                   8788: ENDCLOSE
                   8789: }
                   8790: 
1.1038    www      8791: sub togglebox_script {
                   8792:    return(<<ENDTOGGLE);
                   8793: <script type="text/javascript"> 
                   8794: // <![CDATA[
                   8795: function LCtoggleDisplay(id,hidetext,showtext) {
                   8796:    link = document.getElementById(id + "link").childNodes[0];
                   8797:    with (document.getElementById(id).style) {
                   8798:       if (display == "none" ) {
                   8799:           display = "inline";
                   8800:           link.nodeValue = hidetext;
                   8801:         } else {
                   8802:           display = "none";
                   8803:           link.nodeValue = showtext;
                   8804:        }
                   8805:    }
                   8806: }
                   8807: // ]]>
                   8808: </script>
                   8809: ENDTOGGLE
                   8810: }
                   8811: 
1.1039    www      8812: sub start_togglebox {
                   8813:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8814:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8815:     unless ($showtext) { $showtext=&mt('show'); }
                   8816:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8817:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8818:     return &start_data_table().
                   8819:            &start_data_table_header_row().
                   8820:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8821:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8822:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8823:            &end_data_table_header_row().
                   8824:            '<tr id="'.$id.'" style="display:none""><td>';
                   8825: }
                   8826: 
                   8827: sub end_togglebox {
                   8828:     return '</td></tr>'.&end_data_table();
                   8829: }
                   8830: 
1.1041    www      8831: sub LCprogressbar_script {
1.1045    www      8832:    my ($id)=@_;
1.1041    www      8833:    return(<<ENDPROGRESS);
                   8834: <script type="text/javascript">
                   8835: // <![CDATA[
1.1045    www      8836: \$('#progressbar$id').progressbar({
1.1041    www      8837:   value: 0,
                   8838:   change: function(event, ui) {
                   8839:     var newVal = \$(this).progressbar('option', 'value');
                   8840:     \$('.pblabel', this).text(LCprogressTxt);
                   8841:   }
                   8842: });
                   8843: // ]]>
                   8844: </script>
                   8845: ENDPROGRESS
                   8846: }
                   8847: 
                   8848: sub LCprogressbarUpdate_script {
                   8849:    return(<<ENDPROGRESSUPDATE);
                   8850: <style type="text/css">
                   8851: .ui-progressbar { position:relative; }
                   8852: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8853: </style>
                   8854: <script type="text/javascript">
                   8855: // <![CDATA[
1.1045    www      8856: var LCprogressTxt='---';
                   8857: 
                   8858: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8859:    LCprogressTxt=progresstext;
1.1045    www      8860:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8861: }
                   8862: // ]]>
                   8863: </script>
                   8864: ENDPROGRESSUPDATE
                   8865: }
                   8866: 
1.1042    www      8867: my $LClastpercent;
1.1045    www      8868: my $LCidcnt;
                   8869: my $LCcurrentid;
1.1042    www      8870: 
1.1041    www      8871: sub LCprogressbar {
1.1042    www      8872:     my ($r)=(@_);
                   8873:     $LClastpercent=0;
1.1045    www      8874:     $LCidcnt++;
                   8875:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8876:     my $starting=&mt('Starting');
                   8877:     my $content=(<<ENDPROGBAR);
1.1045    www      8878:   <div id="progressbar$LCcurrentid">
1.1041    www      8879:     <span class="pblabel">$starting</span>
                   8880:   </div>
                   8881: ENDPROGBAR
1.1045    www      8882:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8883: }
                   8884: 
                   8885: sub LCprogressbarUpdate {
1.1042    www      8886:     my ($r,$val,$text)=@_;
                   8887:     unless ($val) { 
                   8888:        if ($LClastpercent) {
                   8889:            $val=$LClastpercent;
                   8890:        } else {
                   8891:            $val=0;
                   8892:        }
                   8893:     }
1.1041    www      8894:     if ($val<0) { $val=0; }
                   8895:     if ($val>100) { $val=0; }
1.1042    www      8896:     $LClastpercent=$val;
1.1041    www      8897:     unless ($text) { $text=$val.'%'; }
                   8898:     $text=&js_ready($text);
1.1044    www      8899:     &r_print($r,<<ENDUPDATE);
1.1041    www      8900: <script type="text/javascript">
                   8901: // <![CDATA[
1.1045    www      8902: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8903: // ]]>
                   8904: </script>
                   8905: ENDUPDATE
1.1035    www      8906: }
                   8907: 
1.1042    www      8908: sub LCprogressbarClose {
                   8909:     my ($r)=@_;
                   8910:     $LClastpercent=0;
1.1044    www      8911:     &r_print($r,<<ENDCLOSE);
1.1042    www      8912: <script type="text/javascript">
                   8913: // <![CDATA[
1.1045    www      8914: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8915: // ]]>
                   8916: </script>
                   8917: ENDCLOSE
1.1044    www      8918: }
                   8919: 
                   8920: sub r_print {
                   8921:     my ($r,$to_print)=@_;
                   8922:     if ($r) {
                   8923:       $r->print($to_print);
                   8924:       $r->rflush();
                   8925:     } else {
                   8926:       print($to_print);
                   8927:     }
1.1042    www      8928: }
                   8929: 
1.320     albertel 8930: sub html_encode {
                   8931:     my ($result) = @_;
                   8932: 
1.322     albertel 8933:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8934:     
                   8935:     return $result;
                   8936: }
1.1044    www      8937: 
1.317     albertel 8938: sub js_ready {
                   8939:     my ($result) = @_;
                   8940: 
1.323     albertel 8941:     $result =~ s/[\n\r]/ /xmsg;
                   8942:     $result =~ s/\\/\\\\/xmsg;
                   8943:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8944:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8945:     
                   8946:     return $result;
                   8947: }
                   8948: 
1.315     albertel 8949: sub validate_page {
                   8950:     if (  exists($env{'internal.start_page'})
1.316     albertel 8951: 	  &&     $env{'internal.start_page'} > 1) {
                   8952: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8953: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8954: 				 $ENV{'request.filename'});
1.315     albertel 8955:     }
                   8956:     if (  exists($env{'internal.end_page'})
1.316     albertel 8957: 	  &&     $env{'internal.end_page'} > 1) {
                   8958: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8959: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8960: 				 $env{'request.filename'});
1.315     albertel 8961:     }
                   8962:     if (     exists($env{'internal.start_page'})
                   8963: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8964: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8965: 				 $env{'request.filename'});
1.315     albertel 8966:     }
                   8967:     if (   ! exists($env{'internal.start_page'})
                   8968: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8969: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8970: 				 $env{'request.filename'});
1.315     albertel 8971:     }
1.306     albertel 8972: }
1.315     albertel 8973: 
1.996     www      8974: 
                   8975: sub start_scrollbox {
1.1140    raeburn  8976:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8977:     unless ($outerwidth) { $outerwidth='520px'; }
                   8978:     unless ($width) { $width='500px'; }
                   8979:     unless ($height) { $height='200px'; }
1.1075    raeburn  8980:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8981:     if ($id ne '') {
1.1140    raeburn  8982:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  8983:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8984:     }
1.1075    raeburn  8985:     if ($bgcolor ne '') {
                   8986:         $tdcol = "background-color: $bgcolor;";
                   8987:     }
1.1137    raeburn  8988:     my $nicescroll_js;
                   8989:     if ($env{'browser.mobile'}) {
1.1140    raeburn  8990:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8991:     }
                   8992:     return <<"END";
                   8993: $nicescroll_js
                   8994: 
                   8995: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   8996: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   8997: END
                   8998: }
                   8999: 
                   9000: sub end_scrollbox {
                   9001:     return '</div></td></tr></table>';
                   9002: }
                   9003: 
                   9004: sub nicescroll_javascript {
                   9005:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9006:     my %options;
                   9007:     if (ref($cursor) eq 'HASH') {
                   9008:         %options = %{$cursor};
                   9009:     }
                   9010:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9011:         $options{'railalign'} = 'left';
                   9012:     }
                   9013:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9014:         my $function  = &get_users_function();
                   9015:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9016:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9017:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9018:         }
1.1140    raeburn  9019:     }
                   9020:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9021:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9022:             $options{'cursoropacity'}='1.0';
                   9023:         }
1.1140    raeburn  9024:     } else {
                   9025:         $options{'cursoropacity'}='1.0';
                   9026:     }
                   9027:     if ($options{'cursorfixedheight'} eq 'none') {
                   9028:         delete($options{'cursorfixedheight'});
                   9029:     } else {
                   9030:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9031:     }
                   9032:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9033:         delete($options{'railoffset'});
                   9034:     }
                   9035:     my @niceoptions;
                   9036:     while (my($key,$value) = each(%options)) {
                   9037:         if ($value =~ /^\{.+\}$/) {
                   9038:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9039:         } else {
1.1140    raeburn  9040:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9041:         }
1.1140    raeburn  9042:     }
                   9043:     my $nicescroll_js = '
1.1137    raeburn  9044: $(document).ready(
1.1140    raeburn  9045:       function() {
                   9046:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9047:       }
1.1137    raeburn  9048: );
                   9049: ';
1.1140    raeburn  9050:     if ($framecheck) {
                   9051:         $nicescroll_js .= '
                   9052: function expand_div(caller) {
                   9053:     if (top === self) {
                   9054:         document.getElementById("'.$id.'").style.width = "auto";
                   9055:         document.getElementById("'.$id.'").style.height = "auto";
                   9056:     } else {
                   9057:         try {
                   9058:             if (parent.frames) {
                   9059:                 if (parent.frames.length > 1) {
                   9060:                     var framesrc = parent.frames[1].location.href;
                   9061:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9062:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9063:                         document.getElementById("'.$id.'").style.width = "auto";
                   9064:                         document.getElementById("'.$id.'").style.height = "auto";
                   9065:                     }
                   9066:                 }
                   9067:             }
                   9068:         } catch (e) {
                   9069:             return;
                   9070:         }
1.1137    raeburn  9071:     }
1.1140    raeburn  9072:     return;
1.996     www      9073: }
1.1140    raeburn  9074: ';
                   9075:     }
                   9076:     if ($needjsready) {
                   9077:         $nicescroll_js = '
                   9078: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9079:     } else {
                   9080:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9081:     }
                   9082:     return $nicescroll_js;
1.996     www      9083: }
                   9084: 
1.318     albertel 9085: sub simple_error_page {
1.1150    bisitz   9086:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  9087:     if (ref($args) eq 'HASH') {
                   9088:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   9089:     } else {
                   9090:         $msg = &mt($msg);
                   9091:     }
1.1150    bisitz   9092: 
1.318     albertel 9093:     my $page =
                   9094: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   9095: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9096: 	&Apache::loncommon::end_page();
                   9097:     if (ref($r)) {
                   9098: 	$r->print($page);
1.327     albertel 9099: 	return;
1.318     albertel 9100:     }
                   9101:     return $page;
                   9102: }
1.347     albertel 9103: 
                   9104: {
1.610     albertel 9105:     my @row_count;
1.961     onken    9106: 
                   9107:     sub start_data_table_count {
                   9108:         unshift(@row_count, 0);
                   9109:         return;
                   9110:     }
                   9111: 
                   9112:     sub end_data_table_count {
                   9113:         shift(@row_count);
                   9114:         return;
                   9115:     }
                   9116: 
1.347     albertel 9117:     sub start_data_table {
1.1018    raeburn  9118: 	my ($add_class,$id) = @_;
1.422     albertel 9119: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9120:         my $table_id;
                   9121:         if (defined($id)) {
                   9122:             $table_id = ' id="'.$id.'"';
                   9123:         }
1.961     onken    9124: 	&start_data_table_count();
1.1018    raeburn  9125: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9126:     }
                   9127: 
                   9128:     sub end_data_table {
1.961     onken    9129: 	&end_data_table_count();
1.389     albertel 9130: 	return '</table>'."\n";;
1.347     albertel 9131:     }
                   9132: 
                   9133:     sub start_data_table_row {
1.974     wenzelju 9134: 	my ($add_class, $id) = @_;
1.610     albertel 9135: 	$row_count[0]++;
                   9136: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9137: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9138:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9139:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9140:     }
1.471     banghart 9141:     
                   9142:     sub continue_data_table_row {
1.974     wenzelju 9143: 	my ($add_class, $id) = @_;
1.610     albertel 9144: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9145: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9146:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9147:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9148:     }
1.347     albertel 9149: 
                   9150:     sub end_data_table_row {
1.389     albertel 9151: 	return '</tr>'."\n";;
1.347     albertel 9152:     }
1.367     www      9153: 
1.421     albertel 9154:     sub start_data_table_empty_row {
1.707     bisitz   9155: #	$row_count[0]++;
1.421     albertel 9156: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9157:     }
                   9158: 
                   9159:     sub end_data_table_empty_row {
                   9160: 	return '</tr>'."\n";;
                   9161:     }
                   9162: 
1.367     www      9163:     sub start_data_table_header_row {
1.389     albertel 9164: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9165:     }
                   9166: 
                   9167:     sub end_data_table_header_row {
1.389     albertel 9168: 	return '</tr>'."\n";;
1.367     www      9169:     }
1.890     droeschl 9170: 
                   9171:     sub data_table_caption {
                   9172:         my $caption = shift;
                   9173:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9174:     }
1.347     albertel 9175: }
                   9176: 
1.548     albertel 9177: =pod
                   9178: 
                   9179: =item * &inhibit_menu_check($arg)
                   9180: 
                   9181: Checks for a inhibitmenu state and generates output to preserve it
                   9182: 
                   9183: Inputs:         $arg - can be any of
                   9184:                      - undef - in which case the return value is a string 
                   9185:                                to add  into arguments list of a uri
                   9186:                      - 'input' - in which case the return value is a HTML
                   9187:                                  <form> <input> field of type hidden to
                   9188:                                  preserve the value
                   9189:                      - a url - in which case the return value is the url with
                   9190:                                the neccesary cgi args added to preserve the
                   9191:                                inhibitmenu state
                   9192:                      - a ref to a url - no return value, but the string is
                   9193:                                         updated to include the neccessary cgi
                   9194:                                         args to preserve the inhibitmenu state
                   9195: 
                   9196: =cut
                   9197: 
                   9198: sub inhibit_menu_check {
                   9199:     my ($arg) = @_;
                   9200:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9201:     if ($arg eq 'input') {
                   9202: 	if ($env{'form.inhibitmenu'}) {
                   9203: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9204: 	} else {
                   9205: 	    return
                   9206: 	}
                   9207:     }
                   9208:     if ($env{'form.inhibitmenu'}) {
                   9209: 	if (ref($arg)) {
                   9210: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9211: 	} elsif ($arg eq '') {
                   9212: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9213: 	} else {
                   9214: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9215: 	}
                   9216:     }
                   9217:     if (!ref($arg)) {
                   9218: 	return $arg;
                   9219:     }
                   9220: }
                   9221: 
1.251     albertel 9222: ###############################################
1.182     matthew  9223: 
                   9224: =pod
                   9225: 
1.549     albertel 9226: =back
                   9227: 
                   9228: =head1 User Information Routines
                   9229: 
                   9230: =over 4
                   9231: 
1.405     albertel 9232: =item * &get_users_function()
1.182     matthew  9233: 
                   9234: Used by &bodytag to determine the current users primary role.
                   9235: Returns either 'student','coordinator','admin', or 'author'.
                   9236: 
                   9237: =cut
                   9238: 
                   9239: ###############################################
                   9240: sub get_users_function {
1.815     tempelho 9241:     my $function = 'norole';
1.818     tempelho 9242:     if ($env{'request.role'}=~/^(st)/) {
                   9243:         $function='student';
                   9244:     }
1.907     raeburn  9245:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9246:         $function='coordinator';
                   9247:     }
1.258     albertel 9248:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9249:         $function='admin';
                   9250:     }
1.826     bisitz   9251:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9252:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9253:         $function='author';
                   9254:     }
                   9255:     return $function;
1.54      www      9256: }
1.99      www      9257: 
                   9258: ###############################################
                   9259: 
1.233     raeburn  9260: =pod
                   9261: 
1.821     raeburn  9262: =item * &show_course()
                   9263: 
                   9264: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9265: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9266: 
                   9267: Inputs:
                   9268: None
                   9269: 
                   9270: Outputs:
                   9271: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9272: 
                   9273: =cut
                   9274: 
                   9275: ###############################################
                   9276: sub show_course {
                   9277:     my $course = !$env{'user.adv'};
                   9278:     if (!$env{'user.adv'}) {
                   9279:         foreach my $env (keys(%env)) {
                   9280:             next if ($env !~ m/^user\.priv\./);
                   9281:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9282:                 $course = 0;
                   9283:                 last;
                   9284:             }
                   9285:         }
                   9286:     }
                   9287:     return $course;
                   9288: }
                   9289: 
                   9290: ###############################################
                   9291: 
                   9292: =pod
                   9293: 
1.542     raeburn  9294: =item * &check_user_status()
1.274     raeburn  9295: 
                   9296: Determines current status of supplied role for a
                   9297: specific user. Roles can be active, previous or future.
                   9298: 
                   9299: Inputs: 
                   9300: user's domain, user's username, course's domain,
1.375     raeburn  9301: course's number, optional section ID.
1.274     raeburn  9302: 
                   9303: Outputs:
                   9304: role status: active, previous or future. 
                   9305: 
                   9306: =cut
                   9307: 
                   9308: sub check_user_status {
1.412     raeburn  9309:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9310:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9311:     my @uroles = keys(%userinfo);
1.274     raeburn  9312:     my $srchstr;
                   9313:     my $active_chk = 'none';
1.412     raeburn  9314:     my $now = time;
1.274     raeburn  9315:     if (@uroles > 0) {
1.908     raeburn  9316:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9317:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9318:         } else {
1.412     raeburn  9319:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9320:         }
                   9321:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9322:             my $role_end = 0;
                   9323:             my $role_start = 0;
                   9324:             $active_chk = 'active';
1.412     raeburn  9325:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9326:                 $role_end = $1;
                   9327:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9328:                     $role_start = $1;
1.274     raeburn  9329:                 }
                   9330:             }
                   9331:             if ($role_start > 0) {
1.412     raeburn  9332:                 if ($now < $role_start) {
1.274     raeburn  9333:                     $active_chk = 'future';
                   9334:                 }
                   9335:             }
                   9336:             if ($role_end > 0) {
1.412     raeburn  9337:                 if ($now > $role_end) {
1.274     raeburn  9338:                     $active_chk = 'previous';
                   9339:                 }
                   9340:             }
                   9341:         }
                   9342:     }
                   9343:     return $active_chk;
                   9344: }
                   9345: 
                   9346: ###############################################
                   9347: 
                   9348: =pod
                   9349: 
1.405     albertel 9350: =item * &get_sections()
1.233     raeburn  9351: 
                   9352: Determines all the sections for a course including
                   9353: sections with students and sections containing other roles.
1.419     raeburn  9354: Incoming parameters: 
                   9355: 
                   9356: 1. domain
                   9357: 2. course number 
                   9358: 3. reference to array containing roles for which sections should 
                   9359: be gathered (optional).
                   9360: 4. reference to array containing status types for which sections 
                   9361: should be gathered (optional).
                   9362: 
                   9363: If the third argument is undefined, sections are gathered for any role. 
                   9364: If the fourth argument is undefined, sections are gathered for any status.
                   9365: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9366:  
1.374     raeburn  9367: Returns section hash (keys are section IDs, values are
                   9368: number of users in each section), subject to the
1.419     raeburn  9369: optional roles filter, optional status filter 
1.233     raeburn  9370: 
                   9371: =cut
                   9372: 
                   9373: ###############################################
                   9374: sub get_sections {
1.419     raeburn  9375:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9376:     if (!defined($cdom) || !defined($cnum)) {
                   9377:         my $cid =  $env{'request.course.id'};
                   9378: 
                   9379: 	return if (!defined($cid));
                   9380: 
                   9381:         $cdom = $env{'course.'.$cid.'.domain'};
                   9382:         $cnum = $env{'course.'.$cid.'.num'};
                   9383:     }
                   9384: 
                   9385:     my %sectioncount;
1.419     raeburn  9386:     my $now = time;
1.240     albertel 9387: 
1.1118    raeburn  9388:     my $check_students = 1;
                   9389:     my $only_students = 0;
                   9390:     if (ref($possible_roles) eq 'ARRAY') {
                   9391:         if (grep(/^st$/,@{$possible_roles})) {
                   9392:             if (@{$possible_roles} == 1) {
                   9393:                 $only_students = 1;
                   9394:             }
                   9395:         } else {
                   9396:             $check_students = 0;
                   9397:         }
                   9398:     }
                   9399: 
                   9400:     if ($check_students) { 
1.276     albertel 9401: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9402: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9403: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9404:         my $start_index = &Apache::loncoursedata::CL_START();
                   9405:         my $end_index = &Apache::loncoursedata::CL_END();
                   9406:         my $status;
1.366     albertel 9407: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9408: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9409: 				                     $data->[$status_index],
                   9410:                                                      $data->[$start_index],
                   9411:                                                      $data->[$end_index]);
                   9412:             if ($stu_status eq 'Active') {
                   9413:                 $status = 'active';
                   9414:             } elsif ($end < $now) {
                   9415:                 $status = 'previous';
                   9416:             } elsif ($start > $now) {
                   9417:                 $status = 'future';
                   9418:             } 
                   9419: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9420:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9421:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9422: 		    $sectioncount{$section}++;
                   9423:                 }
1.240     albertel 9424: 	    }
                   9425: 	}
                   9426:     }
1.1118    raeburn  9427:     if ($only_students) {
                   9428:         return %sectioncount;
                   9429:     }
1.240     albertel 9430:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9431:     foreach my $user (sort(keys(%courseroles))) {
                   9432: 	if ($user !~ /^(\w{2})/) { next; }
                   9433: 	my ($role) = ($user =~ /^(\w{2})/);
                   9434: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9435: 	my ($section,$status);
1.240     albertel 9436: 	if ($role eq 'cr' &&
                   9437: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9438: 	    $section=$1;
                   9439: 	}
                   9440: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9441: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9442:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9443:         if ($end == -1 && $start == -1) {
                   9444:             next; #deleted role
                   9445:         }
                   9446:         if (!defined($possible_status)) { 
                   9447:             $sectioncount{$section}++;
                   9448:         } else {
                   9449:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9450:                 $status = 'active';
                   9451:             } elsif ($end < $now) {
                   9452:                 $status = 'future';
                   9453:             } elsif ($start > $now) {
                   9454:                 $status = 'previous';
                   9455:             }
                   9456:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9457:                 $sectioncount{$section}++;
                   9458:             }
                   9459:         }
1.233     raeburn  9460:     }
1.366     albertel 9461:     return %sectioncount;
1.233     raeburn  9462: }
                   9463: 
1.274     raeburn  9464: ###############################################
1.294     raeburn  9465: 
                   9466: =pod
1.405     albertel 9467: 
                   9468: =item * &get_course_users()
                   9469: 
1.275     raeburn  9470: Retrieves usernames:domains for users in the specified course
                   9471: with specific role(s), and access status. 
                   9472: 
                   9473: Incoming parameters:
1.277     albertel 9474: 1. course domain
                   9475: 2. course number
                   9476: 3. access status: users must have - either active, 
1.275     raeburn  9477: previous, future, or all.
1.277     albertel 9478: 4. reference to array of permissible roles
1.288     raeburn  9479: 5. reference to array of section restrictions (optional)
                   9480: 6. reference to results object (hash of hashes).
                   9481: 7. reference to optional userdata hash
1.609     raeburn  9482: 8. reference to optional statushash
1.630     raeburn  9483: 9. flag if privileged users (except those set to unhide in
                   9484:    course settings) should be excluded    
1.609     raeburn  9485: Keys of top level results hash are roles.
1.275     raeburn  9486: Keys of inner hashes are username:domain, with 
                   9487: values set to access type.
1.288     raeburn  9488: Optional userdata hash returns an array with arguments in the 
                   9489: same order as loncoursedata::get_classlist() for student data.
                   9490: 
1.609     raeburn  9491: Optional statushash returns
                   9492: 
1.288     raeburn  9493: Entries for end, start, section and status are blank because
                   9494: of the possibility of multiple values for non-student roles.
                   9495: 
1.275     raeburn  9496: =cut
1.405     albertel 9497: 
1.275     raeburn  9498: ###############################################
1.405     albertel 9499: 
1.275     raeburn  9500: sub get_course_users {
1.630     raeburn  9501:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9502:     my %idx = ();
1.419     raeburn  9503:     my %seclists;
1.288     raeburn  9504: 
                   9505:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9506:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9507:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9508:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9509:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9510:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9511:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9512:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9513: 
1.290     albertel 9514:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9515:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9516:         my $now = time;
1.277     albertel 9517:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9518:             my $match = 0;
1.412     raeburn  9519:             my $secmatch = 0;
1.419     raeburn  9520:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9521:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9522:             if ($section eq '') {
                   9523:                 $section = 'none';
                   9524:             }
1.291     albertel 9525:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9526:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9527:                     $secmatch = 1;
                   9528:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9529:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9530:                         $secmatch = 1;
                   9531:                     }
                   9532:                 } else {  
1.419     raeburn  9533: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9534: 		        $secmatch = 1;
                   9535:                     }
1.290     albertel 9536: 		}
1.412     raeburn  9537:                 if (!$secmatch) {
                   9538:                     next;
                   9539:                 }
1.419     raeburn  9540:             }
1.275     raeburn  9541:             if (defined($$types{'active'})) {
1.288     raeburn  9542:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9543:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9544:                     $match = 1;
1.275     raeburn  9545:                 }
                   9546:             }
                   9547:             if (defined($$types{'previous'})) {
1.609     raeburn  9548:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9549:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9550:                     $match = 1;
1.275     raeburn  9551:                 }
                   9552:             }
                   9553:             if (defined($$types{'future'})) {
1.609     raeburn  9554:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9555:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9556:                     $match = 1;
1.275     raeburn  9557:                 }
                   9558:             }
1.609     raeburn  9559:             if ($match) {
                   9560:                 push(@{$seclists{$student}},$section);
                   9561:                 if (ref($userdata) eq 'HASH') {
                   9562:                     $$userdata{$student} = $$classlist{$student};
                   9563:                 }
                   9564:                 if (ref($statushash) eq 'HASH') {
                   9565:                     $statushash->{$student}{'st'}{$section} = $status;
                   9566:                 }
1.288     raeburn  9567:             }
1.275     raeburn  9568:         }
                   9569:     }
1.412     raeburn  9570:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9571:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9572:         my $now = time;
1.609     raeburn  9573:         my %displaystatus = ( previous => 'Expired',
                   9574:                               active   => 'Active',
                   9575:                               future   => 'Future',
                   9576:                             );
1.1121    raeburn  9577:         my (%nothide,@possdoms);
1.630     raeburn  9578:         if ($hidepriv) {
                   9579:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9580:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9581:                 if ($user !~ /:/) {
                   9582:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9583:                 } else {
                   9584:                     $nothide{$user} = 1;
                   9585:                 }
                   9586:             }
1.1121    raeburn  9587:             my @possdoms = ($cdom);
                   9588:             if ($coursehash{'checkforpriv'}) {
                   9589:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9590:             }
1.630     raeburn  9591:         }
1.439     raeburn  9592:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9593:             my $match = 0;
1.412     raeburn  9594:             my $secmatch = 0;
1.439     raeburn  9595:             my $status;
1.412     raeburn  9596:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9597:             $user =~ s/:$//;
1.439     raeburn  9598:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9599:             if ($end == -1 || $start == -1) {
                   9600:                 next;
                   9601:             }
                   9602:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9603:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9604:                 my ($uname,$udom) = split(/:/,$user);
                   9605:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9606:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9607:                         $secmatch = 1;
                   9608:                     } elsif ($usec eq '') {
1.420     albertel 9609:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9610:                             $secmatch = 1;
                   9611:                         }
                   9612:                     } else {
                   9613:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9614:                             $secmatch = 1;
                   9615:                         }
                   9616:                     }
                   9617:                     if (!$secmatch) {
                   9618:                         next;
                   9619:                     }
1.288     raeburn  9620:                 }
1.419     raeburn  9621:                 if ($usec eq '') {
                   9622:                     $usec = 'none';
                   9623:                 }
1.275     raeburn  9624:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9625:                     if ($hidepriv) {
1.1121    raeburn  9626:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9627:                             (!$nothide{$uname.':'.$udom})) {
                   9628:                             next;
                   9629:                         }
                   9630:                     }
1.503     raeburn  9631:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9632:                         $status = 'previous';
                   9633:                     } elsif ($start > $now) {
                   9634:                         $status = 'future';
                   9635:                     } else {
                   9636:                         $status = 'active';
                   9637:                     }
1.277     albertel 9638:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9639:                         if ($status eq $type) {
1.420     albertel 9640:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9641:                                 push(@{$$users{$role}{$user}},$type);
                   9642:                             }
1.288     raeburn  9643:                             $match = 1;
                   9644:                         }
                   9645:                     }
1.419     raeburn  9646:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9647:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9648: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9649:                         }
1.420     albertel 9650:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9651:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9652:                         }
1.609     raeburn  9653:                         if (ref($statushash) eq 'HASH') {
                   9654:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9655:                         }
1.275     raeburn  9656:                     }
                   9657:                 }
                   9658:             }
                   9659:         }
1.290     albertel 9660:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9661:             if ((defined($cdom)) && (defined($cnum))) {
                   9662:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9663:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9664:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9665:                     next if ($owner eq '');
                   9666:                     my ($ownername,$ownerdom);
                   9667:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9668:                         $ownername = $1;
                   9669:                         $ownerdom = $2;
                   9670:                     } else {
                   9671:                         $ownername = $owner;
                   9672:                         $ownerdom = $cdom;
                   9673:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9674:                     }
                   9675:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9676:                     if (defined($userdata) && 
1.609     raeburn  9677: 			!exists($$userdata{$owner})) {
                   9678: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9679:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9680:                             push(@{$seclists{$owner}},'none');
                   9681:                         }
                   9682:                         if (ref($statushash) eq 'HASH') {
                   9683:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9684:                         }
1.290     albertel 9685: 		    }
1.279     raeburn  9686:                 }
                   9687:             }
                   9688:         }
1.419     raeburn  9689:         foreach my $user (keys(%seclists)) {
                   9690:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9691:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9692:         }
1.275     raeburn  9693:     }
                   9694:     return;
                   9695: }
                   9696: 
1.288     raeburn  9697: sub get_user_info {
                   9698:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9699:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9700: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9701:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9702:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9703:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9704:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9705:     return;
                   9706: }
1.275     raeburn  9707: 
1.472     raeburn  9708: ###############################################
                   9709: 
                   9710: =pod
                   9711: 
                   9712: =item * &get_user_quota()
                   9713: 
1.1134    raeburn  9714: Retrieves quota assigned for storage of user files.
                   9715: Default is to report quota for portfolio files.
1.472     raeburn  9716: 
                   9717: Incoming parameters:
                   9718: 1. user's username
                   9719: 2. user's domain
1.1134    raeburn  9720: 3. quota name - portfolio, author, or course
1.1136    raeburn  9721:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  9722: 4. crstype - official, unofficial, textbook, placement or community, 
                   9723:    if quota name is course
1.472     raeburn  9724: 
                   9725: Returns:
1.1163    raeburn  9726: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9727: 2. (Optional) Type of setting: custom or default
                   9728:    (individually assigned or default for user's 
                   9729:    institutional status).
                   9730: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9731:    or student - types as defined in localenroll::inst_usertypes 
                   9732:    for user's domain, which determines default quota for user.
                   9733: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9734: 
                   9735: If a value has been stored in the user's environment, 
1.536     raeburn  9736: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9737: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9738: 
                   9739: =cut
                   9740: 
                   9741: ###############################################
                   9742: 
                   9743: 
                   9744: sub get_user_quota {
1.1136    raeburn  9745:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9746:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9747:     if (!defined($udom)) {
                   9748:         $udom = $env{'user.domain'};
                   9749:     }
                   9750:     if (!defined($uname)) {
                   9751:         $uname = $env{'user.name'};
                   9752:     }
                   9753:     if (($udom eq '' || $uname eq '') ||
                   9754:         ($udom eq 'public') && ($uname eq 'public')) {
                   9755:         $quota = 0;
1.536     raeburn  9756:         $quotatype = 'default';
                   9757:         $defquota = 0; 
1.472     raeburn  9758:     } else {
1.536     raeburn  9759:         my $inststatus;
1.1134    raeburn  9760:         if ($quotaname eq 'course') {
                   9761:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9762:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9763:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9764:             } else {
                   9765:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9766:                 $quota = $cenv{'internal.uploadquota'};
                   9767:             }
1.536     raeburn  9768:         } else {
1.1134    raeburn  9769:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9770:                 if ($quotaname eq 'author') {
                   9771:                     $quota = $env{'environment.authorquota'};
                   9772:                 } else {
                   9773:                     $quota = $env{'environment.portfolioquota'};
                   9774:                 }
                   9775:                 $inststatus = $env{'environment.inststatus'};
                   9776:             } else {
                   9777:                 my %userenv = 
                   9778:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9779:                                          'authorquota','inststatus'],$udom,$uname);
                   9780:                 my ($tmp) = keys(%userenv);
                   9781:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9782:                     if ($quotaname eq 'author') {
                   9783:                         $quota = $userenv{'authorquota'};
                   9784:                     } else {
                   9785:                         $quota = $userenv{'portfolioquota'};
                   9786:                     }
                   9787:                     $inststatus = $userenv{'inststatus'};
                   9788:                 } else {
                   9789:                     undef(%userenv);
                   9790:                 }
                   9791:             }
                   9792:         }
                   9793:         if ($quota eq '' || wantarray) {
                   9794:             if ($quotaname eq 'course') {
                   9795:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9796:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  9797:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   9798:                     ($crstype eq 'placement')) { 
1.1136    raeburn  9799:                     $defquota = $domdefs{$crstype.'quota'};
                   9800:                 }
                   9801:                 if ($defquota eq '') {
                   9802:                     $defquota = 500;
                   9803:                 }
1.1134    raeburn  9804:             } else {
                   9805:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9806:             }
                   9807:             if ($quota eq '') {
                   9808:                 $quota = $defquota;
                   9809:                 $quotatype = 'default';
                   9810:             } else {
                   9811:                 $quotatype = 'custom';
                   9812:             }
1.472     raeburn  9813:         }
                   9814:     }
1.536     raeburn  9815:     if (wantarray) {
                   9816:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9817:     } else {
                   9818:         return $quota;
                   9819:     }
1.472     raeburn  9820: }
                   9821: 
                   9822: ###############################################
                   9823: 
                   9824: =pod
                   9825: 
                   9826: =item * &default_quota()
                   9827: 
1.536     raeburn  9828: Retrieves default quota assigned for storage of user portfolio files,
                   9829: given an (optional) user's institutional status.
1.472     raeburn  9830: 
                   9831: Incoming parameters:
1.1142    raeburn  9832: 
1.472     raeburn  9833: 1. domain
1.536     raeburn  9834: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9835:    status types (e.g., faculty, staff, student etc.)
                   9836:    which apply to the user for whom the default is being retrieved.
                   9837:    If the institutional status string in undefined, the domain
1.1134    raeburn  9838:    default quota will be returned.
                   9839: 3.  quota name - portfolio, author, or course
                   9840:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9841: 
                   9842: Returns:
1.1142    raeburn  9843: 
1.1163    raeburn  9844: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9845: 2. (Optional) institutional type which determined the value of the
                   9846:    default quota.
1.472     raeburn  9847: 
                   9848: If a value has been stored in the domain's configuration db,
                   9849: it will return that, otherwise it returns 20 (for backwards 
                   9850: compatibility with domains which have not set up a configuration
1.1163    raeburn  9851: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9852: 
1.536     raeburn  9853: If the user's status includes multiple types (e.g., staff and student),
                   9854: the largest default quota which applies to the user determines the
                   9855: default quota returned.
                   9856: 
1.472     raeburn  9857: =cut
                   9858: 
                   9859: ###############################################
                   9860: 
                   9861: 
                   9862: sub default_quota {
1.1134    raeburn  9863:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9864:     my ($defquota,$settingstatus);
                   9865:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9866:                                             ['quotas'],$udom);
1.1134    raeburn  9867:     my $key = 'defaultquota';
                   9868:     if ($quotaname eq 'author') {
                   9869:         $key = 'authorquota';
                   9870:     }
1.622     raeburn  9871:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9872:         if ($inststatus ne '') {
1.765     raeburn  9873:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9874:             foreach my $item (@statuses) {
1.1134    raeburn  9875:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9876:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9877:                         if ($defquota eq '') {
1.1134    raeburn  9878:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9879:                             $settingstatus = $item;
1.1134    raeburn  9880:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9881:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9882:                             $settingstatus = $item;
                   9883:                         }
                   9884:                     }
1.1134    raeburn  9885:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9886:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9887:                         if ($defquota eq '') {
                   9888:                             $defquota = $quotahash{'quotas'}{$item};
                   9889:                             $settingstatus = $item;
                   9890:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9891:                             $defquota = $quotahash{'quotas'}{$item};
                   9892:                             $settingstatus = $item;
                   9893:                         }
1.536     raeburn  9894:                     }
                   9895:                 }
                   9896:             }
                   9897:         }
                   9898:         if ($defquota eq '') {
1.1134    raeburn  9899:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9900:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9901:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9902:                 $defquota = $quotahash{'quotas'}{'default'};
                   9903:             }
1.536     raeburn  9904:             $settingstatus = 'default';
1.1139    raeburn  9905:             if ($defquota eq '') {
                   9906:                 if ($quotaname eq 'author') {
                   9907:                     $defquota = 500;
                   9908:                 }
                   9909:             }
1.536     raeburn  9910:         }
                   9911:     } else {
                   9912:         $settingstatus = 'default';
1.1134    raeburn  9913:         if ($quotaname eq 'author') {
                   9914:             $defquota = 500;
                   9915:         } else {
                   9916:             $defquota = 20;
                   9917:         }
1.536     raeburn  9918:     }
                   9919:     if (wantarray) {
                   9920:         return ($defquota,$settingstatus);
1.472     raeburn  9921:     } else {
1.536     raeburn  9922:         return $defquota;
1.472     raeburn  9923:     }
                   9924: }
                   9925: 
1.1135    raeburn  9926: ###############################################
                   9927: 
                   9928: =pod
                   9929: 
1.1136    raeburn  9930: =item * &excess_filesize_warning()
1.1135    raeburn  9931: 
                   9932: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  9933: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  9934: space to be exceeded.
1.1136    raeburn  9935: 
                   9936: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  9937: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  9938: 
1.1165    raeburn  9939: Inputs: 7 
1.1136    raeburn  9940: 1. username or coursenum
1.1135    raeburn  9941: 2. domain
1.1136    raeburn  9942: 3. context ('author' or 'course')
1.1135    raeburn  9943: 4. filename of file for which action is being requested
                   9944: 5. filesize (kB) of file
                   9945: 6. action being taken: copy or upload.
1.1237    raeburn  9946: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  9947: 
                   9948: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  9949:          otherwise return null.
                   9950: 
                   9951: =back
1.1135    raeburn  9952: 
                   9953: =cut
                   9954: 
1.1136    raeburn  9955: sub excess_filesize_warning {
1.1165    raeburn  9956:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  9957:     my $current_disk_usage = 0;
1.1165    raeburn  9958:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  9959:     if ($context eq 'author') {
                   9960:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9961:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9962:     } else {
                   9963:         foreach my $subdir ('docs','supplemental') {
                   9964:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9965:         }
                   9966:     }
1.1135    raeburn  9967:     $disk_quota = int($disk_quota * 1000);
                   9968:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   9969:         return '<p class="LC_warning">'.
1.1135    raeburn  9970:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   9971:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9972:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  9973:                             $disk_quota,$current_disk_usage).
                   9974:                '</p>';
                   9975:     }
                   9976:     return;
                   9977: }
                   9978: 
                   9979: ###############################################
                   9980: 
                   9981: 
1.1136    raeburn  9982: 
                   9983: 
1.384     raeburn  9984: sub get_secgrprole_info {
                   9985:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9986:     my %sections_count = &get_sections($cdom,$cnum);
                   9987:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9988:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9989:     my @groups = sort(keys(%curr_groups));
                   9990:     my $allroles = [];
                   9991:     my $rolehash;
                   9992:     my $accesshash = {
                   9993:                      active => 'Currently has access',
                   9994:                      future => 'Will have future access',
                   9995:                      previous => 'Previously had access',
                   9996:                   };
                   9997:     if ($needroles) {
                   9998:         $rolehash = {'all' => 'all'};
1.385     albertel 9999:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10000: 	if (&Apache::lonnet::error(%user_roles)) {
                   10001: 	    undef(%user_roles);
                   10002: 	}
                   10003:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10004:             my ($role)=split(/\:/,$item,2);
                   10005:             if ($role eq 'cr') { next; }
                   10006:             if ($role =~ /^cr/) {
                   10007:                 $$rolehash{$role} = (split('/',$role))[3];
                   10008:             } else {
                   10009:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10010:             }
                   10011:         }
                   10012:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10013:             push(@{$allroles},$key);
                   10014:         }
                   10015:         push (@{$allroles},'st');
                   10016:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10017:     }
                   10018:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10019: }
                   10020: 
1.555     raeburn  10021: sub user_picker {
1.1255    raeburn  10022:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom) = @_;
1.555     raeburn  10023:     my $currdom = $dom;
1.1253    raeburn  10024:     my @alldoms = &Apache::lonnet::all_domains();
                   10025:     if (@alldoms == 1) {
                   10026:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10027:                                                ['directorysrch'],$alldoms[0]);
                   10028:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10029:         my $showdom = $domdesc;
                   10030:         if ($showdom eq '') {
                   10031:             $showdom = $dom;
                   10032:         }
                   10033:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10034:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10035:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10036:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10037:             }
                   10038:         }
                   10039:     }
1.555     raeburn  10040:     my %curr_selected = (
                   10041:                         srchin => 'dom',
1.580     raeburn  10042:                         srchby => 'lastname',
1.555     raeburn  10043:                       );
                   10044:     my $srchterm;
1.625     raeburn  10045:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10046:         if ($srch->{'srchby'} ne '') {
                   10047:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10048:         }
                   10049:         if ($srch->{'srchin'} ne '') {
                   10050:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10051:         }
                   10052:         if ($srch->{'srchtype'} ne '') {
                   10053:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10054:         }
                   10055:         if ($srch->{'srchdomain'} ne '') {
                   10056:             $currdom = $srch->{'srchdomain'};
                   10057:         }
                   10058:         $srchterm = $srch->{'srchterm'};
                   10059:     }
1.1222    damieng  10060:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10061:                     'usr'       => 'Search criteria',
1.563     raeburn  10062:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10063:                     'uname'     => 'username',
                   10064:                     'lastname'  => 'last name',
1.555     raeburn  10065:                     'lastfirst' => 'last name, first name',
1.558     albertel 10066:                     'crs'       => 'in this course',
1.576     raeburn  10067:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10068:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10069:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10070:                     'exact'     => 'is',
                   10071:                     'contains'  => 'contains',
1.569     raeburn  10072:                     'begins'    => 'begins with',
1.1222    damieng  10073:                                        );
                   10074:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10075:                     'youm'      => "You must include some text to search for.",
                   10076:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10077:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10078:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10079:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10080:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10081:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10082:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10083:                                        );
1.1222    damieng  10084:     &html_escape(\%html_lt);
                   10085:     &js_escape(\%js_lt);
1.1255    raeburn  10086:     my $domform;
                   10087:     if ($fixeddom) {
                   10088:         $domform = &select_dom_form($currdom,'srchdomain',1,1,undef,[$currdom]);
                   10089:     } else {
                   10090:         $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   10091:     }
1.563     raeburn  10092:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10093: 
                   10094:     my @srchins = ('crs','dom','alc','instd');
                   10095: 
                   10096:     foreach my $option (@srchins) {
                   10097:         # FIXME 'alc' option unavailable until 
                   10098:         #       loncreateuser::print_user_query_page()
                   10099:         #       has been completed.
                   10100:         next if ($option eq 'alc');
1.880     raeburn  10101:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10102:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  10103:         if ($curr_selected{'srchin'} eq $option) {
                   10104:             $srchinsel .= ' 
1.1222    damieng  10105:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10106:         } else {
                   10107:             $srchinsel .= '
1.1222    damieng  10108:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10109:         }
1.555     raeburn  10110:     }
1.563     raeburn  10111:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10112: 
                   10113:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10114:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10115:         if ($curr_selected{'srchby'} eq $option) {
                   10116:             $srchbysel .= '
1.1222    damieng  10117:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10118:         } else {
                   10119:             $srchbysel .= '
1.1222    damieng  10120:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10121:          }
                   10122:     }
                   10123:     $srchbysel .= "\n  </select>\n";
                   10124: 
                   10125:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10126:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10127:         if ($curr_selected{'srchtype'} eq $option) {
                   10128:             $srchtypesel .= '
1.1222    damieng  10129:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10130:         } else {
                   10131:             $srchtypesel .= '
1.1222    damieng  10132:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10133:         }
                   10134:     }
                   10135:     $srchtypesel .= "\n  </select>\n";
                   10136: 
1.558     albertel 10137:     my ($newuserscript,$new_user_create);
1.994     raeburn  10138:     my $context_dom = $env{'request.role.domain'};
                   10139:     if ($context eq 'requestcrs') {
                   10140:         if ($env{'form.coursedom'} ne '') { 
                   10141:             $context_dom = $env{'form.coursedom'};
                   10142:         }
                   10143:     }
1.556     raeburn  10144:     if ($forcenewuser) {
1.576     raeburn  10145:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10146:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10147:                 if ($cancreate) {
                   10148:                     $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>';
                   10149:                 } else {
1.799     bisitz   10150:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10151:                     my %usertypetext = (
                   10152:                         official   => 'institutional',
                   10153:                         unofficial => 'non-institutional',
                   10154:                     );
1.799     bisitz   10155:                     $new_user_create = '<p class="LC_warning">'
                   10156:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10157:                                       .' '
                   10158:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10159:                                           ,'<a href="'.$helplink.'">','</a>')
                   10160:                                       .'</p><br />';
1.627     raeburn  10161:                 }
1.576     raeburn  10162:             }
                   10163:         }
                   10164: 
1.556     raeburn  10165:         $newuserscript = <<"ENDSCRIPT";
                   10166: 
1.570     raeburn  10167: function setSearch(createnew,callingForm) {
1.556     raeburn  10168:     if (createnew == 1) {
1.570     raeburn  10169:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10170:             if (callingForm.srchby.options[i].value == 'uname') {
                   10171:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10172:             }
                   10173:         }
1.570     raeburn  10174:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10175:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10176: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10177:             }
                   10178:         }
1.570     raeburn  10179:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10180:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10181:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10182:             }
                   10183:         }
1.570     raeburn  10184:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10185:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10186:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10187:             }
                   10188:         }
                   10189:     }
                   10190: }
                   10191: ENDSCRIPT
1.558     albertel 10192: 
1.556     raeburn  10193:     }
                   10194: 
1.555     raeburn  10195:     my $output = <<"END_BLOCK";
1.556     raeburn  10196: <script type="text/javascript">
1.824     bisitz   10197: // <![CDATA[
1.570     raeburn  10198: function validateEntry(callingForm) {
1.558     albertel 10199: 
1.556     raeburn  10200:     var checkok = 1;
1.558     albertel 10201:     var srchin;
1.570     raeburn  10202:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10203: 	if ( callingForm.srchin[i].checked ) {
                   10204: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10205: 	}
                   10206:     }
                   10207: 
1.570     raeburn  10208:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10209:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10210:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10211:     var srchterm =  callingForm.srchterm.value;
                   10212:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10213:     var msg = "";
                   10214: 
                   10215:     if (srchterm == "") {
                   10216:         checkok = 0;
1.1222    damieng  10217:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10218:     }
                   10219: 
1.569     raeburn  10220:     if (srchtype== 'begins') {
                   10221:         if (srchterm.length < 2) {
                   10222:             checkok = 0;
1.1222    damieng  10223:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10224:         }
                   10225:     }
                   10226: 
1.556     raeburn  10227:     if (srchtype== 'contains') {
                   10228:         if (srchterm.length < 3) {
                   10229:             checkok = 0;
1.1222    damieng  10230:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10231:         }
                   10232:     }
                   10233:     if (srchin == 'instd') {
                   10234:         if (srchdomain == '') {
                   10235:             checkok = 0;
1.1222    damieng  10236:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10237:         }
                   10238:     }
                   10239:     if (srchin == 'dom') {
                   10240:         if (srchdomain == '') {
                   10241:             checkok = 0;
1.1222    damieng  10242:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10243:         }
                   10244:     }
                   10245:     if (srchby == 'lastfirst') {
                   10246:         if (srchterm.indexOf(",") == -1) {
                   10247:             checkok = 0;
1.1222    damieng  10248:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10249:         }
                   10250:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10251:             checkok = 0;
1.1222    damieng  10252:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10253:         }
                   10254:     }
                   10255:     if (checkok == 0) {
1.1222    damieng  10256:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10257:         return;
                   10258:     }
                   10259:     if (checkok == 1) {
1.570     raeburn  10260:         callingForm.submit();
1.556     raeburn  10261:     }
                   10262: }
                   10263: 
                   10264: $newuserscript
                   10265: 
1.824     bisitz   10266: // ]]>
1.556     raeburn  10267: </script>
1.558     albertel 10268: 
                   10269: $new_user_create
                   10270: 
1.555     raeburn  10271: END_BLOCK
1.558     albertel 10272: 
1.876     raeburn  10273:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10274:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10275:                $domform.
                   10276:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10277:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10278:                $srchbysel.
                   10279:                $srchtypesel. 
                   10280:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10281:                $srchinsel.
                   10282:                &Apache::lonhtmlcommon::row_closure(1). 
                   10283:                &Apache::lonhtmlcommon::end_pick_box().
                   10284:                '<br />';
1.1253    raeburn  10285:     return ($output,1);
1.555     raeburn  10286: }
                   10287: 
1.612     raeburn  10288: sub user_rule_check {
1.615     raeburn  10289:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10290:     my ($response,%inst_response);
1.612     raeburn  10291:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10292:         if (keys(%{$usershash}) > 1) {
                   10293:             my (%by_username,%by_id,%userdoms);
                   10294:             my $checkid; 
                   10295:             if (ref($checks) eq 'HASH') {
                   10296:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10297:                     $checkid = 1;
                   10298:                 }
                   10299:             }
                   10300:             foreach my $user (keys(%{$usershash})) {
                   10301:                 my ($uname,$udom) = split(/:/,$user);
                   10302:                 if ($checkid) {
                   10303:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10304:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10305:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10306:                             $userdoms{$udom} = 1;
1.1227    raeburn  10307:                             if (ref($inst_results) eq 'HASH') {
                   10308:                                 $inst_results->{$uname.':'.$udom} = {};
                   10309:                             }
1.1226    raeburn  10310:                         }
                   10311:                     }
                   10312:                 } else {
                   10313:                     $by_username{$udom}{$uname} = 1;
                   10314:                     $userdoms{$udom} = 1;
1.1227    raeburn  10315:                     if (ref($inst_results) eq 'HASH') {
                   10316:                         $inst_results->{$uname.':'.$udom} = {};
                   10317:                     }
1.1226    raeburn  10318:                 }
                   10319:             }
                   10320:             foreach my $udom (keys(%userdoms)) {
                   10321:                 if (!$got_rules->{$udom}) {
                   10322:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10323:                                                              ['usercreation'],$udom);
                   10324:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10325:                         foreach my $item ('username','id') {
                   10326:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10327:                                 $$curr_rules{$udom}{$item} =
                   10328:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10329:                             }
                   10330:                         }
                   10331:                     }
                   10332:                     $got_rules->{$udom} = 1;
                   10333:                 }
1.612     raeburn  10334:             }
1.1226    raeburn  10335:             if ($checkid) {
                   10336:                 foreach my $udom (keys(%by_id)) {
                   10337:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10338:                     if ($outcome eq 'ok') {
1.1227    raeburn  10339:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10340:                             my $uname = $by_id{$udom}{$id};
                   10341:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10342:                         }
1.1226    raeburn  10343:                         if (ref($results) eq 'HASH') {
                   10344:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  10345:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10346:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10347:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10348:                                 }
1.1226    raeburn  10349:                             }
                   10350:                         }
                   10351:                     }
1.612     raeburn  10352:                 }
1.615     raeburn  10353:             } else {
1.1226    raeburn  10354:                 foreach my $udom (keys(%by_username)) {
                   10355:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10356:                     if ($outcome eq 'ok') {
1.1227    raeburn  10357:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10358:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10359:                         }
1.1226    raeburn  10360:                         if (ref($results) eq 'HASH') {
                   10361:                             foreach my $uname (keys(%{$results})) {
                   10362:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10363:                             }
                   10364:                         }
                   10365:                     }
                   10366:                 }
1.612     raeburn  10367:             }
1.1226    raeburn  10368:         } elsif (keys(%{$usershash}) == 1) {
                   10369:             my $user = (keys(%{$usershash}))[0];
                   10370:             my ($uname,$udom) = split(/:/,$user);
                   10371:             if (($udom ne '') && ($uname ne '')) {
                   10372:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10373:                     if (ref($checks) eq 'HASH') {
                   10374:                         if (defined($checks->{'username'})) {
                   10375:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   10376:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10377:                         } elsif (defined($checks->{'id'})) {
                   10378:                             if ($usershash->{$user}->{'id'} ne '') {
                   10379:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10380:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10381:                                                                   $usershash->{$user}->{'id'});
                   10382:                             } else {
                   10383:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10384:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10385:                             }
1.585     raeburn  10386:                         }
1.1226    raeburn  10387:                     } else {
                   10388:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10389:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10390:                        return;
                   10391:                     }
                   10392:                     if (!$got_rules->{$udom}) {
                   10393:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10394:                                                                  ['usercreation'],$udom);
                   10395:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10396:                             foreach my $item ('username','id') {
                   10397:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10398:                                    $$curr_rules{$udom}{$item} = 
                   10399:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10400:                                 }
                   10401:                             }
                   10402:                         }
                   10403:                         $got_rules->{$udom} = 1;
1.585     raeburn  10404:                     }
                   10405:                 }
1.1226    raeburn  10406:             } else {
                   10407:                 return;
                   10408:             }
                   10409:         } else {
                   10410:             return;
                   10411:         }
                   10412:         foreach my $user (keys(%{$usershash})) {
                   10413:             my ($uname,$udom) = split(/:/,$user);
                   10414:             next if (($udom eq '') || ($uname eq ''));
                   10415:             my $id;
1.1227    raeburn  10416:             if (ref($inst_results) eq 'HASH') {
                   10417:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10418:                     $id = $inst_results->{$user}->{'id'};
                   10419:                 }
                   10420:             }
                   10421:             if ($id eq '') { 
                   10422:                 if (ref($usershash->{$user})) {
                   10423:                     $id = $usershash->{$user}->{'id'};
                   10424:                 }
1.585     raeburn  10425:             }
1.612     raeburn  10426:             foreach my $item (keys(%{$checks})) {
                   10427:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10428:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10429:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10430:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10431:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10432:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10433:                                 if ($rule_check{$rule}) {
                   10434:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10435:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10436:                                         if (ref($inst_results) eq 'HASH') {
                   10437:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10438:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10439:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10440:                                                 } elsif ($item eq 'id') {
                   10441:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10442:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10443:                                                     }
1.615     raeburn  10444:                                                 }
1.612     raeburn  10445:                                             }
                   10446:                                         }
1.615     raeburn  10447:                                     }
                   10448:                                     last;
1.585     raeburn  10449:                                 }
                   10450:                             }
                   10451:                         }
                   10452:                     }
                   10453:                 }
                   10454:             }
                   10455:         }
                   10456:     }
1.612     raeburn  10457:     return;
                   10458: }
                   10459: 
                   10460: sub user_rule_formats {
                   10461:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10462:     my %text = ( 
                   10463:                  'username' => 'Usernames',
                   10464:                  'id'       => 'IDs',
                   10465:                );
                   10466:     my $output;
                   10467:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10468:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10469:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10470:             $output = '<br />'.
                   10471:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10472:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10473:                       ' <ul>';
1.612     raeburn  10474:             foreach my $rule (@{$ruleorder}) {
                   10475:                 if (ref($curr_rules) eq 'ARRAY') {
                   10476:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10477:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10478:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10479:                                         $rules->{$rule}{'desc'}.'</li>';
                   10480:                         }
                   10481:                     }
                   10482:                 }
                   10483:             }
                   10484:             $output .= '</ul>';
                   10485:         }
                   10486:     }
                   10487:     return $output;
                   10488: }
                   10489: 
                   10490: sub instrule_disallow_msg {
1.615     raeburn  10491:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10492:     my $response;
                   10493:     my %text = (
                   10494:                   item   => 'username',
                   10495:                   items  => 'usernames',
                   10496:                   match  => 'matches',
                   10497:                   do     => 'does',
                   10498:                   action => 'a username',
                   10499:                   one    => 'one',
                   10500:                );
                   10501:     if ($count > 1) {
                   10502:         $text{'item'} = 'usernames';
                   10503:         $text{'match'} ='match';
                   10504:         $text{'do'} = 'do';
                   10505:         $text{'action'} = 'usernames',
                   10506:         $text{'one'} = 'ones';
                   10507:     }
                   10508:     if ($checkitem eq 'id') {
                   10509:         $text{'items'} = 'IDs';
                   10510:         $text{'item'} = 'ID';
                   10511:         $text{'action'} = 'an ID';
1.615     raeburn  10512:         if ($count > 1) {
                   10513:             $text{'item'} = 'IDs';
                   10514:             $text{'action'} = 'IDs';
                   10515:         }
1.612     raeburn  10516:     }
1.674     bisitz   10517:     $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  10518:     if ($mode eq 'upload') {
                   10519:         if ($checkitem eq 'username') {
                   10520:             $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'}.");
                   10521:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10522:             $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  10523:         }
1.669     raeburn  10524:     } elsif ($mode eq 'selfcreate') {
                   10525:         if ($checkitem eq 'id') {
                   10526:             $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.");
                   10527:         }
1.615     raeburn  10528:     } else {
                   10529:         if ($checkitem eq 'username') {
                   10530:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10531:         } elsif ($checkitem eq 'id') {
                   10532:             $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.");
                   10533:         }
1.612     raeburn  10534:     }
                   10535:     return $response;
1.585     raeburn  10536: }
                   10537: 
1.624     raeburn  10538: sub personal_data_fieldtitles {
                   10539:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10540:                         id => 'Student/Employee ID',
                   10541:                         permanentemail => 'E-mail address',
                   10542:                         lastname => 'Last Name',
                   10543:                         firstname => 'First Name',
                   10544:                         middlename => 'Middle Name',
                   10545:                         generation => 'Generation',
                   10546:                         gen => 'Generation',
1.765     raeburn  10547:                         inststatus => 'Affiliation',
1.624     raeburn  10548:                    );
                   10549:     return %fieldtitles;
                   10550: }
                   10551: 
1.642     raeburn  10552: sub sorted_inst_types {
                   10553:     my ($dom) = @_;
1.1185    raeburn  10554:     my ($usertypes,$order);
                   10555:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10556:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10557:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10558:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10559:     } else {
                   10560:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10561:     }
1.642     raeburn  10562:     my $othertitle = &mt('All users');
                   10563:     if ($env{'request.course.id'}) {
1.668     raeburn  10564:         $othertitle  = &mt('Any users');
1.642     raeburn  10565:     }
                   10566:     my @types;
                   10567:     if (ref($order) eq 'ARRAY') {
                   10568:         @types = @{$order};
                   10569:     }
                   10570:     if (@types == 0) {
                   10571:         if (ref($usertypes) eq 'HASH') {
                   10572:             @types = sort(keys(%{$usertypes}));
                   10573:         }
                   10574:     }
                   10575:     if (keys(%{$usertypes}) > 0) {
                   10576:         $othertitle = &mt('Other users');
                   10577:     }
                   10578:     return ($othertitle,$usertypes,\@types);
                   10579: }
                   10580: 
1.645     raeburn  10581: sub get_institutional_codes {
                   10582:     my ($settings,$allcourses,$LC_code) = @_;
                   10583: # Get complete list of course sections to update
                   10584:     my @currsections = ();
                   10585:     my @currxlists = ();
                   10586:     my $coursecode = $$settings{'internal.coursecode'};
                   10587: 
                   10588:     if ($$settings{'internal.sectionnums'} ne '') {
                   10589:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10590:     }
                   10591: 
                   10592:     if ($$settings{'internal.crosslistings'} ne '') {
                   10593:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10594:     }
                   10595: 
                   10596:     if (@currxlists > 0) {
                   10597:         foreach (@currxlists) {
                   10598:             if (m/^([^:]+):(\w*)$/) {
                   10599:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  10600:                     push(@{$allcourses},$1);
1.645     raeburn  10601:                     $$LC_code{$1} = $2;
                   10602:                 }
                   10603:             }
                   10604:         }
                   10605:     }
                   10606:  
                   10607:     if (@currsections > 0) {
                   10608:         foreach (@currsections) {
                   10609:             if (m/^(\w+):(\w*)$/) {
                   10610:                 my $sec = $coursecode.$1;
                   10611:                 my $lc_sec = $2;
                   10612:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1263    raeburn  10613:                     push(@{$allcourses},$sec);
1.645     raeburn  10614:                     $$LC_code{$sec} = $lc_sec;
                   10615:                 }
                   10616:             }
                   10617:         }
                   10618:     }
                   10619:     return;
                   10620: }
                   10621: 
1.971     raeburn  10622: sub get_standard_codeitems {
                   10623:     return ('Year','Semester','Department','Number','Section');
                   10624: }
                   10625: 
1.112     bowersj2 10626: =pod
                   10627: 
1.780     raeburn  10628: =head1 Slot Helpers
                   10629: 
                   10630: =over 4
                   10631: 
                   10632: =item * sorted_slots()
                   10633: 
1.1040    raeburn  10634: Sorts an array of slot names in order of an optional sort key,
                   10635: default sort is by slot start time (earliest first). 
1.780     raeburn  10636: 
                   10637: Inputs:
                   10638: 
                   10639: =over 4
                   10640: 
                   10641: slotsarr  - Reference to array of unsorted slot names.
                   10642: 
                   10643: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10644: 
1.1040    raeburn  10645: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10646: 
1.549     albertel 10647: =back
                   10648: 
1.780     raeburn  10649: Returns:
                   10650: 
                   10651: =over 4
                   10652: 
1.1040    raeburn  10653: sorted   - An array of slot names sorted by a specified sort key 
                   10654:            (default sort key is start time of the slot).
1.780     raeburn  10655: 
                   10656: =back
                   10657: 
                   10658: =cut
                   10659: 
                   10660: 
                   10661: sub sorted_slots {
1.1040    raeburn  10662:     my ($slotsarr,$slots,$sortkey) = @_;
                   10663:     if ($sortkey eq '') {
                   10664:         $sortkey = 'starttime';
                   10665:     }
1.780     raeburn  10666:     my @sorted;
                   10667:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10668:         @sorted =
                   10669:             sort {
                   10670:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10671:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10672:                      }
                   10673:                      if (ref($slots->{$a})) { return -1;}
                   10674:                      if (ref($slots->{$b})) { return 1;}
                   10675:                      return 0;
                   10676:                  } @{$slotsarr};
                   10677:     }
                   10678:     return @sorted;
                   10679: }
                   10680: 
1.1040    raeburn  10681: =pod
                   10682: 
                   10683: =item * get_future_slots()
                   10684: 
                   10685: Inputs:
                   10686: 
                   10687: =over 4
                   10688: 
                   10689: cnum - course number
                   10690: 
                   10691: cdom - course domain
                   10692: 
                   10693: now - current UNIX time
                   10694: 
                   10695: symb - optional symb
                   10696: 
                   10697: =back
                   10698: 
                   10699: Returns:
                   10700: 
                   10701: =over 4
                   10702: 
                   10703: sorted_reservable - ref to array of student_schedulable slots currently 
                   10704:                     reservable, ordered by end date of reservation period.
                   10705: 
                   10706: reservable_now - ref to hash of student_schedulable slots currently
                   10707:                  reservable.
                   10708: 
                   10709:     Keys in inner hash are:
                   10710:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10711:     (b) endreserve: end date of reservation period.
                   10712:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10713:         selected.
1.1040    raeburn  10714: 
                   10715: sorted_future - ref to array of student_schedulable slots reservable in
                   10716:                 the future, ordered by start date of reservation period.
                   10717: 
                   10718: future_reservable - ref to hash of student_schedulable slots reservable
                   10719:                     in the future.
                   10720: 
                   10721:     Keys in inner hash are:
                   10722:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10723:     (b) startreserve: start date of reservation period.
                   10724:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10725:         selected.
1.1040    raeburn  10726: 
                   10727: =back
                   10728: 
                   10729: =cut
                   10730: 
                   10731: sub get_future_slots {
                   10732:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  10733:     my $map;
                   10734:     if ($symb) {
                   10735:         ($map) = &Apache::lonnet::decode_symb($symb);
                   10736:     }
1.1040    raeburn  10737:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10738:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10739:     foreach my $slot (keys(%slots)) {
                   10740:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10741:         if ($symb) {
1.1229    raeburn  10742:             if ($slots{$slot}->{'symb'} ne '') {
                   10743:                 my $canuse;
                   10744:                 my %oksymbs;
                   10745:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   10746:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   10747:                 if ($oksymbs{$symb}) {
                   10748:                     $canuse = 1;
                   10749:                 } else {
                   10750:                     foreach my $item (@slotsymbs) {
                   10751:                         if ($item =~ /\.(page|sequence)$/) {
                   10752:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   10753:                             if (($map ne '') && ($map eq $sloturl)) {
                   10754:                                 $canuse = 1;
                   10755:                                 last;
                   10756:                             }
                   10757:                         }
                   10758:                     }
                   10759:                 }
                   10760:                 next unless ($canuse);
                   10761:             }
1.1040    raeburn  10762:         }
                   10763:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10764:             ($slots{$slot}->{'endtime'} > $now)) {
                   10765:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10766:                 my $userallowed = 0;
                   10767:                 if ($slots{$slot}->{'allowedsections'}) {
                   10768:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10769:                     if (!defined($env{'request.role.sec'})
                   10770:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10771:                         $userallowed=1;
                   10772:                     } else {
                   10773:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10774:                             $userallowed=1;
                   10775:                         }
                   10776:                     }
                   10777:                     unless ($userallowed) {
                   10778:                         if (defined($env{'request.course.groups'})) {
                   10779:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10780:                             foreach my $group (@groups) {
                   10781:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10782:                                     $userallowed=1;
                   10783:                                     last;
                   10784:                                 }
                   10785:                             }
                   10786:                         }
                   10787:                     }
                   10788:                 }
                   10789:                 if ($slots{$slot}->{'allowedusers'}) {
                   10790:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10791:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10792:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10793:                         $userallowed = 1;
                   10794:                     }
                   10795:                 }
                   10796:                 next unless($userallowed);
                   10797:             }
                   10798:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10799:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10800:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  10801:             my $uniqueperiod;
                   10802:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10803:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10804:             }
1.1040    raeburn  10805:             if (($startreserve < $now) &&
                   10806:                 (!$endreserve || $endreserve > $now)) {
                   10807:                 my $lastres = $endreserve;
                   10808:                 if (!$lastres) {
                   10809:                     $lastres = $slots{$slot}->{'starttime'};
                   10810:                 }
                   10811:                 $reservable_now{$slot} = {
                   10812:                                            symb       => $symb,
1.1250    raeburn  10813:                                            endreserve => $lastres,
                   10814:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  10815:                                          };
                   10816:             } elsif (($startreserve > $now) &&
                   10817:                      (!$endreserve || $endreserve > $startreserve)) {
                   10818:                 $future_reservable{$slot} = {
                   10819:                                               symb         => $symb,
1.1250    raeburn  10820:                                               startreserve => $startreserve,
                   10821:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10822:                                             };
                   10823:             }
                   10824:         }
                   10825:     }
                   10826:     my @unsorted_reservable = keys(%reservable_now);
                   10827:     if (@unsorted_reservable > 0) {
                   10828:         @sorted_reservable = 
                   10829:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10830:     }
                   10831:     my @unsorted_future = keys(%future_reservable);
                   10832:     if (@unsorted_future > 0) {
                   10833:         @sorted_future =
                   10834:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10835:     }
                   10836:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10837: }
1.780     raeburn  10838: 
                   10839: =pod
                   10840: 
1.1057    foxr     10841: =back
                   10842: 
1.549     albertel 10843: =head1 HTTP Helpers
                   10844: 
                   10845: =over 4
                   10846: 
1.648     raeburn  10847: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10848: 
1.258     albertel 10849: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10850: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10851: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10852: 
                   10853: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10854: $possible_names is an ref to an array of form element names.  As an example:
                   10855: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10856: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10857: 
                   10858: =cut
1.1       albertel 10859: 
1.6       albertel 10860: sub get_unprocessed_cgi {
1.25      albertel 10861:   my ($query,$possible_names)= @_;
1.26      matthew  10862:   # $Apache::lonxml::debug=1;
1.356     albertel 10863:   foreach my $pair (split(/&/,$query)) {
                   10864:     my ($name, $value) = split(/=/,$pair);
1.369     www      10865:     $name = &unescape($name);
1.25      albertel 10866:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10867:       $value =~ tr/+/ /;
                   10868:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10869:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10870:     }
1.16      harris41 10871:   }
1.6       albertel 10872: }
                   10873: 
1.112     bowersj2 10874: =pod
                   10875: 
1.648     raeburn  10876: =item * &cacheheader() 
1.112     bowersj2 10877: 
                   10878: returns cache-controlling header code
                   10879: 
                   10880: =cut
                   10881: 
1.7       albertel 10882: sub cacheheader {
1.258     albertel 10883:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10884:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10885:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10886:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10887:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10888:     return $output;
1.7       albertel 10889: }
                   10890: 
1.112     bowersj2 10891: =pod
                   10892: 
1.648     raeburn  10893: =item * &no_cache($r) 
1.112     bowersj2 10894: 
                   10895: specifies header code to not have cache
                   10896: 
                   10897: =cut
                   10898: 
1.9       albertel 10899: sub no_cache {
1.216     albertel 10900:     my ($r) = @_;
                   10901:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10902: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10903:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10904:     $r->no_cache(1);
                   10905:     $r->header_out("Expires" => $date);
                   10906:     $r->header_out("Pragma" => "no-cache");
1.123     www      10907: }
                   10908: 
                   10909: sub content_type {
1.181     albertel 10910:     my ($r,$type,$charset) = @_;
1.299     foxr     10911:     if ($r) {
                   10912: 	#  Note that printout.pl calls this with undef for $r.
                   10913: 	&no_cache($r);
                   10914:     }
1.258     albertel 10915:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10916:     unless ($charset) {
                   10917: 	$charset=&Apache::lonlocal::current_encoding;
                   10918:     }
                   10919:     if ($charset) { $type.='; charset='.$charset; }
                   10920:     if ($r) {
                   10921: 	$r->content_type($type);
                   10922:     } else {
                   10923: 	print("Content-type: $type\n\n");
                   10924:     }
1.9       albertel 10925: }
1.25      albertel 10926: 
1.112     bowersj2 10927: =pod
                   10928: 
1.648     raeburn  10929: =item * &add_to_env($name,$value) 
1.112     bowersj2 10930: 
1.258     albertel 10931: adds $name to the %env hash with value
1.112     bowersj2 10932: $value, if $name already exists, the entry is converted to an array
                   10933: reference and $value is added to the array.
                   10934: 
                   10935: =cut
                   10936: 
1.25      albertel 10937: sub add_to_env {
                   10938:   my ($name,$value)=@_;
1.258     albertel 10939:   if (defined($env{$name})) {
                   10940:     if (ref($env{$name})) {
1.25      albertel 10941:       #already have multiple values
1.258     albertel 10942:       push(@{ $env{$name} },$value);
1.25      albertel 10943:     } else {
                   10944:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10945:       my $first=$env{$name};
                   10946:       undef($env{$name});
                   10947:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10948:     }
                   10949:   } else {
1.258     albertel 10950:     $env{$name}=$value;
1.25      albertel 10951:   }
1.31      albertel 10952: }
1.149     albertel 10953: 
                   10954: =pod
                   10955: 
1.648     raeburn  10956: =item * &get_env_multiple($name) 
1.149     albertel 10957: 
1.258     albertel 10958: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10959: values may be defined and end up as an array ref.
                   10960: 
                   10961: returns an array of values
                   10962: 
                   10963: =cut
                   10964: 
                   10965: sub get_env_multiple {
                   10966:     my ($name) = @_;
                   10967:     my @values;
1.258     albertel 10968:     if (defined($env{$name})) {
1.149     albertel 10969:         # exists is it an array
1.258     albertel 10970:         if (ref($env{$name})) {
                   10971:             @values=@{ $env{$name} };
1.149     albertel 10972:         } else {
1.258     albertel 10973:             $values[0]=$env{$name};
1.149     albertel 10974:         }
                   10975:     }
                   10976:     return(@values);
                   10977: }
                   10978: 
1.1249    damieng  10979: # Looks at given dependencies, and returns something depending on the context.
                   10980: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   10981: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   10982: # For all other contexts, returns ($output, $counter, $numpathchg).
                   10983: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   10984: # $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.
                   10985: # $numpathchg: integer with the number of cleaned up dependency paths.
                   10986: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   10987: # \%mapping: hash reference clean path -> original path for all dependencies.
                   10988: # @param {string} actionurl - The path to the handler, indicative of the context.
                   10989: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   10990: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   10991: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   10992: # @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)
                   10993: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  10994: sub ask_for_embedded_content {
1.1249    damieng  10995:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  10996:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10997:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  10998:         %currsubfile,%unused,$rem);
1.1071    raeburn  10999:     my $counter = 0;
                   11000:     my $numnew = 0;
1.987     raeburn  11001:     my $numremref = 0;
                   11002:     my $numinvalid = 0;
                   11003:     my $numpathchg = 0;
                   11004:     my $numexisting = 0;
1.1071    raeburn  11005:     my $numunused = 0;
                   11006:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11007:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11008:     my $heading = &mt('Upload embedded files');
                   11009:     my $buttontext = &mt('Upload');
                   11010: 
1.1249    damieng  11011:     # fills these variables based on the context:
                   11012:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11013:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11014:     if ($env{'request.course.id'}) {
1.1123    raeburn  11015:         if ($actionurl eq '/adm/dependencies') {
                   11016:             $navmap = Apache::lonnavmaps::navmap->new();
                   11017:         }
                   11018:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11019:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11020:     }
1.1123    raeburn  11021:     if (($actionurl eq '/adm/portfolio') || 
                   11022:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11023:         my $current_path='/';
                   11024:         if ($env{'form.currentpath'}) {
                   11025:             $current_path = $env{'form.currentpath'};
                   11026:         }
                   11027:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11028:             $udom = $cdom;
                   11029:             $uname = $cnum;
1.984     raeburn  11030:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11031:         } else {
                   11032:             $udom = $env{'user.domain'};
                   11033:             $uname = $env{'user.name'};
                   11034:             $url = '/userfiles/portfolio';
                   11035:         }
1.987     raeburn  11036:         $toplevel = $url.'/';
1.984     raeburn  11037:         $url .= $current_path;
                   11038:         $getpropath = 1;
1.987     raeburn  11039:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11040:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11041:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11042:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11043:         $toplevel = $url;
1.984     raeburn  11044:         if ($rest ne '') {
1.987     raeburn  11045:             $url .= $rest;
                   11046:         }
                   11047:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11048:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11049:             $url = $args->{'docs_url'};
                   11050:             $toplevel = $url;
1.1084    raeburn  11051:             if ($args->{'context'} eq 'paste') {
                   11052:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11053:                 ($path) = 
                   11054:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11055:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11056:                 $fileloc =~ s{^/}{};
                   11057:             }
1.1071    raeburn  11058:         }
1.1084    raeburn  11059:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11060:         if ($env{'request.course.id'} ne '') {
                   11061:             if (ref($args) eq 'HASH') {
                   11062:                 $url = $args->{'docs_url'};
                   11063:                 $title = $args->{'docs_title'};
1.1126    raeburn  11064:                 $toplevel = $url; 
                   11065:                 unless ($toplevel =~ m{^/}) {
                   11066:                     $toplevel = "/$url";
                   11067:                 }
1.1085    raeburn  11068:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11069:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11070:                     $path = $1;
                   11071:                 } else {
                   11072:                     ($path) =
                   11073:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11074:                 }
1.1195    raeburn  11075:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11076:                     $fileloc = $toplevel;
                   11077:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11078:                     my ($udom,$uname,$fname) =
                   11079:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11080:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11081:                 } else {
                   11082:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11083:                 }
1.1071    raeburn  11084:                 $fileloc =~ s{^/}{};
                   11085:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11086:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11087:             }
1.987     raeburn  11088:         }
1.1123    raeburn  11089:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11090:         $udom = $cdom;
                   11091:         $uname = $cnum;
                   11092:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11093:         $toplevel = $url;
                   11094:         $path = $url;
                   11095:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11096:         $fileloc =~ s{^/}{};
1.987     raeburn  11097:     }
1.1249    damieng  11098:     
                   11099:     # parses the dependency paths to get some info
                   11100:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11101:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11102:     # (will be completed later)
                   11103:     # $mapping:
                   11104:     #   for external URLs: external URL -> external URL
                   11105:     #   for relative paths: clean path -> original path
                   11106:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11107:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11108:     foreach my $file (keys(%{$allfiles})) {
                   11109:         my $embed_file;
                   11110:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11111:             $embed_file = $1;
                   11112:         } else {
                   11113:             $embed_file = $file;
                   11114:         }
1.1158    raeburn  11115:         my ($absolutepath,$cleaned_file);
                   11116:         if ($embed_file =~ m{^\w+://}) {
                   11117:             $cleaned_file = $embed_file;
1.1147    raeburn  11118:             $newfiles{$cleaned_file} = 1;
                   11119:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11120:         } else {
1.1158    raeburn  11121:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11122:             if ($embed_file =~ m{^/}) {
                   11123:                 $absolutepath = $embed_file;
                   11124:             }
1.1147    raeburn  11125:             if ($cleaned_file =~ m{/}) {
                   11126:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11127:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11128:                 my $item = $fname;
                   11129:                 if ($path ne '') {
                   11130:                     $item = $path.'/'.$fname;
                   11131:                     $subdependencies{$path}{$fname} = 1;
                   11132:                 } else {
                   11133:                     $dependencies{$item} = 1;
                   11134:                 }
                   11135:                 if ($absolutepath) {
                   11136:                     $mapping{$item} = $absolutepath;
                   11137:                 } else {
                   11138:                     $mapping{$item} = $embed_file;
                   11139:                 }
                   11140:             } else {
                   11141:                 $dependencies{$embed_file} = 1;
                   11142:                 if ($absolutepath) {
1.1147    raeburn  11143:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11144:                 } else {
1.1147    raeburn  11145:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11146:                 }
                   11147:             }
1.984     raeburn  11148:         }
                   11149:     }
1.1249    damieng  11150:     
                   11151:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11152:     # and lists
                   11153:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11154:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11155:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11156:     #                                    the path had to be cleaned up
                   11157:     # $existing: hash clean path -> 1 if the file exists
                   11158:     # $numexisting: number of keys in $existing
                   11159:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11160:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11161:     #                                      dependency subdirectories that are
                   11162:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11163:     my $dirptr = 16384;
1.984     raeburn  11164:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11165:         $currsubfile{$path} = {};
1.1123    raeburn  11166:         if (($actionurl eq '/adm/portfolio') || 
                   11167:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11168:             my ($sublistref,$listerror) =
                   11169:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11170:             if (ref($sublistref) eq 'ARRAY') {
                   11171:                 foreach my $line (@{$sublistref}) {
                   11172:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11173:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11174:                 }
1.984     raeburn  11175:             }
1.987     raeburn  11176:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11177:             if (opendir(my $dir,$url.'/'.$path)) {
                   11178:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11179:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11180:             }
1.1084    raeburn  11181:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11182:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11183:                   ($args->{'context'} eq 'paste')) ||
                   11184:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11185:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11186:                 my $dir;
                   11187:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11188:                     $dir = $fileloc;
                   11189:                 } else {
                   11190:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11191:                 }
1.1071    raeburn  11192:                 if ($dir ne '') {
                   11193:                     my ($sublistref,$listerror) =
                   11194:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11195:                     if (ref($sublistref) eq 'ARRAY') {
                   11196:                         foreach my $line (@{$sublistref}) {
                   11197:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11198:                                 undef,$mtime)=split(/\&/,$line,12);
                   11199:                             unless (($testdir&$dirptr) ||
                   11200:                                     ($file_name =~ /^\.\.?$/)) {
                   11201:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11202:                             }
                   11203:                         }
                   11204:                     }
                   11205:                 }
1.984     raeburn  11206:             }
                   11207:         }
                   11208:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11209:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11210:                 my $item = $path.'/'.$file;
                   11211:                 unless ($mapping{$item} eq $item) {
                   11212:                     $pathchanges{$item} = 1;
                   11213:                 }
                   11214:                 $existing{$item} = 1;
                   11215:                 $numexisting ++;
                   11216:             } else {
                   11217:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11218:             }
                   11219:         }
1.1071    raeburn  11220:         if ($actionurl eq '/adm/dependencies') {
                   11221:             foreach my $path (keys(%currsubfile)) {
                   11222:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11223:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11224:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11225:                              next if (($rem ne '') &&
                   11226:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11227:                                        (ref($navmap) &&
                   11228:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11229:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11230:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11231:                              $unused{$path.'/'.$file} = 1; 
                   11232:                          }
                   11233:                     }
                   11234:                 }
                   11235:             }
                   11236:         }
1.984     raeburn  11237:     }
1.1249    damieng  11238:     
                   11239:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11240:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11241:     my %currfile;
1.1123    raeburn  11242:     if (($actionurl eq '/adm/portfolio') ||
                   11243:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11244:         my ($dirlistref,$listerror) =
                   11245:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11246:         if (ref($dirlistref) eq 'ARRAY') {
                   11247:             foreach my $line (@{$dirlistref}) {
                   11248:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11249:                 $currfile{$file_name} = 1;
                   11250:             }
1.984     raeburn  11251:         }
1.987     raeburn  11252:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11253:         if (opendir(my $dir,$url)) {
1.987     raeburn  11254:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11255:             map {$currfile{$_} = 1;} @dir_list;
                   11256:         }
1.1084    raeburn  11257:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11258:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11259:               ($args->{'context'} eq 'paste')) ||
                   11260:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11261:         if ($env{'request.course.id'} ne '') {
                   11262:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11263:             if ($dir ne '') {
                   11264:                 my ($dirlistref,$listerror) =
                   11265:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11266:                 if (ref($dirlistref) eq 'ARRAY') {
                   11267:                     foreach my $line (@{$dirlistref}) {
                   11268:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11269:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11270:                         unless (($testdir&$dirptr) ||
                   11271:                                 ($file_name =~ /^\.\.?$/)) {
                   11272:                             $currfile{$file_name} = [$size,$mtime];
                   11273:                         }
                   11274:                     }
                   11275:                 }
                   11276:             }
                   11277:         }
1.984     raeburn  11278:     }
1.1249    damieng  11279:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11280:     # are not in subdirectories, using $currfile
1.984     raeburn  11281:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11282:         if (exists($currfile{$file})) {
1.987     raeburn  11283:             unless ($mapping{$file} eq $file) {
                   11284:                 $pathchanges{$file} = 1;
                   11285:             }
                   11286:             $existing{$file} = 1;
                   11287:             $numexisting ++;
                   11288:         } else {
1.984     raeburn  11289:             $newfiles{$file} = 1;
                   11290:         }
                   11291:     }
1.1071    raeburn  11292:     foreach my $file (keys(%currfile)) {
                   11293:         unless (($file eq $filename) ||
                   11294:                 ($file eq $filename.'.bak') ||
                   11295:                 ($dependencies{$file})) {
1.1085    raeburn  11296:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11297:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11298:                     next if (($rem ne '') &&
                   11299:                              (($env{"httpref.$rem".$file} ne '') ||
                   11300:                               (ref($navmap) &&
                   11301:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11302:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11303:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11304:                 }
1.1085    raeburn  11305:             }
1.1071    raeburn  11306:             $unused{$file} = 1;
                   11307:         }
                   11308:     }
1.1249    damieng  11309:     
                   11310:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11311:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11312:         ($args->{'context'} eq 'paste')) {
                   11313:         $counter = scalar(keys(%existing));
                   11314:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11315:         return ($output,$counter,$numpathchg,\%existing);
                   11316:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11317:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11318:         $counter = scalar(keys(%existing));
                   11319:         $numpathchg = scalar(keys(%pathchanges));
                   11320:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  11321:     }
1.1249    damieng  11322:     
                   11323:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   11324:     
                   11325:     # $upload_output: missing dependencies (with upload form)
                   11326:     # $modify_output: uploaded dependencies (in use)
                   11327:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  11328:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11329:         if ($actionurl eq '/adm/dependencies') {
                   11330:             next if ($embed_file =~ m{^\w+://});
                   11331:         }
1.660     raeburn  11332:         $upload_output .= &start_data_table_row().
1.1123    raeburn  11333:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11334:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11335:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  11336:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11337:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11338:         }
1.1123    raeburn  11339:         $upload_output .= '</td>';
1.1071    raeburn  11340:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  11341:             $upload_output.='<td align="right">'.
                   11342:                             '<span class="LC_info LC_fontsize_medium">'.
                   11343:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11344:             $numremref++;
1.660     raeburn  11345:         } elsif ($args->{'error_on_invalid_names'}
                   11346:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  11347:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11348:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11349:             $numinvalid++;
1.660     raeburn  11350:         } else {
1.1123    raeburn  11351:             $upload_output .= '<td>'.
                   11352:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11353:                                                      $embed_file,\%mapping,
1.1071    raeburn  11354:                                                      $allfiles,$codebase,'upload');
                   11355:             $counter ++;
                   11356:             $numnew ++;
1.987     raeburn  11357:         }
                   11358:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11359:     }
                   11360:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11361:         if ($actionurl eq '/adm/dependencies') {
                   11362:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11363:             $modify_output .= &start_data_table_row().
                   11364:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11365:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11366:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11367:                               '<td>'.$size.'</td>'.
                   11368:                               '<td>'.$mtime.'</td>'.
                   11369:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11370:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11371:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11372:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11373:                               &embedded_file_element('upload_embedded',$counter,
                   11374:                                                      $embed_file,\%mapping,
                   11375:                                                      $allfiles,$codebase,'modify').
                   11376:                               '</div></td>'.
                   11377:                               &end_data_table_row()."\n";
                   11378:             $counter ++;
                   11379:         } else {
                   11380:             $upload_output .= &start_data_table_row().
1.1123    raeburn  11381:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11382:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11383:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11384:                               &Apache::loncommon::end_data_table_row()."\n";
                   11385:         }
                   11386:     }
                   11387:     my $delidx = $counter;
                   11388:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11389:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11390:         $delete_output .= &start_data_table_row().
                   11391:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11392:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11393:                           '<td>'.$size.'</td>'.
                   11394:                           '<td>'.$mtime.'</td>'.
                   11395:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11396:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11397:                           &embedded_file_element('upload_embedded',$delidx,
                   11398:                                                  $oldfile,\%mapping,$allfiles,
                   11399:                                                  $codebase,'delete').'</td>'.
                   11400:                           &end_data_table_row()."\n"; 
                   11401:         $numunused ++;
                   11402:         $delidx ++;
1.987     raeburn  11403:     }
                   11404:     if ($upload_output) {
                   11405:         $upload_output = &start_data_table().
                   11406:                          $upload_output.
                   11407:                          &end_data_table()."\n";
                   11408:     }
1.1071    raeburn  11409:     if ($modify_output) {
                   11410:         $modify_output = &start_data_table().
                   11411:                          &start_data_table_header_row().
                   11412:                          '<th>'.&mt('File').'</th>'.
                   11413:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11414:                          '<th>'.&mt('Modified').'</th>'.
                   11415:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11416:                          &end_data_table_header_row().
                   11417:                          $modify_output.
                   11418:                          &end_data_table()."\n";
                   11419:     }
                   11420:     if ($delete_output) {
                   11421:         $delete_output = &start_data_table().
                   11422:                          &start_data_table_header_row().
                   11423:                          '<th>'.&mt('File').'</th>'.
                   11424:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11425:                          '<th>'.&mt('Modified').'</th>'.
                   11426:                          '<th>'.&mt('Delete?').'</th>'.
                   11427:                          &end_data_table_header_row().
                   11428:                          $delete_output.
                   11429:                          &end_data_table()."\n";
                   11430:     }
1.987     raeburn  11431:     my $applies = 0;
                   11432:     if ($numremref) {
                   11433:         $applies ++;
                   11434:     }
                   11435:     if ($numinvalid) {
                   11436:         $applies ++;
                   11437:     }
                   11438:     if ($numexisting) {
                   11439:         $applies ++;
                   11440:     }
1.1071    raeburn  11441:     if ($counter || $numunused) {
1.987     raeburn  11442:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11443:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11444:                   $state.'<h3>'.$heading.'</h3>'; 
                   11445:         if ($actionurl eq '/adm/dependencies') {
                   11446:             if ($numnew) {
                   11447:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11448:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11449:                            $upload_output.'<br />'."\n";
                   11450:             }
                   11451:             if ($numexisting) {
                   11452:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11453:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11454:                            $modify_output.'<br />'."\n";
                   11455:                            $buttontext = &mt('Save changes');
                   11456:             }
                   11457:             if ($numunused) {
                   11458:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11459:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11460:                            $delete_output.'<br />'."\n";
                   11461:                            $buttontext = &mt('Save changes');
                   11462:             }
                   11463:         } else {
                   11464:             $output .= $upload_output.'<br />'."\n";
                   11465:         }
                   11466:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11467:                    $counter.'" />'."\n";
                   11468:         if ($actionurl eq '/adm/dependencies') { 
                   11469:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11470:                        $numnew.'" />'."\n";
                   11471:         } elsif ($actionurl eq '') {
1.987     raeburn  11472:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11473:         }
                   11474:     } elsif ($applies) {
                   11475:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11476:         if ($applies > 1) {
                   11477:             $output .=  
1.1123    raeburn  11478:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11479:             if ($numremref) {
                   11480:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11481:             }
                   11482:             if ($numinvalid) {
                   11483:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11484:             }
                   11485:             if ($numexisting) {
                   11486:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11487:             }
                   11488:             $output .= '</ul><br />';
                   11489:         } elsif ($numremref) {
                   11490:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11491:         } elsif ($numinvalid) {
                   11492:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11493:         } elsif ($numexisting) {
                   11494:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11495:         }
                   11496:         $output .= $upload_output.'<br />';
                   11497:     }
                   11498:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11499:     $chgcount = $counter;
1.987     raeburn  11500:     if (keys(%pathchanges) > 0) {
                   11501:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11502:             if ($counter) {
1.987     raeburn  11503:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11504:                                                   $embed_file,\%mapping,
1.1071    raeburn  11505:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11506:             } else {
                   11507:                 $pathchange_output .= 
                   11508:                     &start_data_table_row().
                   11509:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11510:                     $chgcount.'" checked="checked" /></td>'.
                   11511:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11512:                     '<td>'.$embed_file.
                   11513:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11514:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11515:                     '</td>'.&end_data_table_row();
1.660     raeburn  11516:             }
1.987     raeburn  11517:             $numpathchg ++;
                   11518:             $chgcount ++;
1.660     raeburn  11519:         }
                   11520:     }
1.1127    raeburn  11521:     if (($counter) || ($numunused)) {
1.987     raeburn  11522:         if ($numpathchg) {
                   11523:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11524:                        $numpathchg.'" />'."\n";
                   11525:         }
                   11526:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11527:             ($actionurl eq '/adm/imsimport')) {
                   11528:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11529:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11530:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11531:         } elsif ($actionurl eq '/adm/dependencies') {
                   11532:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11533:         }
1.1123    raeburn  11534:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11535:     } elsif ($numpathchg) {
                   11536:         my %pathchange = ();
                   11537:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11538:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11539:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11540:         }
1.987     raeburn  11541:     }
1.1071    raeburn  11542:     return ($output,$counter,$numpathchg);
1.987     raeburn  11543: }
                   11544: 
1.1147    raeburn  11545: =pod
                   11546: 
                   11547: =item * clean_path($name)
                   11548: 
                   11549: Performs clean-up of directories, subdirectories and filename in an
                   11550: embedded object, referenced in an HTML file which is being uploaded
                   11551: to a course or portfolio, where 
                   11552: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11553: checked.
                   11554: 
                   11555: Clean-up is similar to replacements in lonnet::clean_filename()
                   11556: except each / between sub-directory and next level is preserved.
                   11557: 
                   11558: =cut
                   11559: 
                   11560: sub clean_path {
                   11561:     my ($embed_file) = @_;
                   11562:     $embed_file =~s{^/+}{};
                   11563:     my @contents;
                   11564:     if ($embed_file =~ m{/}) {
                   11565:         @contents = split(/\//,$embed_file);
                   11566:     } else {
                   11567:         @contents = ($embed_file);
                   11568:     }
                   11569:     my $lastidx = scalar(@contents)-1;
                   11570:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11571:         $contents[$i]=~s{\\}{/}g;
                   11572:         $contents[$i]=~s/\s+/\_/g;
                   11573:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11574:         if ($i == $lastidx) {
                   11575:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11576:         }
                   11577:     }
                   11578:     if ($lastidx > 0) {
                   11579:         return join('/',@contents);
                   11580:     } else {
                   11581:         return $contents[0];
                   11582:     }
                   11583: }
                   11584: 
1.987     raeburn  11585: sub embedded_file_element {
1.1071    raeburn  11586:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11587:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11588:                    (ref($codebase) eq 'HASH'));
                   11589:     my $output;
1.1071    raeburn  11590:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11591:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11592:     }
                   11593:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11594:                &escape($embed_file).'" />';
                   11595:     unless (($context eq 'upload_embedded') && 
                   11596:             ($mapping->{$embed_file} eq $embed_file)) {
                   11597:         $output .='
                   11598:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11599:     }
                   11600:     my $attrib;
                   11601:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11602:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11603:     }
                   11604:     $output .=
                   11605:         "\n\t\t".
                   11606:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11607:         $attrib.'" />';
                   11608:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11609:         $output .=
                   11610:             "\n\t\t".
                   11611:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11612:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11613:     }
1.987     raeburn  11614:     return $output;
1.660     raeburn  11615: }
                   11616: 
1.1071    raeburn  11617: sub get_dependency_details {
                   11618:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11619:     my ($size,$mtime,$showsize,$showmtime);
                   11620:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11621:         if ($embed_file =~ m{/}) {
                   11622:             my ($path,$fname) = split(/\//,$embed_file);
                   11623:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11624:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11625:             }
                   11626:         } else {
                   11627:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11628:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11629:             }
                   11630:         }
                   11631:         $showsize = $size/1024.0;
                   11632:         $showsize = sprintf("%.1f",$showsize);
                   11633:         if ($mtime > 0) {
                   11634:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11635:         }
                   11636:     }
                   11637:     return ($showsize,$showmtime);
                   11638: }
                   11639: 
                   11640: sub ask_embedded_js {
                   11641:     return <<"END";
                   11642: <script type="text/javascript"">
                   11643: // <![CDATA[
                   11644: function toggleBrowse(counter) {
                   11645:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11646:     var fileid = document.getElementById('embedded_item_'+counter);
                   11647:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11648:     if (chkboxid.checked == true) {
                   11649:         uploaddivid.style.display='block';
                   11650:     } else {
                   11651:         uploaddivid.style.display='none';
                   11652:         fileid.value = '';
                   11653:     }
                   11654: }
                   11655: // ]]>
                   11656: </script>
                   11657: 
                   11658: END
                   11659: }
                   11660: 
1.661     raeburn  11661: sub upload_embedded {
                   11662:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11663:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11664:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11665:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11666:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11667:         my $orig_uploaded_filename =
                   11668:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11669:         foreach my $type ('orig','ref','attrib','codebase') {
                   11670:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11671:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11672:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11673:             }
                   11674:         }
1.661     raeburn  11675:         my ($path,$fname) =
                   11676:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11677:         # no path, whole string is fname
                   11678:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11679:         $fname = &Apache::lonnet::clean_filename($fname);
                   11680:         # See if there is anything left
                   11681:         next if ($fname eq '');
                   11682: 
                   11683:         # Check if file already exists as a file or directory.
                   11684:         my ($state,$msg);
                   11685:         if ($context eq 'portfolio') {
                   11686:             my $port_path = $dirpath;
                   11687:             if ($group ne '') {
                   11688:                 $port_path = "groups/$group/$port_path";
                   11689:             }
1.987     raeburn  11690:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11691:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11692:                                               $dir_root,$port_path,$disk_quota,
                   11693:                                               $current_disk_usage,$uname,$udom);
                   11694:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11695:                 || $state eq 'file_locked') {
1.661     raeburn  11696:                 $output .= $msg;
                   11697:                 next;
                   11698:             }
                   11699:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11700:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11701:             if ($state eq 'exists') {
                   11702:                 $output .= $msg;
                   11703:                 next;
                   11704:             }
                   11705:         }
                   11706:         # Check if extension is valid
                   11707:         if (($fname =~ /\.(\w+)$/) &&
                   11708:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   11709:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11710:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11711:             next;
                   11712:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11713:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11714:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11715:             next;
                   11716:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   11717:             $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  11718:             next;
                   11719:         }
                   11720:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  11721:         my $subdir = $path;
                   11722:         $subdir =~ s{/+$}{};
1.661     raeburn  11723:         if ($context eq 'portfolio') {
1.984     raeburn  11724:             my $result;
                   11725:             if ($state eq 'existingfile') {
                   11726:                 $result=
                   11727:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  11728:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11729:             } else {
1.984     raeburn  11730:                 $result=
                   11731:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11732:                                                     $dirpath.
1.1123    raeburn  11733:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11734:                 if ($result !~ m|^/uploaded/|) {
                   11735:                     $output .= '<span class="LC_error">'
                   11736:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11737:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11738:                                .'</span><br />';
                   11739:                     next;
                   11740:                 } else {
1.987     raeburn  11741:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11742:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11743:                 }
1.661     raeburn  11744:             }
1.1123    raeburn  11745:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  11746:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11747:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11748:             my $result =
1.1126    raeburn  11749:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11750:             if ($result !~ m|^/uploaded/|) {
                   11751:                 $output .= '<span class="LC_error">'
                   11752:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11753:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11754:                            .'</span><br />';
                   11755:                     next;
                   11756:             } else {
                   11757:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11758:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11759:                 if ($context eq 'syllabus') {
                   11760:                     &Apache::lonnet::make_public_indefinitely($result);
                   11761:                 }
1.987     raeburn  11762:             }
1.661     raeburn  11763:         } else {
                   11764: # Save the file
                   11765:             my $target = $env{'form.embedded_item_'.$i};
                   11766:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11767:             my $dest = $fullpath.$fname;
                   11768:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11769:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11770:             my $count;
                   11771:             my $filepath = $dir_root;
1.1027    raeburn  11772:             foreach my $subdir (@parts) {
                   11773:                 $filepath .= "/$subdir";
                   11774:                 if (!-e $filepath) {
1.661     raeburn  11775:                     mkdir($filepath,0770);
                   11776:                 }
                   11777:             }
                   11778:             my $fh;
                   11779:             if (!open($fh,'>'.$dest)) {
                   11780:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11781:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11782:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11783:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11784:                            '</span><br />';
                   11785:             } else {
                   11786:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11787:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11788:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11789:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11790:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11791:                               '</span><br />';
                   11792:                 } else {
1.987     raeburn  11793:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11794:                                $url.'</span>').'<br />';
                   11795:                     unless ($context eq 'testbank') {
                   11796:                         $footer .= &mt('View embedded file: [_1]',
                   11797:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11798:                     }
                   11799:                 }
                   11800:                 close($fh);
                   11801:             }
                   11802:         }
                   11803:         if ($env{'form.embedded_ref_'.$i}) {
                   11804:             $pathchange{$i} = 1;
                   11805:         }
                   11806:     }
                   11807:     if ($output) {
                   11808:         $output = '<p>'.$output.'</p>';
                   11809:     }
                   11810:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11811:     $returnflag = 'ok';
1.1071    raeburn  11812:     my $numpathchgs = scalar(keys(%pathchange));
                   11813:     if ($numpathchgs > 0) {
1.987     raeburn  11814:         if ($context eq 'portfolio') {
                   11815:             $output .= '<p>'.&mt('or').'</p>';
                   11816:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11817:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11818:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11819:             $returnflag = 'modify_orightml';
                   11820:         }
                   11821:     }
1.1071    raeburn  11822:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11823: }
                   11824: 
                   11825: sub modify_html_form {
                   11826:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11827:     my $end = 0;
                   11828:     my $modifyform;
                   11829:     if ($context eq 'upload_embedded') {
                   11830:         return unless (ref($pathchange) eq 'HASH');
                   11831:         if ($env{'form.number_embedded_items'}) {
                   11832:             $end += $env{'form.number_embedded_items'};
                   11833:         }
                   11834:         if ($env{'form.number_pathchange_items'}) {
                   11835:             $end += $env{'form.number_pathchange_items'};
                   11836:         }
                   11837:         if ($end) {
                   11838:             for (my $i=0; $i<$end; $i++) {
                   11839:                 if ($i < $env{'form.number_embedded_items'}) {
                   11840:                     next unless($pathchange->{$i});
                   11841:                 }
                   11842:                 $modifyform .=
                   11843:                     &start_data_table_row().
                   11844:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11845:                     'checked="checked" /></td>'.
                   11846:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11847:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11848:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11849:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11850:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11851:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11852:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11853:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11854:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11855:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11856:                     &end_data_table_row();
1.1071    raeburn  11857:             }
1.987     raeburn  11858:         }
                   11859:     } else {
                   11860:         $modifyform = $pathchgtable;
                   11861:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11862:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11863:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11864:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11865:         }
                   11866:     }
                   11867:     if ($modifyform) {
1.1071    raeburn  11868:         if ($actionurl eq '/adm/dependencies') {
                   11869:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11870:         }
1.987     raeburn  11871:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11872:                '<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".
                   11873:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11874:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11875:                '</ol></p>'."\n".'<p>'.
                   11876:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11877:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11878:                &start_data_table()."\n".
                   11879:                &start_data_table_header_row().
                   11880:                '<th>'.&mt('Change?').'</th>'.
                   11881:                '<th>'.&mt('Current reference').'</th>'.
                   11882:                '<th>'.&mt('Required reference').'</th>'.
                   11883:                &end_data_table_header_row()."\n".
                   11884:                $modifyform.
                   11885:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11886:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11887:                '</form>'."\n";
                   11888:     }
                   11889:     return;
                   11890: }
                   11891: 
                   11892: sub modify_html_refs {
1.1123    raeburn  11893:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11894:     my $container;
                   11895:     if ($context eq 'portfolio') {
                   11896:         $container = $env{'form.container'};
                   11897:     } elsif ($context eq 'coursedoc') {
                   11898:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11899:     } elsif ($context eq 'manage_dependencies') {
                   11900:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11901:         $container = "/$container";
1.1123    raeburn  11902:     } elsif ($context eq 'syllabus') {
                   11903:         $container = $url;
1.987     raeburn  11904:     } else {
1.1027    raeburn  11905:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11906:     }
                   11907:     my (%allfiles,%codebase,$output,$content);
                   11908:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  11909:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  11910:         if (wantarray) {
                   11911:             return ('',0,0); 
                   11912:         } else {
                   11913:             return;
                   11914:         }
                   11915:     }
                   11916:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11917:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11918:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11919:             if (wantarray) {
                   11920:                 return ('',0,0);
                   11921:             } else {
                   11922:                 return;
                   11923:             }
                   11924:         } 
1.987     raeburn  11925:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11926:         if ($content eq '-1') {
                   11927:             if (wantarray) {
                   11928:                 return ('',0,0);
                   11929:             } else {
                   11930:                 return;
                   11931:             }
                   11932:         }
1.987     raeburn  11933:     } else {
1.1071    raeburn  11934:         unless ($container =~ /^\Q$dir_root\E/) {
                   11935:             if (wantarray) {
                   11936:                 return ('',0,0);
                   11937:             } else {
                   11938:                 return;
                   11939:             }
                   11940:         } 
1.987     raeburn  11941:         if (open(my $fh,"<$container")) {
                   11942:             $content = join('', <$fh>);
                   11943:             close($fh);
                   11944:         } else {
1.1071    raeburn  11945:             if (wantarray) {
                   11946:                 return ('',0,0);
                   11947:             } else {
                   11948:                 return;
                   11949:             }
1.987     raeburn  11950:         }
                   11951:     }
                   11952:     my ($count,$codebasecount) = (0,0);
                   11953:     my $mm = new File::MMagic;
                   11954:     my $mime_type = $mm->checktype_contents($content);
                   11955:     if ($mime_type eq 'text/html') {
                   11956:         my $parse_result = 
                   11957:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11958:                                                     \%codebase,\$content);
                   11959:         if ($parse_result eq 'ok') {
                   11960:             foreach my $i (@changes) {
                   11961:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11962:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11963:                 if ($allfiles{$ref}) {
                   11964:                     my $newname =  $orig;
                   11965:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11966:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11967:                     if ($attrib_regexp =~ /:/) {
                   11968:                         $attrib_regexp =~ s/\:/|/g;
                   11969:                     }
                   11970:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11971:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11972:                         $count += $numchg;
1.1123    raeburn  11973:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  11974:                         delete($allfiles{$ref});
1.987     raeburn  11975:                     }
                   11976:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11977:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11978:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11979:                         $codebasecount ++;
                   11980:                     }
                   11981:                 }
                   11982:             }
1.1123    raeburn  11983:             my $skiprewrites;
1.987     raeburn  11984:             if ($count || $codebasecount) {
                   11985:                 my $saveresult;
1.1071    raeburn  11986:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11987:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11988:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11989:                     if ($url eq $container) {
                   11990:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11991:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11992:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11993:                                             $fname.'</span>').'</p>';
1.987     raeburn  11994:                     } else {
                   11995:                          $output = '<p class="LC_error">'.
                   11996:                                    &mt('Error: update failed for: [_1].',
                   11997:                                    '<span class="LC_filename">'.
                   11998:                                    $container.'</span>').'</p>';
                   11999:                     }
1.1123    raeburn  12000:                     if ($context eq 'syllabus') {
                   12001:                         unless ($saveresult eq 'ok') {
                   12002:                             $skiprewrites = 1;
                   12003:                         }
                   12004:                     }
1.987     raeburn  12005:                 } else {
                   12006:                     if (open(my $fh,">$container")) {
                   12007:                         print $fh $content;
                   12008:                         close($fh);
                   12009:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12010:                                   $count,'<span class="LC_filename">'.
                   12011:                                   $container.'</span>').'</p>';
1.661     raeburn  12012:                     } else {
1.987     raeburn  12013:                          $output = '<p class="LC_error">'.
                   12014:                                    &mt('Error: could not update [_1].',
                   12015:                                    '<span class="LC_filename">'.
                   12016:                                    $container.'</span>').'</p>';
1.661     raeburn  12017:                     }
                   12018:                 }
                   12019:             }
1.1123    raeburn  12020:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12021:                 my ($actionurl,$state);
                   12022:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12023:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12024:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12025:                                               \%codebase,
                   12026:                                               {'context' => 'rewrites',
                   12027:                                                'ignore_remote_references' => 1,});
                   12028:                 if (ref($mapping) eq 'HASH') {
                   12029:                     my $rewrites = 0;
                   12030:                     foreach my $key (keys(%{$mapping})) {
                   12031:                         next if ($key =~ m{^https?://});
                   12032:                         my $ref = $mapping->{$key};
                   12033:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12034:                         my $attrib;
                   12035:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12036:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12037:                         }
                   12038:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12039:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12040:                             $rewrites += $numchg;
                   12041:                         }
                   12042:                     }
                   12043:                     if ($rewrites) {
                   12044:                         my $saveresult; 
                   12045:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12046:                         if ($url eq $container) {
                   12047:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12048:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12049:                                             $count,'<span class="LC_filename">'.
                   12050:                                             $fname.'</span>').'</p>';
                   12051:                         } else {
                   12052:                             $output .= '<p class="LC_error">'.
                   12053:                                        &mt('Error: could not update links in [_1].',
                   12054:                                        '<span class="LC_filename">'.
                   12055:                                        $container.'</span>').'</p>';
                   12056: 
                   12057:                         }
                   12058:                     }
                   12059:                 }
                   12060:             }
1.987     raeburn  12061:         } else {
                   12062:             &logthis('Failed to parse '.$container.
                   12063:                      ' to modify references: '.$parse_result);
1.661     raeburn  12064:         }
                   12065:     }
1.1071    raeburn  12066:     if (wantarray) {
                   12067:         return ($output,$count,$codebasecount);
                   12068:     } else {
                   12069:         return $output;
                   12070:     }
1.661     raeburn  12071: }
                   12072: 
                   12073: sub check_for_existing {
                   12074:     my ($path,$fname,$element) = @_;
                   12075:     my ($state,$msg);
                   12076:     if (-d $path.'/'.$fname) {
                   12077:         $state = 'exists';
                   12078:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12079:     } elsif (-e $path.'/'.$fname) {
                   12080:         $state = 'exists';
                   12081:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12082:     }
                   12083:     if ($state eq 'exists') {
                   12084:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12085:     }
                   12086:     return ($state,$msg);
                   12087: }
                   12088: 
                   12089: sub check_for_upload {
                   12090:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12091:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12092:     my $filesize = length($env{'form.'.$element});
                   12093:     if (!$filesize) {
                   12094:         my $msg = '<span class="LC_error">'.
                   12095:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12096:                       '<span class="LC_filename">'.$fname.'</span>',
                   12097:                       $filesize).'<br />'.
1.1007    raeburn  12098:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12099:                   '</span>';
                   12100:         return ('zero_bytes',$msg);
                   12101:     }
                   12102:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12103:     my $getpropath = 1;
1.1021    raeburn  12104:     my ($dirlistref,$listerror) =
                   12105:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12106:     my $found_file = 0;
                   12107:     my $locked_file = 0;
1.991     raeburn  12108:     my @lockers;
                   12109:     my $navmap;
                   12110:     if ($env{'request.course.id'}) {
                   12111:         $navmap = Apache::lonnavmaps::navmap->new();
                   12112:     }
1.1021    raeburn  12113:     if (ref($dirlistref) eq 'ARRAY') {
                   12114:         foreach my $line (@{$dirlistref}) {
                   12115:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12116:             if ($file_name eq $fname){
                   12117:                 $file_name = $path.$file_name;
                   12118:                 if ($group ne '') {
                   12119:                     $file_name = $group.$file_name;
                   12120:                 }
                   12121:                 $found_file = 1;
                   12122:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12123:                     foreach my $lock (@lockers) {
                   12124:                         if (ref($lock) eq 'ARRAY') {
                   12125:                             my ($symb,$crsid) = @{$lock};
                   12126:                             if ($crsid eq $env{'request.course.id'}) {
                   12127:                                 if (ref($navmap)) {
                   12128:                                     my $res = $navmap->getBySymb($symb);
                   12129:                                     foreach my $part (@{$res->parts()}) { 
                   12130:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12131:                                         unless (($slot_status == $res->RESERVED) ||
                   12132:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12133:                                             $locked_file = 1;
                   12134:                                         }
1.991     raeburn  12135:                                     }
1.1021    raeburn  12136:                                 } else {
                   12137:                                     $locked_file = 1;
1.991     raeburn  12138:                                 }
                   12139:                             } else {
                   12140:                                 $locked_file = 1;
                   12141:                             }
                   12142:                         }
1.1021    raeburn  12143:                    }
                   12144:                 } else {
                   12145:                     my @info = split(/\&/,$rest);
                   12146:                     my $currsize = $info[6]/1000;
                   12147:                     if ($currsize < $filesize) {
                   12148:                         my $extra = $filesize - $currsize;
                   12149:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12150:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12151:                                       &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   12152:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12153:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12154:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12155:                             return ('will_exceed_quota',$msg);
                   12156:                         }
1.984     raeburn  12157:                     }
                   12158:                 }
1.661     raeburn  12159:             }
                   12160:         }
                   12161:     }
                   12162:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12163:         my $msg = '<p class="LC_warning">'.
                   12164:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12165:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12166:         return ('will_exceed_quota',$msg);
                   12167:     } elsif ($found_file) {
                   12168:         if ($locked_file) {
1.1179    bisitz   12169:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12170:             $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   12171:             $msg .= '</p>';
1.661     raeburn  12172:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12173:             return ('file_locked',$msg);
                   12174:         } else {
1.1179    bisitz   12175:             my $msg = '<p class="LC_error">';
1.984     raeburn  12176:             $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   12177:             $msg .= '</p>';
1.984     raeburn  12178:             return ('existingfile',$msg);
1.661     raeburn  12179:         }
                   12180:     }
                   12181: }
                   12182: 
1.987     raeburn  12183: sub check_for_traversal {
                   12184:     my ($path,$url,$toplevel) = @_;
                   12185:     my @parts=split(/\//,$path);
                   12186:     my $cleanpath;
                   12187:     my $fullpath = $url;
                   12188:     for (my $i=0;$i<@parts;$i++) {
                   12189:         next if ($parts[$i] eq '.');
                   12190:         if ($parts[$i] eq '..') {
                   12191:             $fullpath =~ s{([^/]+/)$}{};
                   12192:         } else {
                   12193:             $fullpath .= $parts[$i].'/';
                   12194:         }
                   12195:     }
                   12196:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12197:         $cleanpath = $1;
                   12198:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12199:         my $curr_toprel = $1;
                   12200:         my @parts = split(/\//,$curr_toprel);
                   12201:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12202:         my @urlparts = split(/\//,$url_toprel);
                   12203:         my $doubledots;
                   12204:         my $startdiff = -1;
                   12205:         for (my $i=0; $i<@urlparts; $i++) {
                   12206:             if ($startdiff == -1) {
                   12207:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12208:                     $startdiff = $i;
                   12209:                     $doubledots .= '../';
                   12210:                 }
                   12211:             } else {
                   12212:                 $doubledots .= '../';
                   12213:             }
                   12214:         }
                   12215:         if ($startdiff > -1) {
                   12216:             $cleanpath = $doubledots;
                   12217:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12218:                 $cleanpath .= $parts[$i].'/';
                   12219:             }
                   12220:         }
                   12221:     }
                   12222:     $cleanpath =~ s{(/)$}{};
                   12223:     return $cleanpath;
                   12224: }
1.31      albertel 12225: 
1.1053    raeburn  12226: sub is_archive_file {
                   12227:     my ($mimetype) = @_;
                   12228:     if (($mimetype eq 'application/octet-stream') ||
                   12229:         ($mimetype eq 'application/x-stuffit') ||
                   12230:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12231:         return 1;
                   12232:     }
                   12233:     return;
                   12234: }
                   12235: 
                   12236: sub decompress_form {
1.1065    raeburn  12237:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12238:     my %lt = &Apache::lonlocal::texthash (
                   12239:         this => 'This file is an archive file.',
1.1067    raeburn  12240:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12241:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12242:         youm => 'You may wish to extract its contents.',
                   12243:         extr => 'Extract contents',
1.1067    raeburn  12244:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12245:         proa => 'Process automatically?',
1.1053    raeburn  12246:         yes  => 'Yes',
                   12247:         no   => 'No',
1.1067    raeburn  12248:         fold => 'Title for folder containing movie',
                   12249:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12250:     );
1.1065    raeburn  12251:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12252:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12253:     my $info = &list_archive_contents($fileloc,\@paths);
                   12254:     if (@paths) {
                   12255:         foreach my $path (@paths) {
                   12256:             $path =~ s{^/}{};
1.1067    raeburn  12257:             if ($path =~ m{^([^/]+)/$}) {
                   12258:                 $topdir = $1;
                   12259:             }
1.1065    raeburn  12260:             if ($path =~ m{^([^/]+)/}) {
                   12261:                 $toplevel{$1} = $path;
                   12262:             } else {
                   12263:                 $toplevel{$path} = $path;
                   12264:             }
                   12265:         }
                   12266:     }
1.1067    raeburn  12267:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12268:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12269:                         "$topdir/media/",
                   12270:                         "$topdir/media/$topdir.mp4",
                   12271:                         "$topdir/media/FirstFrame.png",
                   12272:                         "$topdir/media/player.swf",
                   12273:                         "$topdir/media/swfobject.js",
                   12274:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12275:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12276:                          "$topdir/$topdir.mp4",
                   12277:                          "$topdir/$topdir\_config.xml",
                   12278:                          "$topdir/$topdir\_controller.swf",
                   12279:                          "$topdir/$topdir\_embed.css",
                   12280:                          "$topdir/$topdir\_First_Frame.png",
                   12281:                          "$topdir/$topdir\_player.html",
                   12282:                          "$topdir/$topdir\_Thumbnails.png",
                   12283:                          "$topdir/playerProductInstall.swf",
                   12284:                          "$topdir/scripts/",
                   12285:                          "$topdir/scripts/config_xml.js",
                   12286:                          "$topdir/scripts/handlebars.js",
                   12287:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12288:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12289:                          "$topdir/scripts/modernizr.js",
                   12290:                          "$topdir/scripts/player-min.js",
                   12291:                          "$topdir/scripts/swfobject.js",
                   12292:                          "$topdir/skins/",
                   12293:                          "$topdir/skins/configuration_express.xml",
                   12294:                          "$topdir/skins/express_show/",
                   12295:                          "$topdir/skins/express_show/player-min.css",
                   12296:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12297:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12298:                          "$topdir/$topdir.mp4",
                   12299:                          "$topdir/$topdir\_config.xml",
                   12300:                          "$topdir/$topdir\_controller.swf",
                   12301:                          "$topdir/$topdir\_embed.css",
                   12302:                          "$topdir/$topdir\_First_Frame.png",
                   12303:                          "$topdir/$topdir\_player.html",
                   12304:                          "$topdir/$topdir\_Thumbnails.png",
                   12305:                          "$topdir/playerProductInstall.swf",
                   12306:                          "$topdir/scripts/",
                   12307:                          "$topdir/scripts/config_xml.js",
                   12308:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12309:                          "$topdir/skins/",
                   12310:                          "$topdir/skins/configuration_express.xml",
                   12311:                          "$topdir/skins/express_show/",
                   12312:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12313:                          "$topdir/skins/express_show/spritesheet.png",
                   12314:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12315:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12316:         if (@diffs == 0) {
1.1164    raeburn  12317:             $is_camtasia = 6;
                   12318:         } else {
1.1197    raeburn  12319:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12320:             if (@diffs == 0) {
                   12321:                 $is_camtasia = 8;
1.1197    raeburn  12322:             } else {
                   12323:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12324:                 if (@diffs == 0) {
                   12325:                     $is_camtasia = 8;
                   12326:                 }
1.1164    raeburn  12327:             }
1.1067    raeburn  12328:         }
                   12329:     }
                   12330:     my $output;
                   12331:     if ($is_camtasia) {
                   12332:         $output = <<"ENDCAM";
                   12333: <script type="text/javascript" language="Javascript">
                   12334: // <![CDATA[
                   12335: 
                   12336: function camtasiaToggle() {
                   12337:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12338:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  12339:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12340:                 document.getElementById('camtasia_titles').style.display='block';
                   12341:             } else {
                   12342:                 document.getElementById('camtasia_titles').style.display='none';
                   12343:             }
                   12344:         }
                   12345:     }
                   12346:     return;
                   12347: }
                   12348: 
                   12349: // ]]>
                   12350: </script>
                   12351: <p>$lt{'camt'}</p>
                   12352: ENDCAM
1.1065    raeburn  12353:     } else {
1.1067    raeburn  12354:         $output = '<p>'.$lt{'this'};
                   12355:         if ($info eq '') {
                   12356:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12357:         } else {
                   12358:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12359:                        '<div><pre>'.$info.'</pre></div>';
                   12360:         }
1.1065    raeburn  12361:     }
1.1067    raeburn  12362:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12363:     my $duplicates;
                   12364:     my $num = 0;
                   12365:     if (ref($dirlist) eq 'ARRAY') {
                   12366:         foreach my $item (@{$dirlist}) {
                   12367:             if (ref($item) eq 'ARRAY') {
                   12368:                 if (exists($toplevel{$item->[0]})) {
                   12369:                     $duplicates .= 
                   12370:                         &start_data_table_row().
                   12371:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12372:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12373:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12374:                         'value="1" />'.&mt('Yes').'</label>'.
                   12375:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12376:                         '<td>'.$item->[0].'</td>';
                   12377:                     if ($item->[2]) {
                   12378:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12379:                     } else {
                   12380:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12381:                     }
                   12382:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12383:                                    '<td>'.
                   12384:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12385:                                    '</td>'.
                   12386:                                    &end_data_table_row();
                   12387:                     $num ++;
                   12388:                 }
                   12389:             }
                   12390:         }
                   12391:     }
                   12392:     my $itemcount;
                   12393:     if (@paths > 0) {
                   12394:         $itemcount = scalar(@paths);
                   12395:     } else {
                   12396:         $itemcount = 1;
                   12397:     }
1.1067    raeburn  12398:     if ($is_camtasia) {
                   12399:         $output .= $lt{'auto'}.'<br />'.
                   12400:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  12401:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12402:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12403:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12404:                    $lt{'no'}.'</label></span><br />'.
                   12405:                    '<div id="camtasia_titles" style="display:block">'.
                   12406:                    &Apache::lonhtmlcommon::start_pick_box().
                   12407:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12408:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12409:                    &Apache::lonhtmlcommon::row_closure().
                   12410:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12411:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12412:                    &Apache::lonhtmlcommon::row_closure(1).
                   12413:                    &Apache::lonhtmlcommon::end_pick_box().
                   12414:                    '</div>';
                   12415:     }
1.1065    raeburn  12416:     $output .= 
                   12417:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12418:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12419:         "\n";
1.1065    raeburn  12420:     if ($duplicates ne '') {
                   12421:         $output .= '<p><span class="LC_warning">'.
                   12422:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12423:                    &start_data_table().
                   12424:                    &start_data_table_header_row().
                   12425:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12426:                    '<th>'.&mt('Name').'</th>'.
                   12427:                    '<th>'.&mt('Type').'</th>'.
                   12428:                    '<th>'.&mt('Size').'</th>'.
                   12429:                    '<th>'.&mt('Last modified').'</th>'.
                   12430:                    &end_data_table_header_row().
                   12431:                    $duplicates.
                   12432:                    &end_data_table().
                   12433:                    '</p>';
                   12434:     }
1.1067    raeburn  12435:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12436:     if (ref($hiddenelements) eq 'HASH') {
                   12437:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12438:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12439:         }
                   12440:     }
                   12441:     $output .= <<"END";
1.1067    raeburn  12442: <br />
1.1053    raeburn  12443: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12444: </form>
                   12445: $noextract
                   12446: END
                   12447:     return $output;
                   12448: }
                   12449: 
1.1065    raeburn  12450: sub decompression_utility {
                   12451:     my ($program) = @_;
                   12452:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12453:     my $location;
                   12454:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12455:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12456:                          '/usr/sbin/') {
                   12457:             if (-x $dir.$program) {
                   12458:                 $location = $dir.$program;
                   12459:                 last;
                   12460:             }
                   12461:         }
                   12462:     }
                   12463:     return $location;
                   12464: }
                   12465: 
                   12466: sub list_archive_contents {
                   12467:     my ($file,$pathsref) = @_;
                   12468:     my (@cmd,$output);
                   12469:     my $needsregexp;
                   12470:     if ($file =~ /\.zip$/) {
                   12471:         @cmd = (&decompression_utility('unzip'),"-l");
                   12472:         $needsregexp = 1;
                   12473:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12474:              ($file =~ /\.tgz$/)) {
                   12475:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12476:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12477:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12478:     } elsif ($file =~ m|\.tar$|) {
                   12479:         @cmd = (&decompression_utility('tar'),"-tf");
                   12480:     }
                   12481:     if (@cmd) {
                   12482:         undef($!);
                   12483:         undef($@);
                   12484:         if (open(my $fh,"-|", @cmd, $file)) {
                   12485:             while (my $line = <$fh>) {
                   12486:                 $output .= $line;
                   12487:                 chomp($line);
                   12488:                 my $item;
                   12489:                 if ($needsregexp) {
                   12490:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12491:                 } else {
                   12492:                     $item = $line;
                   12493:                 }
                   12494:                 if ($item ne '') {
                   12495:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12496:                         push(@{$pathsref},$item);
                   12497:                     } 
                   12498:                 }
                   12499:             }
                   12500:             close($fh);
                   12501:         }
                   12502:     }
                   12503:     return $output;
                   12504: }
                   12505: 
1.1053    raeburn  12506: sub decompress_uploaded_file {
                   12507:     my ($file,$dir) = @_;
                   12508:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12509:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12510:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12511:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12512:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12513:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12514:     my $decompressed = $env{'cgi.decompressed'};
                   12515:     &Apache::lonnet::delenv('cgi.file');
                   12516:     &Apache::lonnet::delenv('cgi.dir');
                   12517:     &Apache::lonnet::delenv('cgi.decompressed');
                   12518:     return ($decompressed,$result);
                   12519: }
                   12520: 
1.1055    raeburn  12521: sub process_decompression {
                   12522:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   12523:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12524:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12525:         $error = &mt('Filename not a supported archive file type.').
                   12526:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12527:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12528:     } else {
                   12529:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12530:         if ($docuhome eq 'no_host') {
                   12531:             $error = &mt('Could not determine home server for course.');
                   12532:         } else {
                   12533:             my @ids=&Apache::lonnet::current_machine_ids();
                   12534:             my $currdir = "$dir_root/$destination";
                   12535:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12536:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12537:                        "$dir_root/$destination";
                   12538:             } else {
                   12539:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12540:                        "$dir_root/$docudom/$docuname/$destination";
                   12541:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12542:                     $error = &mt('Archive file not found.');
                   12543:                 }
                   12544:             }
1.1065    raeburn  12545:             my (@to_overwrite,@to_skip);
                   12546:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12547:                 my $total = $env{'form.archive_overwrite_total'};
                   12548:                 for (my $i=0; $i<$total; $i++) {
                   12549:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12550:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12551:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12552:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12553:                     }
                   12554:                 }
                   12555:             }
                   12556:             my $numskip = scalar(@to_skip);
                   12557:             if (($numskip > 0) && 
                   12558:                 ($numskip == $env{'form.archive_itemcount'})) {
                   12559:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12560:             } elsif ($dir eq '') {
1.1055    raeburn  12561:                 $error = &mt('Directory containing archive file unavailable.');
                   12562:             } elsif (!$error) {
1.1065    raeburn  12563:                 my ($decompressed,$display);
                   12564:                 if ($numskip > 0) {
                   12565:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12566:                     mkdir("$dir/$tempdir",0755);
                   12567:                     system("mv $dir/$file $dir/$tempdir/$file");
                   12568:                     ($decompressed,$display) = 
                   12569:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   12570:                     foreach my $item (@to_skip) {
                   12571:                         if (($item ne '') && ($item !~ /\.\./)) {
                   12572:                             if (-f "$dir/$tempdir/$item") { 
                   12573:                                 unlink("$dir/$tempdir/$item");
                   12574:                             } elsif (-d "$dir/$tempdir/$item") {
                   12575:                                 system("rm -rf $dir/$tempdir/$item");
                   12576:                             }
                   12577:                         }
                   12578:                     }
                   12579:                     system("mv $dir/$tempdir/* $dir");
                   12580:                     rmdir("$dir/$tempdir");   
                   12581:                 } else {
                   12582:                     ($decompressed,$display) = 
                   12583:                         &decompress_uploaded_file($file,$dir);
                   12584:                 }
1.1055    raeburn  12585:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12586:                     $output = '<p class="LC_info">'.
                   12587:                               &mt('Files extracted successfully from archive.').
                   12588:                               '</p>'."\n";
1.1055    raeburn  12589:                     my ($warning,$result,@contents);
                   12590:                     my ($newdirlistref,$newlisterror) =
                   12591:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12592:                                                  $docuname,1);
                   12593:                     my (%is_dir,%changes,@newitems);
                   12594:                     my $dirptr = 16384;
1.1065    raeburn  12595:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12596:                         foreach my $dir_line (@{$newdirlistref}) {
                   12597:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  12598:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   12599:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  12600:                                 push(@newitems,$item);
                   12601:                                 if ($dirptr&$testdir) {
                   12602:                                     $is_dir{$item} = 1;
                   12603:                                 }
                   12604:                                 $changes{$item} = 1;
                   12605:                             }
                   12606:                         }
                   12607:                     }
                   12608:                     if (keys(%changes) > 0) {
                   12609:                         foreach my $item (sort(@newitems)) {
                   12610:                             if ($changes{$item}) {
                   12611:                                 push(@contents,$item);
                   12612:                             }
                   12613:                         }
                   12614:                     }
                   12615:                     if (@contents > 0) {
1.1067    raeburn  12616:                         my $wantform;
                   12617:                         unless ($env{'form.autoextract_camtasia'}) {
                   12618:                             $wantform = 1;
                   12619:                         }
1.1056    raeburn  12620:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12621:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12622:                                                                 $currdir,\%is_dir,
                   12623:                                                                 \%children,\%parent,
1.1056    raeburn  12624:                                                                 \@contents,\%dirorder,
                   12625:                                                                 \%titles,$wantform);
1.1055    raeburn  12626:                         if ($datatable ne '') {
                   12627:                             $output .= &archive_options_form('decompressed',$datatable,
                   12628:                                                              $count,$hiddenelem);
1.1065    raeburn  12629:                             my $startcount = 6;
1.1055    raeburn  12630:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12631:                                                            \%titles,\%children);
1.1055    raeburn  12632:                         }
1.1067    raeburn  12633:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  12634:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12635:                             my %displayed;
                   12636:                             my $total = 1;
                   12637:                             $env{'form.archive_directory'} = [];
                   12638:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12639:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12640:                                 $path =~ s{/$}{};
                   12641:                                 my $item;
                   12642:                                 if ($path ne '') {
                   12643:                                     $item = "$path/$titles{$i}";
                   12644:                                 } else {
                   12645:                                     $item = $titles{$i};
                   12646:                                 }
                   12647:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12648:                                 if ($item eq $contents[0]) {
                   12649:                                     push(@{$env{'form.archive_directory'}},$i);
                   12650:                                     $env{'form.archive_'.$i} = 'display';
                   12651:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12652:                                     $displayed{'folder'} = $i;
1.1164    raeburn  12653:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12654:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  12655:                                     $env{'form.archive_'.$i} = 'display';
                   12656:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12657:                                     $displayed{'web'} = $i;
                   12658:                                 } else {
1.1164    raeburn  12659:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12660:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12661:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12662:                                         push(@{$env{'form.archive_directory'}},$i);
                   12663:                                     }
                   12664:                                     $env{'form.archive_'.$i} = 'dependency';
                   12665:                                 }
                   12666:                                 $total ++;
                   12667:                             }
                   12668:                             for (my $i=1; $i<$total; $i++) {
                   12669:                                 next if ($i == $displayed{'web'});
                   12670:                                 next if ($i == $displayed{'folder'});
                   12671:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12672:                             }
                   12673:                             $env{'form.phase'} = 'decompress_cleanup';
                   12674:                             $env{'form.archivedelete'} = 1;
                   12675:                             $env{'form.archive_count'} = $total-1;
                   12676:                             $output .=
                   12677:                                 &process_extracted_files('coursedocs',$docudom,
                   12678:                                                          $docuname,$destination,
                   12679:                                                          $dir_root,$hiddenelem);
                   12680:                         }
1.1055    raeburn  12681:                     } else {
                   12682:                         $warning = &mt('No new items extracted from archive file.');
                   12683:                     }
                   12684:                 } else {
                   12685:                     $output = $display;
                   12686:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12687:                 }
                   12688:             }
                   12689:         }
                   12690:     }
                   12691:     if ($error) {
                   12692:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12693:                    $error.'</p>'."\n";
                   12694:     }
                   12695:     if ($warning) {
                   12696:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12697:     }
                   12698:     return $output;
                   12699: }
                   12700: 
                   12701: sub get_extracted {
1.1056    raeburn  12702:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12703:         $titles,$wantform) = @_;
1.1055    raeburn  12704:     my $count = 0;
                   12705:     my $depth = 0;
                   12706:     my $datatable;
1.1056    raeburn  12707:     my @hierarchy;
1.1055    raeburn  12708:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12709:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12710:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12711:     foreach my $item (@{$contents}) {
                   12712:         $count ++;
1.1056    raeburn  12713:         @{$dirorder->{$count}} = @hierarchy;
                   12714:         $titles->{$count} = $item;
1.1055    raeburn  12715:         &archive_hierarchy($depth,$count,$parent,$children);
                   12716:         if ($wantform) {
                   12717:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12718:                                        $currdir,$depth,$count);
                   12719:         }
                   12720:         if ($is_dir->{$item}) {
                   12721:             $depth ++;
1.1056    raeburn  12722:             push(@hierarchy,$count);
                   12723:             $parent->{$depth} = $count;
1.1055    raeburn  12724:             $datatable .=
                   12725:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12726:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12727:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12728:             $depth --;
1.1056    raeburn  12729:             pop(@hierarchy);
1.1055    raeburn  12730:         }
                   12731:     }
                   12732:     return ($count,$datatable);
                   12733: }
                   12734: 
                   12735: sub recurse_extracted_archive {
1.1056    raeburn  12736:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12737:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12738:     my $result='';
1.1056    raeburn  12739:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12740:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12741:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12742:         return $result;
                   12743:     }
                   12744:     my $dirptr = 16384;
                   12745:     my ($newdirlistref,$newlisterror) =
                   12746:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12747:     if (ref($newdirlistref) eq 'ARRAY') {
                   12748:         foreach my $dir_line (@{$newdirlistref}) {
                   12749:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12750:             unless ($item =~ /^\.+$/) {
                   12751:                 $$count ++;
1.1056    raeburn  12752:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12753:                 $titles->{$$count} = $item;
1.1055    raeburn  12754:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12755: 
1.1055    raeburn  12756:                 my $is_dir;
                   12757:                 if ($dirptr&$testdir) {
                   12758:                     $is_dir = 1;
                   12759:                 }
                   12760:                 if ($wantform) {
                   12761:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12762:                 }
                   12763:                 if ($is_dir) {
                   12764:                     $$depth ++;
1.1056    raeburn  12765:                     push(@{$hierarchy},$$count);
                   12766:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12767:                     $result .=
                   12768:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12769:                                                    $docuname,$depth,$count,
1.1056    raeburn  12770:                                                    $hierarchy,$dirorder,$children,
                   12771:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12772:                     $$depth --;
1.1056    raeburn  12773:                     pop(@{$hierarchy});
1.1055    raeburn  12774:                 }
                   12775:             }
                   12776:         }
                   12777:     }
                   12778:     return $result;
                   12779: }
                   12780: 
                   12781: sub archive_hierarchy {
                   12782:     my ($depth,$count,$parent,$children) =@_;
                   12783:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12784:         if (exists($parent->{$depth})) {
                   12785:              $children->{$parent->{$depth}} .= $count.':';
                   12786:         }
                   12787:     }
                   12788:     return;
                   12789: }
                   12790: 
                   12791: sub archive_row {
                   12792:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12793:     my ($name) = ($item =~ m{([^/]+)$});
                   12794:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12795:                                        'display'    => 'Add as file',
1.1055    raeburn  12796:                                        'dependency' => 'Include as dependency',
                   12797:                                        'discard'    => 'Discard',
                   12798:                                       );
                   12799:     if ($is_dir) {
1.1059    raeburn  12800:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12801:     }
1.1056    raeburn  12802:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12803:     my $offset = 0;
1.1055    raeburn  12804:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12805:         $offset ++;
1.1065    raeburn  12806:         if ($action ne 'display') {
                   12807:             $offset ++;
                   12808:         }  
1.1055    raeburn  12809:         $output .= '<td><span class="LC_nobreak">'.
                   12810:                    '<label><input type="radio" name="archive_'.$count.
                   12811:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12812:         my $text = $choices{$action};
                   12813:         if ($is_dir) {
                   12814:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12815:             if ($action eq 'display') {
1.1059    raeburn  12816:                 $text = &mt('Add as folder');
1.1055    raeburn  12817:             }
1.1056    raeburn  12818:         } else {
                   12819:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12820: 
                   12821:         }
                   12822:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12823:         if ($action eq 'dependency') {
                   12824:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12825:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12826:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12827:                        '<option value=""></option>'."\n".
                   12828:                        '</select>'."\n".
                   12829:                        '</div>';
1.1059    raeburn  12830:         } elsif ($action eq 'display') {
                   12831:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12832:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12833:                        '</div>';
1.1055    raeburn  12834:         }
1.1056    raeburn  12835:         $output .= '</td>';
1.1055    raeburn  12836:     }
                   12837:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12838:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12839:     for (my $i=0; $i<$depth; $i++) {
                   12840:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12841:     }
                   12842:     if ($is_dir) {
                   12843:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12844:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12845:     } else {
                   12846:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12847:     }
                   12848:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12849:                &end_data_table_row();
                   12850:     return $output;
                   12851: }
                   12852: 
                   12853: sub archive_options_form {
1.1065    raeburn  12854:     my ($form,$display,$count,$hiddenelem) = @_;
                   12855:     my %lt = &Apache::lonlocal::texthash(
                   12856:                perm => 'Permanently remove archive file?',
                   12857:                hows => 'How should each extracted item be incorporated in the course?',
                   12858:                cont => 'Content actions for all',
                   12859:                addf => 'Add as folder/file',
                   12860:                incd => 'Include as dependency for a displayed file',
                   12861:                disc => 'Discard',
                   12862:                no   => 'No',
                   12863:                yes  => 'Yes',
                   12864:                save => 'Save',
                   12865:     );
                   12866:     my $output = <<"END";
                   12867: <form name="$form" method="post" action="">
                   12868: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12869: <label>
                   12870:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12871: </label>
                   12872: &nbsp;
                   12873: <label>
                   12874:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12875: </span>
                   12876: </p>
                   12877: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12878: <br />$lt{'hows'}
                   12879: <div class="LC_columnSection">
                   12880:   <fieldset>
                   12881:     <legend>$lt{'cont'}</legend>
                   12882:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12883:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12884:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12885:   </fieldset>
                   12886: </div>
                   12887: END
                   12888:     return $output.
1.1055    raeburn  12889:            &start_data_table()."\n".
1.1065    raeburn  12890:            $display."\n".
1.1055    raeburn  12891:            &end_data_table()."\n".
                   12892:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12893:            $hiddenelem.
1.1065    raeburn  12894:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12895:            '</form>';
                   12896: }
                   12897: 
                   12898: sub archive_javascript {
1.1056    raeburn  12899:     my ($startcount,$numitems,$titles,$children) = @_;
                   12900:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12901:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12902:     my $scripttag = <<START;
                   12903: <script type="text/javascript">
                   12904: // <![CDATA[
                   12905: 
                   12906: function checkAll(form,prefix) {
                   12907:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12908:     for (var i=0; i < form.elements.length; i++) {
                   12909:         var id = form.elements[i].id;
                   12910:         if ((id != '') && (id != undefined)) {
                   12911:             if (idstr.test(id)) {
                   12912:                 if (form.elements[i].type == 'radio') {
                   12913:                     form.elements[i].checked = true;
1.1056    raeburn  12914:                     var nostart = i-$startcount;
1.1059    raeburn  12915:                     var offset = nostart%7;
                   12916:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12917:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12918:                 }
                   12919:             }
                   12920:         }
                   12921:     }
                   12922: }
                   12923: 
                   12924: function propagateCheck(form,count) {
                   12925:     if (count > 0) {
1.1059    raeburn  12926:         var startelement = $startcount + ((count-1) * 7);
                   12927:         for (var j=1; j<6; j++) {
                   12928:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12929:                 var item = startelement + j; 
                   12930:                 if (form.elements[item].type == 'radio') {
                   12931:                     if (form.elements[item].checked) {
                   12932:                         containerCheck(form,count,j);
                   12933:                         break;
                   12934:                     }
1.1055    raeburn  12935:                 }
                   12936:             }
                   12937:         }
                   12938:     }
                   12939: }
                   12940: 
                   12941: numitems = $numitems
1.1056    raeburn  12942: var titles = new Array(numitems);
                   12943: var parents = new Array(numitems);
1.1055    raeburn  12944: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12945:     parents[i] = new Array;
1.1055    raeburn  12946: }
1.1059    raeburn  12947: var maintitle = '$maintitle';
1.1055    raeburn  12948: 
                   12949: START
                   12950: 
1.1056    raeburn  12951:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12952:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12953:         for (my $i=0; $i<@contents; $i ++) {
                   12954:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12955:         }
                   12956:     }
                   12957: 
1.1056    raeburn  12958:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12959:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12960:     }
                   12961: 
1.1055    raeburn  12962:     $scripttag .= <<END;
                   12963: 
                   12964: function containerCheck(form,count,offset) {
                   12965:     if (count > 0) {
1.1056    raeburn  12966:         dependencyCheck(form,count,offset);
1.1059    raeburn  12967:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12968:         form.elements[item].checked = true;
                   12969:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12970:             if (parents[count].length > 0) {
                   12971:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12972:                     containerCheck(form,parents[count][j],offset);
                   12973:                 }
                   12974:             }
                   12975:         }
                   12976:     }
                   12977: }
                   12978: 
                   12979: function dependencyCheck(form,count,offset) {
                   12980:     if (count > 0) {
1.1059    raeburn  12981:         var chosen = (offset+$startcount)+7*(count-1);
                   12982:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12983:         var currtype = form.elements[depitem].type;
                   12984:         if (form.elements[chosen].value == 'dependency') {
                   12985:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12986:             form.elements[depitem].options.length = 0;
                   12987:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  12988:             for (var i=1; i<=numitems; i++) {
                   12989:                 if (i == count) {
                   12990:                     continue;
                   12991:                 }
1.1059    raeburn  12992:                 var startelement = $startcount + (i-1) * 7;
                   12993:                 for (var j=1; j<6; j++) {
                   12994:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12995:                         var item = startelement + j;
                   12996:                         if (form.elements[item].type == 'radio') {
                   12997:                             if (form.elements[item].checked) {
                   12998:                                 if (form.elements[item].value == 'display') {
                   12999:                                     var n = form.elements[depitem].options.length;
                   13000:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13001:                                 }
                   13002:                             }
                   13003:                         }
                   13004:                     }
                   13005:                 }
                   13006:             }
                   13007:         } else {
                   13008:             document.getElementById('arc_depon_'+count).style.display='none';
                   13009:             form.elements[depitem].options.length = 0;
                   13010:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13011:         }
1.1059    raeburn  13012:         titleCheck(form,count,offset);
1.1056    raeburn  13013:     }
                   13014: }
                   13015: 
                   13016: function propagateSelect(form,count,offset) {
                   13017:     if (count > 0) {
1.1065    raeburn  13018:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13019:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13020:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13021:             if (parents[count].length > 0) {
                   13022:                 for (var j=0; j<parents[count].length; j++) {
                   13023:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13024:                 }
                   13025:             }
                   13026:         }
                   13027:     }
                   13028: }
1.1056    raeburn  13029: 
                   13030: function containerSelect(form,count,offset,picked) {
                   13031:     if (count > 0) {
1.1065    raeburn  13032:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13033:         if (form.elements[item].type == 'radio') {
                   13034:             if (form.elements[item].value == 'dependency') {
                   13035:                 if (form.elements[item+1].type == 'select-one') {
                   13036:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13037:                         if (form.elements[item+1].options[i].value == picked) {
                   13038:                             form.elements[item+1].selectedIndex = i;
                   13039:                             break;
                   13040:                         }
                   13041:                     }
                   13042:                 }
                   13043:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13044:                     if (parents[count].length > 0) {
                   13045:                         for (var j=0; j<parents[count].length; j++) {
                   13046:                             containerSelect(form,parents[count][j],offset,picked);
                   13047:                         }
                   13048:                     }
                   13049:                 }
                   13050:             }
                   13051:         }
                   13052:     }
                   13053: }
                   13054: 
1.1059    raeburn  13055: function titleCheck(form,count,offset) {
                   13056:     if (count > 0) {
                   13057:         var chosen = (offset+$startcount)+7*(count-1);
                   13058:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13059:         var currtype = form.elements[depitem].type;
                   13060:         if (form.elements[chosen].value == 'display') {
                   13061:             document.getElementById('arc_title_'+count).style.display='block';
                   13062:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13063:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13064:             }
                   13065:         } else {
                   13066:             document.getElementById('arc_title_'+count).style.display='none';
                   13067:             if (currtype == 'text') { 
                   13068:                 document.getElementById('archive_title_'+count).value='';
                   13069:             }
                   13070:         }
                   13071:     }
                   13072:     return;
                   13073: }
                   13074: 
1.1055    raeburn  13075: // ]]>
                   13076: </script>
                   13077: END
                   13078:     return $scripttag;
                   13079: }
                   13080: 
                   13081: sub process_extracted_files {
1.1067    raeburn  13082:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13083:     my $numitems = $env{'form.archive_count'};
                   13084:     return unless ($numitems);
                   13085:     my @ids=&Apache::lonnet::current_machine_ids();
                   13086:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13087:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13088:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13089:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13090:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13091:         $pathtocheck = "$dir_root/$destination";
                   13092:         $dir = $dir_root;
                   13093:         $ishome = 1;
                   13094:     } else {
                   13095:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13096:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   13097:         $dir = "$dir_root/$docudom/$docuname";    
                   13098:     }
                   13099:     my $currdir = "$dir_root/$destination";
                   13100:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13101:     if ($env{'form.folderpath'}) {
                   13102:         my @items = split('&',$env{'form.folderpath'});
                   13103:         $folders{'0'} = $items[-2];
1.1099    raeburn  13104:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13105:             $containers{'0'}='page';
                   13106:         } else {  
                   13107:             $containers{'0'}='sequence';
                   13108:         }
1.1055    raeburn  13109:     }
                   13110:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13111:     if ($numitems) {
                   13112:         for (my $i=1; $i<=$numitems; $i++) {
                   13113:             my $path = $env{'form.archive_content_'.$i};
                   13114:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13115:                 my $item = $1;
                   13116:                 $toplevelitems{$item} = $i;
                   13117:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13118:                     $is_dir{$item} = 1;
                   13119:                 }
                   13120:             }
                   13121:         }
                   13122:     }
1.1067    raeburn  13123:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13124:     if (keys(%toplevelitems) > 0) {
                   13125:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13126:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13127:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13128:     }
1.1066    raeburn  13129:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13130:     if ($numitems) {
                   13131:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13132:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13133:             my $path = $env{'form.archive_content_'.$i};
                   13134:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13135:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13136:                     if ($prefix ne '' && $path ne '') {
                   13137:                         if (-e $prefix.$path) {
1.1066    raeburn  13138:                             if ((@archdirs > 0) && 
                   13139:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13140:                                 $todeletedir{$prefix.$path} = 1;
                   13141:                             } else {
                   13142:                                 $todelete{$prefix.$path} = 1;
                   13143:                             }
1.1055    raeburn  13144:                         }
                   13145:                     }
                   13146:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13147:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13148:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13149:                     $docstitle = $env{'form.archive_title_'.$i};
                   13150:                     if ($docstitle eq '') {
                   13151:                         $docstitle = $title;
                   13152:                     }
1.1055    raeburn  13153:                     $outer = 0;
1.1056    raeburn  13154:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13155:                         if (@{$dirorder{$i}} > 0) {
                   13156:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13157:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13158:                                     $outer = $item;
                   13159:                                     last;
                   13160:                                 }
                   13161:                             }
                   13162:                         }
                   13163:                     }
                   13164:                     my ($errtext,$fatal) = 
                   13165:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13166:                                                '/'.$folders{$outer}.'.'.
                   13167:                                                $containers{$outer});
                   13168:                     next if ($fatal);
                   13169:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13170:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13171:                             $mapinner{$i} = time;
1.1055    raeburn  13172:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13173:                             $containers{$i} = 'sequence';
                   13174:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13175:                                       $folders{$i}.'.'.$containers{$i};
                   13176:                             my $newidx = &LONCAPA::map::getresidx();
                   13177:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13178:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13179:                             push(@LONCAPA::map::order,$newidx);
                   13180:                             my ($outtext,$errtext) =
                   13181:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13182:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13183:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13184:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13185:                             unless ($errtext) {
                   13186:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   13187:                             }
1.1055    raeburn  13188:                         }
                   13189:                     } else {
                   13190:                         if ($context eq 'coursedocs') {
                   13191:                             my $newidx=&LONCAPA::map::getresidx();
                   13192:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13193:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13194:                                       $title;
                   13195:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13196:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13197:                             }
                   13198:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13199:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13200:                             }
                   13201:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13202:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  13203:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  13204:                                 unless ($ishome) {
                   13205:                                     my $fetch = "$newdest{$i}/$title";
                   13206:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13207:                                     $prompttofetch{$fetch} = 1;
                   13208:                                 }
1.1055    raeburn  13209:                             }
                   13210:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13211:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13212:                             push(@LONCAPA::map::order, $newidx);
                   13213:                             my ($outtext,$errtext)=
                   13214:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13215:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13216:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  13217:                             unless ($errtext) {
                   13218:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13219:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   13220:                                 }
                   13221:                             }
1.1055    raeburn  13222:                         }
                   13223:                     }
1.1086    raeburn  13224:                 }
                   13225:             } else {
                   13226:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   13227:             }
                   13228:         }
                   13229:         for (my $i=1; $i<=$numitems; $i++) {
                   13230:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13231:             my $path = $env{'form.archive_content_'.$i};
                   13232:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13233:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13234:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13235:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13236:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13237:                         my ($itemidx,$fullpath,$relpath);
                   13238:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13239:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13240:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13241:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13242:                                     $itemidx = $j;
1.1056    raeburn  13243:                                 }
                   13244:                             }
1.1086    raeburn  13245:                         }
                   13246:                         if ($itemidx eq '') {
                   13247:                             $itemidx =  0;
                   13248:                         } 
                   13249:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13250:                             if ($mapinner{$referrer{$i}}) {
                   13251:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13252:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13253:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13254:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13255:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13256:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13257:                                             if (!-e $fullpath) {
                   13258:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13259:                                             }
                   13260:                                         }
1.1086    raeburn  13261:                                     } else {
                   13262:                                         last;
1.1056    raeburn  13263:                                     }
1.1086    raeburn  13264:                                 }
                   13265:                             }
                   13266:                         } elsif ($newdest{$referrer{$i}}) {
                   13267:                             $fullpath = $newdest{$referrer{$i}};
                   13268:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13269:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13270:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13271:                                     last;
                   13272:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13273:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13274:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13275:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13276:                                         if (!-e $fullpath) {
                   13277:                                             mkdir($fullpath,0755);
1.1056    raeburn  13278:                                         }
                   13279:                                     }
1.1086    raeburn  13280:                                 } else {
                   13281:                                     last;
1.1056    raeburn  13282:                                 }
1.1055    raeburn  13283:                             }
                   13284:                         }
1.1086    raeburn  13285:                         if ($fullpath ne '') {
                   13286:                             if (-e "$prefix$path") {
                   13287:                                 system("mv $prefix$path $fullpath/$title");
                   13288:                             }
                   13289:                             if (-e "$fullpath/$title") {
                   13290:                                 my $showpath;
                   13291:                                 if ($relpath ne '') {
                   13292:                                     $showpath = "$relpath/$title";
                   13293:                                 } else {
                   13294:                                     $showpath = "/$title";
                   13295:                                 } 
                   13296:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   13297:                             } 
                   13298:                             unless ($ishome) {
                   13299:                                 my $fetch = "$fullpath/$title";
                   13300:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   13301:                                 $prompttofetch{$fetch} = 1;
                   13302:                             }
                   13303:                         }
1.1055    raeburn  13304:                     }
1.1086    raeburn  13305:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13306:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   13307:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  13308:                 }
                   13309:             } else {
                   13310:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   13311:             }
                   13312:         }
                   13313:         if (keys(%todelete)) {
                   13314:             foreach my $key (keys(%todelete)) {
                   13315:                 unlink($key);
1.1066    raeburn  13316:             }
                   13317:         }
                   13318:         if (keys(%todeletedir)) {
                   13319:             foreach my $key (keys(%todeletedir)) {
                   13320:                 rmdir($key);
                   13321:             }
                   13322:         }
                   13323:         foreach my $dir (sort(keys(%is_dir))) {
                   13324:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13325:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13326:             }
                   13327:         }
1.1067    raeburn  13328:         if ($result ne '') {
                   13329:             $output .= '<ul>'."\n".
                   13330:                        $result."\n".
                   13331:                        '</ul>';
                   13332:         }
                   13333:         unless ($ishome) {
                   13334:             my $replicationfail;
                   13335:             foreach my $item (keys(%prompttofetch)) {
                   13336:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13337:                 unless ($fetchresult eq 'ok') {
                   13338:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13339:                 }
                   13340:             }
                   13341:             if ($replicationfail) {
                   13342:                 $output .= '<p class="LC_error">'.
                   13343:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13344:                            $replicationfail.
                   13345:                            '</ul></p>';
                   13346:             }
                   13347:         }
1.1055    raeburn  13348:     } else {
                   13349:         $warning = &mt('No items found in archive.');
                   13350:     }
                   13351:     if ($error) {
                   13352:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13353:                    $error.'</p>'."\n";
                   13354:     }
                   13355:     if ($warning) {
                   13356:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13357:     }
                   13358:     return $output;
                   13359: }
                   13360: 
1.1066    raeburn  13361: sub cleanup_empty_dirs {
                   13362:     my ($path) = @_;
                   13363:     if (($path ne '') && (-d $path)) {
                   13364:         if (opendir(my $dirh,$path)) {
                   13365:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13366:             my $numitems = 0;
                   13367:             foreach my $item (@dircontents) {
                   13368:                 if (-d "$path/$item") {
1.1111    raeburn  13369:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13370:                     if (-e "$path/$item") {
                   13371:                         $numitems ++;
                   13372:                     }
                   13373:                 } else {
                   13374:                     $numitems ++;
                   13375:                 }
                   13376:             }
                   13377:             if ($numitems == 0) {
                   13378:                 rmdir($path);
                   13379:             }
                   13380:             closedir($dirh);
                   13381:         }
                   13382:     }
                   13383:     return;
                   13384: }
                   13385: 
1.41      ng       13386: =pod
1.45      matthew  13387: 
1.1162    raeburn  13388: =item * &get_folder_hierarchy()
1.1068    raeburn  13389: 
                   13390: Provides hierarchy of names of folders/sub-folders containing the current
                   13391: item,
                   13392: 
                   13393: Inputs: 3
                   13394:      - $navmap - navmaps object
                   13395: 
                   13396:      - $map - url for map (either the trigger itself, or map containing
                   13397:                            the resource, which is the trigger).
                   13398: 
                   13399:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13400: 
                   13401: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13402: 
                   13403: =cut
                   13404: 
                   13405: sub get_folder_hierarchy {
                   13406:     my ($navmap,$map,$showitem) = @_;
                   13407:     my @pathitems;
                   13408:     if (ref($navmap)) {
                   13409:         my $mapres = $navmap->getResourceByUrl($map);
                   13410:         if (ref($mapres)) {
                   13411:             my $pcslist = $mapres->map_hierarchy();
                   13412:             if ($pcslist ne '') {
                   13413:                 my @pcs = split(/,/,$pcslist);
                   13414:                 foreach my $pc (@pcs) {
                   13415:                     if ($pc == 1) {
1.1129    raeburn  13416:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13417:                     } else {
                   13418:                         my $res = $navmap->getByMapPc($pc);
                   13419:                         if (ref($res)) {
                   13420:                             my $title = $res->compTitle();
                   13421:                             $title =~ s/\W+/_/g;
                   13422:                             if ($title ne '') {
                   13423:                                 push(@pathitems,$title);
                   13424:                             }
                   13425:                         }
                   13426:                     }
                   13427:                 }
                   13428:             }
1.1071    raeburn  13429:             if ($showitem) {
                   13430:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  13431:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13432:                 } else {
                   13433:                     my $maptitle = $mapres->compTitle();
                   13434:                     $maptitle =~ s/\W+/_/g;
                   13435:                     if ($maptitle ne '') {
                   13436:                         push(@pathitems,$maptitle);
                   13437:                     }
1.1068    raeburn  13438:                 }
                   13439:             }
                   13440:         }
                   13441:     }
                   13442:     return @pathitems;
                   13443: }
                   13444: 
                   13445: =pod
                   13446: 
1.1015    raeburn  13447: =item * &get_turnedin_filepath()
                   13448: 
                   13449: Determines path in a user's portfolio file for storage of files uploaded
                   13450: to a specific essayresponse or dropbox item.
                   13451: 
                   13452: Inputs: 3 required + 1 optional.
                   13453: $symb is symb for resource, $uname and $udom are for current user (required).
                   13454: $caller is optional (can be "submission", if routine is called when storing
                   13455: an upoaded file when "Submit Answer" button was pressed).
                   13456: 
                   13457: Returns array containing $path and $multiresp. 
                   13458: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13459: than one file upload item.  Callers of routine should append partid as a 
                   13460: subdirectory to $path in cases where $multiresp is 1.
                   13461: 
                   13462: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13463: 
                   13464: =cut
                   13465: 
                   13466: sub get_turnedin_filepath {
                   13467:     my ($symb,$uname,$udom,$caller) = @_;
                   13468:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13469:     my $turnindir;
                   13470:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13471:     $turnindir = $userhash{'turnindir'};
                   13472:     my ($path,$multiresp);
                   13473:     if ($turnindir eq '') {
                   13474:         if ($caller eq 'submission') {
                   13475:             $turnindir = &mt('turned in');
                   13476:             $turnindir =~ s/\W+/_/g;
                   13477:             my %newhash = (
                   13478:                             'turnindir' => $turnindir,
                   13479:                           );
                   13480:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13481:         }
                   13482:     }
                   13483:     if ($turnindir ne '') {
                   13484:         $path = '/'.$turnindir.'/';
                   13485:         my ($multipart,$turnin,@pathitems);
                   13486:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13487:         if (defined($navmap)) {
                   13488:             my $mapres = $navmap->getResourceByUrl($map);
                   13489:             if (ref($mapres)) {
                   13490:                 my $pcslist = $mapres->map_hierarchy();
                   13491:                 if ($pcslist ne '') {
                   13492:                     foreach my $pc (split(/,/,$pcslist)) {
                   13493:                         my $res = $navmap->getByMapPc($pc);
                   13494:                         if (ref($res)) {
                   13495:                             my $title = $res->compTitle();
                   13496:                             $title =~ s/\W+/_/g;
                   13497:                             if ($title ne '') {
1.1149    raeburn  13498:                                 if (($pc > 1) && (length($title) > 12)) {
                   13499:                                     $title = substr($title,0,12);
                   13500:                                 }
1.1015    raeburn  13501:                                 push(@pathitems,$title);
                   13502:                             }
                   13503:                         }
                   13504:                     }
                   13505:                 }
                   13506:                 my $maptitle = $mapres->compTitle();
                   13507:                 $maptitle =~ s/\W+/_/g;
                   13508:                 if ($maptitle ne '') {
1.1149    raeburn  13509:                     if (length($maptitle) > 12) {
                   13510:                         $maptitle = substr($maptitle,0,12);
                   13511:                     }
1.1015    raeburn  13512:                     push(@pathitems,$maptitle);
                   13513:                 }
                   13514:                 unless ($env{'request.state'} eq 'construct') {
                   13515:                     my $res = $navmap->getBySymb($symb);
                   13516:                     if (ref($res)) {
                   13517:                         my $partlist = $res->parts();
                   13518:                         my $totaluploads = 0;
                   13519:                         if (ref($partlist) eq 'ARRAY') {
                   13520:                             foreach my $part (@{$partlist}) {
                   13521:                                 my @types = $res->responseType($part);
                   13522:                                 my @ids = $res->responseIds($part);
                   13523:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13524:                                     if ($types[$i] eq 'essay') {
                   13525:                                         my $partid = $part.'_'.$ids[$i];
                   13526:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13527:                                             $totaluploads ++;
                   13528:                                         }
                   13529:                                     }
                   13530:                                 }
                   13531:                             }
                   13532:                             if ($totaluploads > 1) {
                   13533:                                 $multiresp = 1;
                   13534:                             }
                   13535:                         }
                   13536:                     }
                   13537:                 }
                   13538:             } else {
                   13539:                 return;
                   13540:             }
                   13541:         } else {
                   13542:             return;
                   13543:         }
                   13544:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13545:         $restitle =~ s/\W+/_/g;
                   13546:         if ($restitle eq '') {
                   13547:             $restitle = ($resurl =~ m{/[^/]+$});
                   13548:             if ($restitle eq '') {
                   13549:                 $restitle = time;
                   13550:             }
                   13551:         }
1.1149    raeburn  13552:         if (length($restitle) > 12) {
                   13553:             $restitle = substr($restitle,0,12);
                   13554:         }
1.1015    raeburn  13555:         push(@pathitems,$restitle);
                   13556:         $path .= join('/',@pathitems);
                   13557:     }
                   13558:     return ($path,$multiresp);
                   13559: }
                   13560: 
                   13561: =pod
                   13562: 
1.464     albertel 13563: =back
1.41      ng       13564: 
1.112     bowersj2 13565: =head1 CSV Upload/Handling functions
1.38      albertel 13566: 
1.41      ng       13567: =over 4
                   13568: 
1.648     raeburn  13569: =item * &upfile_store($r)
1.41      ng       13570: 
                   13571: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13572: needs $env{'form.upfile'}
1.41      ng       13573: returns $datatoken to be put into hidden field
                   13574: 
                   13575: =cut
1.31      albertel 13576: 
                   13577: sub upfile_store {
                   13578:     my $r=shift;
1.258     albertel 13579:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13580:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13581:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13582:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13583: 
1.258     albertel 13584:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   13585: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 13586:     {
1.158     raeburn  13587:         my $datafile = $r->dir_config('lonDaemons').
                   13588:                            '/tmp/'.$datatoken.'.tmp';
                   13589:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13590:             print $fh $env{'form.upfile'};
1.158     raeburn  13591:             close($fh);
                   13592:         }
1.31      albertel 13593:     }
                   13594:     return $datatoken;
                   13595: }
                   13596: 
1.56      matthew  13597: =pod
                   13598: 
1.648     raeburn  13599: =item * &load_tmp_file($r)
1.41      ng       13600: 
                   13601: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 13602: needs $env{'form.datatoken'},
                   13603: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13604: 
                   13605: =cut
1.31      albertel 13606: 
                   13607: sub load_tmp_file {
                   13608:     my $r=shift;
                   13609:     my @studentdata=();
                   13610:     {
1.158     raeburn  13611:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13612:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13613:         if ( open(my $fh,"<$studentfile") ) {
                   13614:             @studentdata=<$fh>;
                   13615:             close($fh);
                   13616:         }
1.31      albertel 13617:     }
1.258     albertel 13618:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13619: }
                   13620: 
1.56      matthew  13621: =pod
                   13622: 
1.648     raeburn  13623: =item * &upfile_record_sep()
1.41      ng       13624: 
                   13625: Separate uploaded file into records
                   13626: returns array of records,
1.258     albertel 13627: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13628: 
                   13629: =cut
1.31      albertel 13630: 
                   13631: sub upfile_record_sep {
1.258     albertel 13632:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13633:     } else {
1.248     albertel 13634: 	my @records;
1.258     albertel 13635: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13636: 	    if ($line=~/^\s*$/) { next; }
                   13637: 	    push(@records,$line);
                   13638: 	}
                   13639: 	return @records;
1.31      albertel 13640:     }
                   13641: }
                   13642: 
1.56      matthew  13643: =pod
                   13644: 
1.648     raeburn  13645: =item * &record_sep($record)
1.41      ng       13646: 
1.258     albertel 13647: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13648: 
                   13649: =cut
                   13650: 
1.263     www      13651: sub takeleft {
                   13652:     my $index=shift;
                   13653:     return substr('0000'.$index,-4,4);
                   13654: }
                   13655: 
1.31      albertel 13656: sub record_sep {
                   13657:     my $record=shift;
                   13658:     my %components=();
1.258     albertel 13659:     if ($env{'form.upfiletype'} eq 'xml') {
                   13660:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13661:         my $i=0;
1.356     albertel 13662:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13663:             $field=~s/^(\"|\')//;
                   13664:             $field=~s/(\"|\')$//;
1.263     www      13665:             $components{&takeleft($i)}=$field;
1.31      albertel 13666:             $i++;
                   13667:         }
1.258     albertel 13668:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13669:         my $i=0;
1.356     albertel 13670:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13671:             $field=~s/^(\"|\')//;
                   13672:             $field=~s/(\"|\')$//;
1.263     www      13673:             $components{&takeleft($i)}=$field;
1.31      albertel 13674:             $i++;
                   13675:         }
                   13676:     } else {
1.561     www      13677:         my $separator=',';
1.480     banghart 13678:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13679:             $separator=';';
1.480     banghart 13680:         }
1.31      albertel 13681:         my $i=0;
1.561     www      13682: # the character we are looking for to indicate the end of a quote or a record 
                   13683:         my $looking_for=$separator;
                   13684: # do not add the characters to the fields
                   13685:         my $ignore=0;
                   13686: # we just encountered a separator (or the beginning of the record)
                   13687:         my $just_found_separator=1;
                   13688: # store the field we are working on here
                   13689:         my $field='';
                   13690: # work our way through all characters in record
                   13691:         foreach my $character ($record=~/(.)/g) {
                   13692:             if ($character eq $looking_for) {
                   13693:                if ($character ne $separator) {
                   13694: # Found the end of a quote, again looking for separator
                   13695:                   $looking_for=$separator;
                   13696:                   $ignore=1;
                   13697:                } else {
                   13698: # Found a separator, store away what we got
                   13699:                   $components{&takeleft($i)}=$field;
                   13700: 	          $i++;
                   13701:                   $just_found_separator=1;
                   13702:                   $ignore=0;
                   13703:                   $field='';
                   13704:                }
                   13705:                next;
                   13706:             }
                   13707: # single or double quotation marks after a separator indicate beginning of a quote
                   13708: # we are now looking for the end of the quote and need to ignore separators
                   13709:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13710:                $looking_for=$character;
                   13711:                next;
                   13712:             }
                   13713: # ignore would be true after we reached the end of a quote
                   13714:             if ($ignore) { next; }
                   13715:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13716:             $field.=$character;
                   13717:             $just_found_separator=0; 
1.31      albertel 13718:         }
1.561     www      13719: # catch the very last entry, since we never encountered the separator
                   13720:         $components{&takeleft($i)}=$field;
1.31      albertel 13721:     }
                   13722:     return %components;
                   13723: }
                   13724: 
1.144     matthew  13725: ######################################################
                   13726: ######################################################
                   13727: 
1.56      matthew  13728: =pod
                   13729: 
1.648     raeburn  13730: =item * &upfile_select_html()
1.41      ng       13731: 
1.144     matthew  13732: Return HTML code to select a file from the users machine and specify 
                   13733: the file type.
1.41      ng       13734: 
                   13735: =cut
                   13736: 
1.144     matthew  13737: ######################################################
                   13738: ######################################################
1.31      albertel 13739: sub upfile_select_html {
1.144     matthew  13740:     my %Types = (
                   13741:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13742:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13743:                  space => &mt('Space separated'),
                   13744:                  tab   => &mt('Tabulator separated'),
                   13745: #                 xml   => &mt('HTML/XML'),
                   13746:                  );
                   13747:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13748:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13749:     foreach my $type (sort(keys(%Types))) {
                   13750:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13751:     }
                   13752:     $Str .= "</select>\n";
                   13753:     return $Str;
1.31      albertel 13754: }
                   13755: 
1.301     albertel 13756: sub get_samples {
                   13757:     my ($records,$toget) = @_;
                   13758:     my @samples=({});
                   13759:     my $got=0;
                   13760:     foreach my $rec (@$records) {
                   13761: 	my %temp = &record_sep($rec);
                   13762: 	if (! grep(/\S/, values(%temp))) { next; }
                   13763: 	if (%temp) {
                   13764: 	    $samples[$got]=\%temp;
                   13765: 	    $got++;
                   13766: 	    if ($got == $toget) { last; }
                   13767: 	}
                   13768:     }
                   13769:     return \@samples;
                   13770: }
                   13771: 
1.144     matthew  13772: ######################################################
                   13773: ######################################################
                   13774: 
1.56      matthew  13775: =pod
                   13776: 
1.648     raeburn  13777: =item * &csv_print_samples($r,$records)
1.41      ng       13778: 
                   13779: Prints a table of sample values from each column uploaded $r is an
                   13780: Apache Request ref, $records is an arrayref from
                   13781: &Apache::loncommon::upfile_record_sep
                   13782: 
                   13783: =cut
                   13784: 
1.144     matthew  13785: ######################################################
                   13786: ######################################################
1.31      albertel 13787: sub csv_print_samples {
                   13788:     my ($r,$records) = @_;
1.662     bisitz   13789:     my $samples = &get_samples($records,5);
1.301     albertel 13790: 
1.594     raeburn  13791:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13792:               &start_data_table_header_row());
1.356     albertel 13793:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13794:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13795:     $r->print(&end_data_table_header_row());
1.301     albertel 13796:     foreach my $hash (@$samples) {
1.594     raeburn  13797: 	$r->print(&start_data_table_row());
1.356     albertel 13798: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13799: 	    $r->print('<td>');
1.356     albertel 13800: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13801: 	    $r->print('</td>');
                   13802: 	}
1.594     raeburn  13803: 	$r->print(&end_data_table_row());
1.31      albertel 13804:     }
1.594     raeburn  13805:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13806: }
                   13807: 
1.144     matthew  13808: ######################################################
                   13809: ######################################################
                   13810: 
1.56      matthew  13811: =pod
                   13812: 
1.648     raeburn  13813: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13814: 
                   13815: Prints a table to create associations between values and table columns.
1.144     matthew  13816: 
1.41      ng       13817: $r is an Apache Request ref,
                   13818: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13819: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13820: 
                   13821: =cut
                   13822: 
1.144     matthew  13823: ######################################################
                   13824: ######################################################
1.31      albertel 13825: sub csv_print_select_table {
                   13826:     my ($r,$records,$d) = @_;
1.301     albertel 13827:     my $i=0;
                   13828:     my $samples = &get_samples($records,1);
1.144     matthew  13829:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13830: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13831:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13832:               '<th>'.&mt('Column').'</th>'.
                   13833:               &end_data_table_header_row()."\n");
1.356     albertel 13834:     foreach my $array_ref (@$d) {
                   13835: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13836: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13837: 
1.875     bisitz   13838: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13839: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13840: 	$r->print('<option value="none"></option>');
1.356     albertel 13841: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13842: 	    $r->print('<option value="'.$sample.'"'.
                   13843:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13844:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13845: 	}
1.594     raeburn  13846: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13847: 	$i++;
                   13848:     }
1.594     raeburn  13849:     $r->print(&end_data_table());
1.31      albertel 13850:     $i--;
                   13851:     return $i;
                   13852: }
1.56      matthew  13853: 
1.144     matthew  13854: ######################################################
                   13855: ######################################################
                   13856: 
1.56      matthew  13857: =pod
1.31      albertel 13858: 
1.648     raeburn  13859: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13860: 
                   13861: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13862: 
                   13863: $r is an Apache Request ref,
                   13864: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13865: $d is an array of 2 element arrays (internal name, displayed name)
                   13866: 
                   13867: =cut
                   13868: 
1.144     matthew  13869: ######################################################
                   13870: ######################################################
1.31      albertel 13871: sub csv_samples_select_table {
                   13872:     my ($r,$records,$d) = @_;
                   13873:     my $i=0;
1.144     matthew  13874:     #
1.662     bisitz   13875:     my $max_samples = 5;
                   13876:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13877:     $r->print(&start_data_table().
                   13878:               &start_data_table_header_row().'<th>'.
                   13879:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13880:               &end_data_table_header_row());
1.301     albertel 13881: 
                   13882:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13883: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13884: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13885: 	foreach my $option (@$d) {
                   13886: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13887: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13888:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13889:                       $display.'</option>');
1.31      albertel 13890: 	}
                   13891: 	$r->print('</select></td><td>');
1.662     bisitz   13892: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13893: 	    if (defined($samples->[$line]{$key})) { 
                   13894: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13895: 	    }
                   13896: 	}
1.594     raeburn  13897: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13898: 	$i++;
                   13899:     }
1.594     raeburn  13900:     $r->print(&end_data_table());
1.31      albertel 13901:     $i--;
                   13902:     return($i);
1.115     matthew  13903: }
                   13904: 
1.144     matthew  13905: ######################################################
                   13906: ######################################################
                   13907: 
1.115     matthew  13908: =pod
                   13909: 
1.648     raeburn  13910: =item * &clean_excel_name($name)
1.115     matthew  13911: 
                   13912: Returns a replacement for $name which does not contain any illegal characters.
                   13913: 
                   13914: =cut
                   13915: 
1.144     matthew  13916: ######################################################
                   13917: ######################################################
1.115     matthew  13918: sub clean_excel_name {
                   13919:     my ($name) = @_;
                   13920:     $name =~ s/[:\*\?\/\\]//g;
                   13921:     if (length($name) > 31) {
                   13922:         $name = substr($name,0,31);
                   13923:     }
                   13924:     return $name;
1.25      albertel 13925: }
1.84      albertel 13926: 
1.85      albertel 13927: =pod
                   13928: 
1.648     raeburn  13929: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13930: 
                   13931: Returns either 1 or undef
                   13932: 
                   13933: 1 if the part is to be hidden, undef if it is to be shown
                   13934: 
                   13935: Arguments are:
                   13936: 
                   13937: $id the id of the part to be checked
                   13938: $symb, optional the symb of the resource to check
                   13939: $udom, optional the domain of the user to check for
                   13940: $uname, optional the username of the user to check for
                   13941: 
                   13942: =cut
1.84      albertel 13943: 
                   13944: sub check_if_partid_hidden {
                   13945:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13946:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13947: 					 $symb,$udom,$uname);
1.141     albertel 13948:     my $truth=1;
                   13949:     #if the string starts with !, then the list is the list to show not hide
                   13950:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13951:     my @hiddenlist=split(/,/,$hiddenparts);
                   13952:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13953: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13954:     }
1.141     albertel 13955:     return !$truth;
1.84      albertel 13956: }
1.127     matthew  13957: 
1.138     matthew  13958: 
                   13959: ############################################################
                   13960: ############################################################
                   13961: 
                   13962: =pod
                   13963: 
1.157     matthew  13964: =back 
                   13965: 
1.138     matthew  13966: =head1 cgi-bin script and graphing routines
                   13967: 
1.157     matthew  13968: =over 4
                   13969: 
1.648     raeburn  13970: =item * &get_cgi_id()
1.138     matthew  13971: 
                   13972: Inputs: none
                   13973: 
                   13974: Returns an id which can be used to pass environment variables
                   13975: to various cgi-bin scripts.  These environment variables will
                   13976: be removed from the users environment after a given time by
                   13977: the routine &Apache::lonnet::transfer_profile_to_env.
                   13978: 
                   13979: =cut
                   13980: 
                   13981: ############################################################
                   13982: ############################################################
1.152     albertel 13983: my $uniq=0;
1.136     matthew  13984: sub get_cgi_id {
1.154     albertel 13985:     $uniq=($uniq+1)%100000;
1.280     albertel 13986:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13987: }
                   13988: 
1.127     matthew  13989: ############################################################
                   13990: ############################################################
                   13991: 
                   13992: =pod
                   13993: 
1.648     raeburn  13994: =item * &DrawBarGraph()
1.127     matthew  13995: 
1.138     matthew  13996: Facilitates the plotting of data in a (stacked) bar graph.
                   13997: Puts plot definition data into the users environment in order for 
                   13998: graph.png to plot it.  Returns an <img> tag for the plot.
                   13999: The bars on the plot are labeled '1','2',...,'n'.
                   14000: 
                   14001: Inputs:
                   14002: 
                   14003: =over 4
                   14004: 
                   14005: =item $Title: string, the title of the plot
                   14006: 
                   14007: =item $xlabel: string, text describing the X-axis of the plot
                   14008: 
                   14009: =item $ylabel: string, text describing the Y-axis of the plot
                   14010: 
                   14011: =item $Max: scalar, the maximum Y value to use in the plot
                   14012: If $Max is < any data point, the graph will not be rendered.
                   14013: 
1.140     matthew  14014: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14015: they are plotted.  If undefined, default values will be used.
                   14016: 
1.178     matthew  14017: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14018: 
1.138     matthew  14019: =item @Values: An array of array references.  Each array reference holds data
                   14020: to be plotted in a stacked bar chart.
                   14021: 
1.239     matthew  14022: =item If the final element of @Values is a hash reference the key/value
                   14023: pairs will be added to the graph definition.
                   14024: 
1.138     matthew  14025: =back
                   14026: 
                   14027: Returns:
                   14028: 
                   14029: An <img> tag which references graph.png and the appropriate identifying
                   14030: information for the plot.
                   14031: 
1.127     matthew  14032: =cut
                   14033: 
                   14034: ############################################################
                   14035: ############################################################
1.134     matthew  14036: sub DrawBarGraph {
1.178     matthew  14037:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14038:     #
                   14039:     if (! defined($colors)) {
                   14040:         $colors = ['#33ff00', 
                   14041:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14042:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14043:                   ]; 
                   14044:     }
1.228     matthew  14045:     my $extra_settings = {};
                   14046:     if (ref($Values[-1]) eq 'HASH') {
                   14047:         $extra_settings = pop(@Values);
                   14048:     }
1.127     matthew  14049:     #
1.136     matthew  14050:     my $identifier = &get_cgi_id();
                   14051:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14052:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14053:         return '';
                   14054:     }
1.225     matthew  14055:     #
                   14056:     my @Labels;
                   14057:     if (defined($labels)) {
                   14058:         @Labels = @$labels;
                   14059:     } else {
                   14060:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14061:             push(@Labels,$i+1);
1.225     matthew  14062:         }
                   14063:     }
                   14064:     #
1.129     matthew  14065:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14066:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14067:     my %ValuesHash;
                   14068:     my $NumSets=1;
                   14069:     foreach my $array (@Values) {
                   14070:         next if (! ref($array));
1.136     matthew  14071:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14072:             join(',',@$array);
1.129     matthew  14073:     }
1.127     matthew  14074:     #
1.136     matthew  14075:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14076:     if ($NumBars < 3) {
                   14077:         $width = 120+$NumBars*32;
1.220     matthew  14078:         $xskip = 1;
1.225     matthew  14079:         $bar_width = 30;
                   14080:     } elsif ($NumBars < 5) {
                   14081:         $width = 120+$NumBars*20;
                   14082:         $xskip = 1;
                   14083:         $bar_width = 20;
1.220     matthew  14084:     } elsif ($NumBars < 10) {
1.136     matthew  14085:         $width = 120+$NumBars*15;
                   14086:         $xskip = 1;
                   14087:         $bar_width = 15;
                   14088:     } elsif ($NumBars <= 25) {
                   14089:         $width = 120+$NumBars*11;
                   14090:         $xskip = 5;
                   14091:         $bar_width = 8;
                   14092:     } elsif ($NumBars <= 50) {
                   14093:         $width = 120+$NumBars*8;
                   14094:         $xskip = 5;
                   14095:         $bar_width = 4;
                   14096:     } else {
                   14097:         $width = 120+$NumBars*8;
                   14098:         $xskip = 5;
                   14099:         $bar_width = 4;
                   14100:     }
                   14101:     #
1.137     matthew  14102:     $Max = 1 if ($Max < 1);
                   14103:     if ( int($Max) < $Max ) {
                   14104:         $Max++;
                   14105:         $Max = int($Max);
                   14106:     }
1.127     matthew  14107:     $Title  = '' if (! defined($Title));
                   14108:     $xlabel = '' if (! defined($xlabel));
                   14109:     $ylabel = '' if (! defined($ylabel));
1.369     www      14110:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14111:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14112:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14113:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14114:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14115:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14116:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14117:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14118:     $ValuesHash{$id.'.height'}   = $height;
                   14119:     $ValuesHash{$id.'.width'}    = $width;
                   14120:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14121:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14122:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14123:     #
1.228     matthew  14124:     # Deal with other parameters
                   14125:     while (my ($key,$value) = each(%$extra_settings)) {
                   14126:         $ValuesHash{$id.'.'.$key} = $value;
                   14127:     }
                   14128:     #
1.646     raeburn  14129:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14130:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14131: }
                   14132: 
                   14133: ############################################################
                   14134: ############################################################
                   14135: 
                   14136: =pod
                   14137: 
1.648     raeburn  14138: =item * &DrawXYGraph()
1.137     matthew  14139: 
1.138     matthew  14140: Facilitates the plotting of data in an XY graph.
                   14141: Puts plot definition data into the users environment in order for 
                   14142: graph.png to plot it.  Returns an <img> tag for the plot.
                   14143: 
                   14144: Inputs:
                   14145: 
                   14146: =over 4
                   14147: 
                   14148: =item $Title: string, the title of the plot
                   14149: 
                   14150: =item $xlabel: string, text describing the X-axis of the plot
                   14151: 
                   14152: =item $ylabel: string, text describing the Y-axis of the plot
                   14153: 
                   14154: =item $Max: scalar, the maximum Y value to use in the plot
                   14155: If $Max is < any data point, the graph will not be rendered.
                   14156: 
                   14157: =item $colors: Array ref containing the hex color codes for the data to be 
                   14158: plotted in.  If undefined, default values will be used.
                   14159: 
                   14160: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14161: 
                   14162: =item $Ydata: Array ref containing Array refs.  
1.185     www      14163: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14164: 
                   14165: =item %Values: hash indicating or overriding any default values which are 
                   14166: passed to graph.png.  
                   14167: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14168: 
                   14169: =back
                   14170: 
                   14171: Returns:
                   14172: 
                   14173: An <img> tag which references graph.png and the appropriate identifying
                   14174: information for the plot.
                   14175: 
1.137     matthew  14176: =cut
                   14177: 
                   14178: ############################################################
                   14179: ############################################################
                   14180: sub DrawXYGraph {
                   14181:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14182:     #
                   14183:     # Create the identifier for the graph
                   14184:     my $identifier = &get_cgi_id();
                   14185:     my $id = 'cgi.'.$identifier;
                   14186:     #
                   14187:     $Title  = '' if (! defined($Title));
                   14188:     $xlabel = '' if (! defined($xlabel));
                   14189:     $ylabel = '' if (! defined($ylabel));
                   14190:     my %ValuesHash = 
                   14191:         (
1.369     www      14192:          $id.'.title'  => &escape($Title),
                   14193:          $id.'.xlabel' => &escape($xlabel),
                   14194:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14195:          $id.'.y_max_value'=> $Max,
                   14196:          $id.'.labels'     => join(',',@$Xlabels),
                   14197:          $id.'.PlotType'   => 'XY',
                   14198:          );
                   14199:     #
                   14200:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14201:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14202:     }
                   14203:     #
                   14204:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14205:         return '';
                   14206:     }
                   14207:     my $NumSets=1;
1.138     matthew  14208:     foreach my $array (@{$Ydata}){
1.137     matthew  14209:         next if (! ref($array));
                   14210:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14211:     }
1.138     matthew  14212:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14213:     #
                   14214:     # Deal with other parameters
                   14215:     while (my ($key,$value) = each(%Values)) {
                   14216:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14217:     }
                   14218:     #
1.646     raeburn  14219:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14220:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14221: }
                   14222: 
                   14223: ############################################################
                   14224: ############################################################
                   14225: 
                   14226: =pod
                   14227: 
1.648     raeburn  14228: =item * &DrawXYYGraph()
1.138     matthew  14229: 
                   14230: Facilitates the plotting of data in an XY graph with two Y axes.
                   14231: Puts plot definition data into the users environment in order for 
                   14232: graph.png to plot it.  Returns an <img> tag for the plot.
                   14233: 
                   14234: Inputs:
                   14235: 
                   14236: =over 4
                   14237: 
                   14238: =item $Title: string, the title of the plot
                   14239: 
                   14240: =item $xlabel: string, text describing the X-axis of the plot
                   14241: 
                   14242: =item $ylabel: string, text describing the Y-axis of the plot
                   14243: 
                   14244: =item $colors: Array ref containing the hex color codes for the data to be 
                   14245: plotted in.  If undefined, default values will be used.
                   14246: 
                   14247: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14248: 
                   14249: =item $Ydata1: The first data set
                   14250: 
                   14251: =item $Min1: The minimum value of the left Y-axis
                   14252: 
                   14253: =item $Max1: The maximum value of the left Y-axis
                   14254: 
                   14255: =item $Ydata2: The second data set
                   14256: 
                   14257: =item $Min2: The minimum value of the right Y-axis
                   14258: 
                   14259: =item $Max2: The maximum value of the left Y-axis
                   14260: 
                   14261: =item %Values: hash indicating or overriding any default values which are 
                   14262: passed to graph.png.  
                   14263: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14264: 
                   14265: =back
                   14266: 
                   14267: Returns:
                   14268: 
                   14269: An <img> tag which references graph.png and the appropriate identifying
                   14270: information for the plot.
1.136     matthew  14271: 
                   14272: =cut
                   14273: 
                   14274: ############################################################
                   14275: ############################################################
1.137     matthew  14276: sub DrawXYYGraph {
                   14277:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14278:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14279:     #
                   14280:     # Create the identifier for the graph
                   14281:     my $identifier = &get_cgi_id();
                   14282:     my $id = 'cgi.'.$identifier;
                   14283:     #
                   14284:     $Title  = '' if (! defined($Title));
                   14285:     $xlabel = '' if (! defined($xlabel));
                   14286:     $ylabel = '' if (! defined($ylabel));
                   14287:     my %ValuesHash = 
                   14288:         (
1.369     www      14289:          $id.'.title'  => &escape($Title),
                   14290:          $id.'.xlabel' => &escape($xlabel),
                   14291:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14292:          $id.'.labels' => join(',',@$Xlabels),
                   14293:          $id.'.PlotType' => 'XY',
                   14294:          $id.'.NumSets' => 2,
1.137     matthew  14295:          $id.'.two_axes' => 1,
                   14296:          $id.'.y1_max_value' => $Max1,
                   14297:          $id.'.y1_min_value' => $Min1,
                   14298:          $id.'.y2_max_value' => $Max2,
                   14299:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14300:          );
                   14301:     #
1.137     matthew  14302:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14303:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14304:     }
                   14305:     #
                   14306:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14307:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14308:         return '';
                   14309:     }
                   14310:     my $NumSets=1;
1.137     matthew  14311:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14312:         next if (! ref($array));
                   14313:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14314:     }
                   14315:     #
                   14316:     # Deal with other parameters
                   14317:     while (my ($key,$value) = each(%Values)) {
                   14318:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14319:     }
                   14320:     #
1.646     raeburn  14321:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14322:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14323: }
                   14324: 
                   14325: ############################################################
                   14326: ############################################################
                   14327: 
                   14328: =pod
                   14329: 
1.157     matthew  14330: =back 
                   14331: 
1.139     matthew  14332: =head1 Statistics helper routines?  
                   14333: 
                   14334: Bad place for them but what the hell.
                   14335: 
1.157     matthew  14336: =over 4
                   14337: 
1.648     raeburn  14338: =item * &chartlink()
1.139     matthew  14339: 
                   14340: Returns a link to the chart for a specific student.  
                   14341: 
                   14342: Inputs:
                   14343: 
                   14344: =over 4
                   14345: 
                   14346: =item $linktext: The text of the link
                   14347: 
                   14348: =item $sname: The students username
                   14349: 
                   14350: =item $sdomain: The students domain
                   14351: 
                   14352: =back
                   14353: 
1.157     matthew  14354: =back
                   14355: 
1.139     matthew  14356: =cut
                   14357: 
                   14358: ############################################################
                   14359: ############################################################
                   14360: sub chartlink {
                   14361:     my ($linktext, $sname, $sdomain) = @_;
                   14362:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14363:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14364:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14365:        '">'.$linktext.'</a>';
1.153     matthew  14366: }
                   14367: 
                   14368: #######################################################
                   14369: #######################################################
                   14370: 
                   14371: =pod
                   14372: 
                   14373: =head1 Course Environment Routines
1.157     matthew  14374: 
                   14375: =over 4
1.153     matthew  14376: 
1.648     raeburn  14377: =item * &restore_course_settings()
1.153     matthew  14378: 
1.648     raeburn  14379: =item * &store_course_settings()
1.153     matthew  14380: 
                   14381: Restores/Store indicated form parameters from the course environment.
                   14382: Will not overwrite existing values of the form parameters.
                   14383: 
                   14384: Inputs: 
                   14385: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14386: 
                   14387: a hash ref describing the data to be stored.  For example:
                   14388:    
                   14389: %Save_Parameters = ('Status' => 'scalar',
                   14390:     'chartoutputmode' => 'scalar',
                   14391:     'chartoutputdata' => 'scalar',
                   14392:     'Section' => 'array',
1.373     raeburn  14393:     'Group' => 'array',
1.153     matthew  14394:     'StudentData' => 'array',
                   14395:     'Maps' => 'array');
                   14396: 
                   14397: Returns: both routines return nothing
                   14398: 
1.631     raeburn  14399: =back
                   14400: 
1.153     matthew  14401: =cut
                   14402: 
                   14403: #######################################################
                   14404: #######################################################
                   14405: sub store_course_settings {
1.496     albertel 14406:     return &store_settings($env{'request.course.id'},@_);
                   14407: }
                   14408: 
                   14409: sub store_settings {
1.153     matthew  14410:     # save to the environment
                   14411:     # appenv the same items, just to be safe
1.300     albertel 14412:     my $udom  = $env{'user.domain'};
                   14413:     my $uname = $env{'user.name'};
1.496     albertel 14414:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14415:     my %SaveHash;
                   14416:     my %AppHash;
                   14417:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14418:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14419:         my $envname = 'environment.'.$basename;
1.258     albertel 14420:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14421:             # Save this value away
                   14422:             if ($type eq 'scalar' &&
1.258     albertel 14423:                 (! exists($env{$envname}) || 
                   14424:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14425:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14426:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14427:             } elsif ($type eq 'array') {
                   14428:                 my $stored_form;
1.258     albertel 14429:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14430:                     $stored_form = join(',',
                   14431:                                         map {
1.369     www      14432:                                             &escape($_);
1.258     albertel 14433:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14434:                 } else {
                   14435:                     $stored_form = 
1.369     www      14436:                         &escape($env{'form.'.$setting});
1.153     matthew  14437:                 }
                   14438:                 # Determine if the array contents are the same.
1.258     albertel 14439:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14440:                     $SaveHash{$basename} = $stored_form;
                   14441:                     $AppHash{$envname}   = $stored_form;
                   14442:                 }
                   14443:             }
                   14444:         }
                   14445:     }
                   14446:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14447:                                           $udom,$uname);
1.153     matthew  14448:     if ($put_result !~ /^(ok|delayed)/) {
                   14449:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14450:                                  'got error:'.$put_result);
                   14451:     }
                   14452:     # Make sure these settings stick around in this session, too
1.646     raeburn  14453:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14454:     return;
                   14455: }
                   14456: 
                   14457: sub restore_course_settings {
1.499     albertel 14458:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14459: }
                   14460: 
                   14461: sub restore_settings {
                   14462:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14463:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14464:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14465:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14466:             '.'.$setting;
1.258     albertel 14467:         if (exists($env{$envname})) {
1.153     matthew  14468:             if ($type eq 'scalar') {
1.258     albertel 14469:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14470:             } elsif ($type eq 'array') {
1.258     albertel 14471:                 $env{'form.'.$setting} = [ 
1.153     matthew  14472:                                            map { 
1.369     www      14473:                                                &unescape($_); 
1.258     albertel 14474:                                            } split(',',$env{$envname})
1.153     matthew  14475:                                            ];
                   14476:             }
                   14477:         }
                   14478:     }
1.127     matthew  14479: }
                   14480: 
1.618     raeburn  14481: #######################################################
                   14482: #######################################################
                   14483: 
                   14484: =pod
                   14485: 
                   14486: =head1 Domain E-mail Routines  
                   14487: 
                   14488: =over 4
                   14489: 
1.648     raeburn  14490: =item * &build_recipient_list()
1.618     raeburn  14491: 
1.1144    raeburn  14492: Build recipient lists for following types of e-mail:
1.766     raeburn  14493: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14494: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14495: module change checking, student/employee ID conflict checks, as
                   14496: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14497: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14498: 
                   14499: Inputs:
1.619     raeburn  14500: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14501: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14502: requestsmail, updatesmail, or idconflictsmail).
                   14503: 
1.619     raeburn  14504: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14505: 
1.619     raeburn  14506: origmail (scalar - email address of recipient from loncapa.conf, 
                   14507: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  14508: 
1.655     raeburn  14509: Returns: comma separated list of addresses to which to send e-mail.
                   14510: 
                   14511: =back
1.618     raeburn  14512: 
                   14513: =cut
                   14514: 
                   14515: ############################################################
                   14516: ############################################################
                   14517: sub build_recipient_list {
1.619     raeburn  14518:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  14519:     my @recipients;
                   14520:     my $otheremails;
                   14521:     my %domconfig =
                   14522:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   14523:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14524:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14525:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14526:                 my @contacts = ('adminemail','supportemail');
                   14527:                 foreach my $item (@contacts) {
                   14528:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14529:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14530:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14531:                             push(@recipients,$addr);
                   14532:                         }
1.619     raeburn  14533:                     }
1.766     raeburn  14534:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  14535:                 }
                   14536:             }
1.766     raeburn  14537:         } elsif ($origmail ne '') {
                   14538:             push(@recipients,$origmail);
1.618     raeburn  14539:         }
1.619     raeburn  14540:     } elsif ($origmail ne '') {
                   14541:         push(@recipients,$origmail);
1.618     raeburn  14542:     }
1.688     raeburn  14543:     if (defined($defmail)) {
                   14544:         if ($defmail ne '') {
                   14545:             push(@recipients,$defmail);
                   14546:         }
1.618     raeburn  14547:     }
                   14548:     if ($otheremails) {
1.619     raeburn  14549:         my @others;
                   14550:         if ($otheremails =~ /,/) {
                   14551:             @others = split(/,/,$otheremails);
1.618     raeburn  14552:         } else {
1.619     raeburn  14553:             push(@others,$otheremails);
                   14554:         }
                   14555:         foreach my $addr (@others) {
                   14556:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14557:                 push(@recipients,$addr);
                   14558:             }
1.618     raeburn  14559:         }
                   14560:     }
1.619     raeburn  14561:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  14562:     return $recipientlist;
                   14563: }
                   14564: 
1.127     matthew  14565: ############################################################
                   14566: ############################################################
1.154     albertel 14567: 
1.655     raeburn  14568: =pod
                   14569: 
1.1224    musolffc 14570: =over 4
                   14571: 
1.1223    musolffc 14572: =item * &mime_email()
                   14573: 
                   14574: Sends an email with a possible attachment
                   14575: 
                   14576: Inputs:
                   14577: 
                   14578: =over 4
                   14579: 
                   14580: from -              Sender's email address
                   14581: 
                   14582: to -                Email address of recipient
                   14583: 
                   14584: subject -           Subject of email
                   14585: 
                   14586: body -              Body of email
                   14587: 
                   14588: cc_string -         Carbon copy email address
                   14589: 
                   14590: bcc -               Blind carbon copy email address
                   14591: 
                   14592: type -              File type of attachment
                   14593: 
                   14594: attachment_path -   Path of file to be attached
                   14595: 
                   14596: file_name -         Name of file to be attached
                   14597: 
                   14598: attachment_text -   The body of an attachment of type "TEXT"
                   14599: 
                   14600: =back
                   14601: 
                   14602: =back
                   14603: 
                   14604: =cut
                   14605: 
                   14606: ############################################################
                   14607: ############################################################
                   14608: 
                   14609: sub mime_email {
                   14610:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   14611:         $file_name, $attachment_text) = @_;
                   14612:     my $msg = MIME::Lite->new(
                   14613:              From    => $from,
                   14614:              To      => $to,
                   14615:              Subject => $subject,
                   14616:              Type    =>'TEXT',
                   14617:              Data    => $body,
                   14618:              );
                   14619:     if ($cc_string ne '') {
                   14620:         $msg->add("Cc" => $cc_string);
                   14621:     }
                   14622:     if ($bcc ne '') {
                   14623:         $msg->add("Bcc" => $bcc);
                   14624:     }
                   14625:     $msg->attr("content-type"         => "text/plain");
                   14626:     $msg->attr("content-type.charset" => "UTF-8");
                   14627:     # Attach file if given
                   14628:     if ($attachment_path) {
                   14629:         unless ($file_name) {
                   14630:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   14631:         }
                   14632:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   14633:         $msg->attach(Type     => $type,
                   14634:                      Path     => $attachment_path,
                   14635:                      Filename => $file_name
                   14636:                      );
                   14637:     # Otherwise attach text if given
                   14638:     } elsif ($attachment_text) {
                   14639:         $msg->attach(Type => 'TEXT',
                   14640:                      Data => $attachment_text);
                   14641:     }
                   14642:     # Send it
                   14643:     $msg->send('sendmail');
                   14644: }
                   14645: 
                   14646: ############################################################
                   14647: ############################################################
                   14648: 
                   14649: =pod
                   14650: 
1.655     raeburn  14651: =head1 Course Catalog Routines
                   14652: 
                   14653: =over 4
                   14654: 
                   14655: =item * &gather_categories()
                   14656: 
                   14657: Converts category definitions - keys of categories hash stored in  
                   14658: coursecategories in configuration.db on the primary library server in a 
                   14659: domain - to an array.  Also generates javascript and idx hash used to 
                   14660: generate Domain Coordinator interface for editing Course Categories.
                   14661: 
                   14662: Inputs:
1.663     raeburn  14663: 
1.655     raeburn  14664: categories (reference to hash of category definitions).
1.663     raeburn  14665: 
1.655     raeburn  14666: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14667:       categories and subcategories).
1.663     raeburn  14668: 
1.655     raeburn  14669: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14670:       editing Course Categories).
1.663     raeburn  14671: 
1.655     raeburn  14672: jsarray (reference to array of categories used to create Javascript arrays for
                   14673:          Domain Coordinator interface for editing Course Categories).
                   14674: 
                   14675: Returns: nothing
                   14676: 
                   14677: Side effects: populates cats, idx and jsarray. 
                   14678: 
                   14679: =cut
                   14680: 
                   14681: sub gather_categories {
                   14682:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14683:     my %counters;
                   14684:     my $num = 0;
                   14685:     foreach my $item (keys(%{$categories})) {
                   14686:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14687:         if ($container eq '' && $depth == 0) {
                   14688:             $cats->[$depth][$categories->{$item}] = $cat;
                   14689:         } else {
                   14690:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14691:         }
                   14692:         my ($escitem,$tail) = split(/:/,$item,2);
                   14693:         if ($counters{$tail} eq '') {
                   14694:             $counters{$tail} = $num;
                   14695:             $num ++;
                   14696:         }
                   14697:         if (ref($idx) eq 'HASH') {
                   14698:             $idx->{$item} = $counters{$tail};
                   14699:         }
                   14700:         if (ref($jsarray) eq 'ARRAY') {
                   14701:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14702:         }
                   14703:     }
                   14704:     return;
                   14705: }
                   14706: 
                   14707: =pod
                   14708: 
                   14709: =item * &extract_categories()
                   14710: 
                   14711: Used to generate breadcrumb trails for course categories.
                   14712: 
                   14713: Inputs:
1.663     raeburn  14714: 
1.655     raeburn  14715: categories (reference to hash of category definitions).
1.663     raeburn  14716: 
1.655     raeburn  14717: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14718:       categories and subcategories).
1.663     raeburn  14719: 
1.655     raeburn  14720: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14721: 
1.655     raeburn  14722: allitems (reference to hash - key is category key 
                   14723:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14724: 
1.655     raeburn  14725: idx (reference to hash of counters used in Domain Coordinator interface for
                   14726:       editing Course Categories).
1.663     raeburn  14727: 
1.655     raeburn  14728: jsarray (reference to array of categories used to create Javascript arrays for
                   14729:          Domain Coordinator interface for editing Course Categories).
                   14730: 
1.665     raeburn  14731: subcats (reference to hash of arrays containing all subcategories within each 
                   14732:          category, -recursive)
                   14733: 
1.655     raeburn  14734: Returns: nothing
                   14735: 
                   14736: Side effects: populates trails and allitems hash references.
                   14737: 
                   14738: =cut
                   14739: 
                   14740: sub extract_categories {
1.665     raeburn  14741:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14742:     if (ref($categories) eq 'HASH') {
                   14743:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14744:         if (ref($cats->[0]) eq 'ARRAY') {
                   14745:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14746:                 my $name = $cats->[0][$i];
                   14747:                 my $item = &escape($name).'::0';
                   14748:                 my $trailstr;
                   14749:                 if ($name eq 'instcode') {
                   14750:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14751:                 } elsif ($name eq 'communities') {
                   14752:                     $trailstr = &mt('Communities');
1.1239    raeburn  14753:                 } elsif ($name eq 'placement') {
                   14754:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  14755:                 } else {
                   14756:                     $trailstr = $name;
                   14757:                 }
                   14758:                 if ($allitems->{$item} eq '') {
                   14759:                     push(@{$trails},$trailstr);
                   14760:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14761:                 }
                   14762:                 my @parents = ($name);
                   14763:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14764:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14765:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14766:                         if (ref($subcats) eq 'HASH') {
                   14767:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14768:                         }
                   14769:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14770:                     }
                   14771:                 } else {
                   14772:                     if (ref($subcats) eq 'HASH') {
                   14773:                         $subcats->{$item} = [];
1.655     raeburn  14774:                     }
                   14775:                 }
                   14776:             }
                   14777:         }
                   14778:     }
                   14779:     return;
                   14780: }
                   14781: 
                   14782: =pod
                   14783: 
1.1162    raeburn  14784: =item * &recurse_categories()
1.655     raeburn  14785: 
                   14786: Recursively used to generate breadcrumb trails for course categories.
                   14787: 
                   14788: Inputs:
1.663     raeburn  14789: 
1.655     raeburn  14790: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14791:       categories and subcategories).
1.663     raeburn  14792: 
1.655     raeburn  14793: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14794: 
                   14795: category (current course category, for which breadcrumb trail is being generated).
                   14796: 
                   14797: trails (reference to array of breadcrumb trails for each category).
                   14798: 
1.655     raeburn  14799: allitems (reference to hash - key is category key
                   14800:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14801: 
1.655     raeburn  14802: parents (array containing containers directories for current category, 
                   14803:          back to top level). 
                   14804: 
                   14805: Returns: nothing
                   14806: 
                   14807: Side effects: populates trails and allitems hash references
                   14808: 
                   14809: =cut
                   14810: 
                   14811: sub recurse_categories {
1.665     raeburn  14812:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14813:     my $shallower = $depth - 1;
                   14814:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14815:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14816:             my $name = $cats->[$depth]{$category}[$k];
                   14817:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14818:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14819:             if ($allitems->{$item} eq '') {
                   14820:                 push(@{$trails},$trailstr);
                   14821:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14822:             }
                   14823:             my $deeper = $depth+1;
                   14824:             push(@{$parents},$category);
1.665     raeburn  14825:             if (ref($subcats) eq 'HASH') {
                   14826:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14827:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14828:                     my $higher;
                   14829:                     if ($j > 0) {
                   14830:                         $higher = &escape($parents->[$j]).':'.
                   14831:                                   &escape($parents->[$j-1]).':'.$j;
                   14832:                     } else {
                   14833:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14834:                     }
                   14835:                     push(@{$subcats->{$higher}},$subcat);
                   14836:                 }
                   14837:             }
                   14838:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14839:                                 $subcats);
1.655     raeburn  14840:             pop(@{$parents});
                   14841:         }
                   14842:     } else {
                   14843:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14844:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14845:         if ($allitems->{$item} eq '') {
                   14846:             push(@{$trails},$trailstr);
                   14847:             $allitems->{$item} = scalar(@{$trails})-1;
                   14848:         }
                   14849:     }
                   14850:     return;
                   14851: }
                   14852: 
1.663     raeburn  14853: =pod
                   14854: 
1.1162    raeburn  14855: =item * &assign_categories_table()
1.663     raeburn  14856: 
                   14857: Create a datatable for display of hierarchical categories in a domain,
                   14858: with checkboxes to allow a course to be categorized. 
                   14859: 
                   14860: Inputs:
                   14861: 
                   14862: cathash - reference to hash of categories defined for the domain (from
                   14863:           configuration.db)
                   14864: 
                   14865: currcat - scalar with an & separated list of categories assigned to a course. 
                   14866: 
1.919     raeburn  14867: type    - scalar contains course type (Course or Community).
                   14868: 
1.1260    raeburn  14869: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14870:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14871: 
1.663     raeburn  14872: Returns: $output (markup to be displayed) 
                   14873: 
                   14874: =cut
                   14875: 
                   14876: sub assign_categories_table {
1.1259    raeburn  14877:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14878:     my $output;
                   14879:     if (ref($cathash) eq 'HASH') {
                   14880:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14881:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14882:         $maxdepth = scalar(@cats);
                   14883:         if (@cats > 0) {
                   14884:             my $itemcount = 0;
                   14885:             if (ref($cats[0]) eq 'ARRAY') {
                   14886:                 my @currcategories;
                   14887:                 if ($currcat ne '') {
                   14888:                     @currcategories = split('&',$currcat);
                   14889:                 }
1.919     raeburn  14890:                 my $table;
1.663     raeburn  14891:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14892:                     my $parent = $cats[0][$i];
1.919     raeburn  14893:                     next if ($parent eq 'instcode');
                   14894:                     if ($type eq 'Community') {
                   14895:                         next unless ($parent eq 'communities');
1.1239    raeburn  14896:                     } elsif ($type eq 'Placement') {
                   14897:                         next unless ($parent eq 'placement');
1.919     raeburn  14898:                     } else {
1.1239    raeburn  14899:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  14900:                     }
1.663     raeburn  14901:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14902:                     my $item = &escape($parent).'::0';
                   14903:                     my $checked = '';
                   14904:                     if (@currcategories > 0) {
                   14905:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14906:                             $checked = ' checked="checked"';
1.663     raeburn  14907:                         }
                   14908:                     }
1.919     raeburn  14909:                     my $parent_title = $parent;
                   14910:                     if ($parent eq 'communities') {
                   14911:                         $parent_title = &mt('Communities');
1.1239    raeburn  14912:                     } elsif ($parent eq 'placement') {
                   14913:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  14914:                     }
                   14915:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14916:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  14917:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14918:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14919:                     my $depth = 1;
                   14920:                     push(@path,$parent);
1.1259    raeburn  14921:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14922:                     pop(@path);
1.919     raeburn  14923:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14924:                     $itemcount ++;
                   14925:                 }
1.919     raeburn  14926:                 if ($itemcount) {
                   14927:                     $output = &Apache::loncommon::start_data_table().
                   14928:                               $table.
                   14929:                               &Apache::loncommon::end_data_table();
                   14930:                 }
1.663     raeburn  14931:             }
                   14932:         }
                   14933:     }
                   14934:     return $output;
                   14935: }
                   14936: 
                   14937: =pod
                   14938: 
1.1162    raeburn  14939: =item * &assign_category_rows()
1.663     raeburn  14940: 
                   14941: Create a datatable row for display of nested categories in a domain,
                   14942: with checkboxes to allow a course to be categorized,called recursively.
                   14943: 
                   14944: Inputs:
                   14945: 
                   14946: itemcount - track row number for alternating colors
                   14947: 
                   14948: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14949:       categories and subcategories.
                   14950: 
                   14951: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14952: 
                   14953: parent - parent of current category item
                   14954: 
                   14955: path - Array containing all categories back up through the hierarchy from the
                   14956:        current category to the top level.
                   14957: 
                   14958: currcategories - reference to array of current categories assigned to the course
                   14959: 
1.1260    raeburn  14960: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14961:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14962: 
1.663     raeburn  14963: Returns: $output (markup to be displayed).
                   14964: 
                   14965: =cut
                   14966: 
                   14967: sub assign_category_rows {
1.1259    raeburn  14968:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14969:     my ($text,$name,$item,$chgstr);
                   14970:     if (ref($cats) eq 'ARRAY') {
                   14971:         my $maxdepth = scalar(@{$cats});
                   14972:         if (ref($cats->[$depth]) eq 'HASH') {
                   14973:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14974:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14975:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  14976:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14977:                 for (my $j=0; $j<$numchildren; $j++) {
                   14978:                     $name = $cats->[$depth]{$parent}[$j];
                   14979:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14980:                     my $deeper = $depth+1;
                   14981:                     my $checked = '';
                   14982:                     if (ref($currcategories) eq 'ARRAY') {
                   14983:                         if (@{$currcategories} > 0) {
                   14984:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14985:                                 $checked = ' checked="checked"';
1.663     raeburn  14986:                             }
                   14987:                         }
                   14988:                     }
1.664     raeburn  14989:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14990:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  14991:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14992:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14993:                              '</td><td>';
1.663     raeburn  14994:                     if (ref($path) eq 'ARRAY') {
                   14995:                         push(@{$path},$name);
1.1259    raeburn  14996:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14997:                         pop(@{$path});
                   14998:                     }
                   14999:                     $text .= '</td></tr>';
                   15000:                 }
                   15001:                 $text .= '</table></td>';
                   15002:             }
                   15003:         }
                   15004:     }
                   15005:     return $text;
                   15006: }
                   15007: 
1.1181    raeburn  15008: =pod
                   15009: 
                   15010: =back
                   15011: 
                   15012: =cut
                   15013: 
1.655     raeburn  15014: ############################################################
                   15015: ############################################################
                   15016: 
                   15017: 
1.443     albertel 15018: sub commit_customrole {
1.664     raeburn  15019:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15020:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15021:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15022:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15023:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15024:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15025:                  '</b><br />';
                   15026:     return $output;
                   15027: }
                   15028: 
                   15029: sub commit_standardrole {
1.1116    raeburn  15030:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15031:     my ($output,$logmsg,$linefeed);
                   15032:     if ($context eq 'auto') {
                   15033:         $linefeed = "\n";
                   15034:     } else {
                   15035:         $linefeed = "<br />\n";
                   15036:     }  
1.443     albertel 15037:     if ($three eq 'st') {
1.541     raeburn  15038:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15039:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15040:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15041:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15042:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15043:         } else {
1.541     raeburn  15044:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15045:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15046:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15047:             if ($context eq 'auto') {
                   15048:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15049:             } else {
                   15050:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15051:                &mt('Add to classlist').': <b>ok</b>';
                   15052:             }
                   15053:             $output .= $linefeed;
1.443     albertel 15054:         }
                   15055:     } else {
                   15056:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15057:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15058:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15059:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15060:         if ($context eq 'auto') {
                   15061:             $output .= $result.$linefeed;
                   15062:         } else {
                   15063:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15064:         }
1.443     albertel 15065:     }
                   15066:     return $output;
                   15067: }
                   15068: 
                   15069: sub commit_studentrole {
1.1116    raeburn  15070:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15071:         $credits) = @_;
1.626     raeburn  15072:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15073:     if ($context eq 'auto') {
                   15074:         $linefeed = "\n";
                   15075:     } else {
                   15076:         $linefeed = '<br />'."\n";
                   15077:     }
1.443     albertel 15078:     if (defined($one) && defined($two)) {
                   15079:         my $cid=$one.'_'.$two;
                   15080:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15081:         my $secchange = 0;
                   15082:         my $expire_role_result;
                   15083:         my $modify_section_result;
1.628     raeburn  15084:         if ($oldsec ne '-1') { 
                   15085:             if ($oldsec ne $sec) {
1.443     albertel 15086:                 $secchange = 1;
1.628     raeburn  15087:                 my $now = time;
1.443     albertel 15088:                 my $uurl='/'.$cid;
                   15089:                 $uurl=~s/\_/\//g;
                   15090:                 if ($oldsec) {
                   15091:                     $uurl.='/'.$oldsec;
                   15092:                 }
1.626     raeburn  15093:                 $oldsecurl = $uurl;
1.628     raeburn  15094:                 $expire_role_result = 
1.652     raeburn  15095:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15096:                 if ($env{'request.course.sec'} ne '') { 
                   15097:                     if ($expire_role_result eq 'refused') {
                   15098:                         my @roles = ('st');
                   15099:                         my @statuses = ('previous');
                   15100:                         my @roledoms = ($one);
                   15101:                         my $withsec = 1;
                   15102:                         my %roleshash = 
                   15103:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15104:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15105:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15106:                             my ($oldstart,$oldend) = 
                   15107:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15108:                             if ($oldend > 0 && $oldend <= $now) {
                   15109:                                 $expire_role_result = 'ok';
                   15110:                             }
                   15111:                         }
                   15112:                     }
                   15113:                 }
1.443     albertel 15114:                 $result = $expire_role_result;
                   15115:             }
                   15116:         }
                   15117:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  15118:             $modify_section_result = 
                   15119:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15120:                                                            undef,undef,undef,$sec,
                   15121:                                                            $end,$start,'','',$cid,
                   15122:                                                            '',$context,$credits);
1.443     albertel 15123:             if ($modify_section_result =~ /^ok/) {
                   15124:                 if ($secchange == 1) {
1.628     raeburn  15125:                     if ($sec eq '') {
                   15126:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15127:                     } else {
                   15128:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15129:                     }
1.443     albertel 15130:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15131:                     if ($sec eq '') {
                   15132:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15133:                     } else {
                   15134:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15135:                     }
1.443     albertel 15136:                 } else {
1.628     raeburn  15137:                     if ($sec eq '') {
                   15138:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15139:                     } else {
                   15140:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15141:                     }
1.443     albertel 15142:                 }
                   15143:             } else {
1.1115    raeburn  15144:                 if ($secchange) { 
1.628     raeburn  15145:                     $$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;
                   15146:                 } else {
                   15147:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15148:                 }
1.443     albertel 15149:             }
                   15150:             $result = $modify_section_result;
                   15151:         } elsif ($secchange == 1) {
1.628     raeburn  15152:             if ($oldsec eq '') {
1.1103    raeburn  15153:                 $$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  15154:             } else {
                   15155:                 $$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;
                   15156:             }
1.626     raeburn  15157:             if ($expire_role_result eq 'refused') {
                   15158:                 my $newsecurl = '/'.$cid;
                   15159:                 $newsecurl =~ s/\_/\//g;
                   15160:                 if ($sec ne '') {
                   15161:                     $newsecurl.='/'.$sec;
                   15162:                 }
                   15163:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15164:                     if ($sec eq '') {
                   15165:                         $$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;
                   15166:                     } else {
                   15167:                         $$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;
                   15168:                     }
                   15169:                 }
                   15170:             }
1.443     albertel 15171:         }
                   15172:     } else {
1.626     raeburn  15173:         $$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 15174:         $result = "error: incomplete course id\n";
                   15175:     }
                   15176:     return $result;
                   15177: }
                   15178: 
1.1108    raeburn  15179: sub show_role_extent {
                   15180:     my ($scope,$context,$role) = @_;
                   15181:     $scope =~ s{^/}{};
                   15182:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15183:     push(@courseroles,'co');
                   15184:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15185:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15186:         $scope =~ s{/}{_};
                   15187:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15188:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15189:         my ($audom,$auname) = split(/\//,$scope);
                   15190:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15191:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15192:     } else {
                   15193:         $scope =~ s{/$}{};
                   15194:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15195:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15196:     }
                   15197: }
                   15198: 
1.443     albertel 15199: ############################################################
                   15200: ############################################################
                   15201: 
1.566     albertel 15202: sub check_clone {
1.578     raeburn  15203:     my ($args,$linefeed) = @_;
1.566     albertel 15204:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15205:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15206:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15207:     my $clonemsg;
                   15208:     my $can_clone = 0;
1.944     raeburn  15209:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15210:     if ($lctype ne 'community') {
                   15211:         $lctype = 'course';
                   15212:     }
1.566     albertel 15213:     if ($clonehome eq 'no_host') {
1.944     raeburn  15214:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15215:             $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'});
                   15216:         } else {
                   15217:             $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'});
                   15218:         }     
1.566     albertel 15219:     } else {
                   15220: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15221:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15222:             if ($clonedesc{'type'} ne 'Community') {
1.1262    raeburn  15223:                 $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  15224:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15225:             }
                   15226:         }
1.1262    raeburn  15227: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15228:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15229: 	    $can_clone = 1;
                   15230: 	} else {
1.1221    raeburn  15231: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15232: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  15233:             if ($clonehash{'cloners'} eq '') {
                   15234:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15235:                 if ($domdefs{'canclone'}) {
                   15236:                     unless ($domdefs{'canclone'} eq 'none') {
                   15237:                         if ($domdefs{'canclone'} eq 'domain') {
                   15238:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15239:                                 $can_clone = 1;
                   15240:                             }
                   15241:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15242:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15243:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15244:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15245:                                 $can_clone = 1;
                   15246:                             }
                   15247:                         }
                   15248:                     }
                   15249:                 }
1.578     raeburn  15250:             } else {
1.1221    raeburn  15251: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15252:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15253:                     $can_clone = 1;
1.1221    raeburn  15254:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15255:                     $can_clone = 1;
1.1225    raeburn  15256:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15257:                     $can_clone = 1;
1.1221    raeburn  15258:                 }
                   15259:                 unless ($can_clone) {
1.1225    raeburn  15260:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15261:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  15262:                         my (%gotdomdefaults,%gotcodedefaults);
                   15263:                         foreach my $cloner (@cloners) {
                   15264:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15265:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15266:                                 my (%codedefaults,@code_order);
                   15267:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15268:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15269:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15270:                                     }
                   15271:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15272:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15273:                                     }
                   15274:                                 } else {
                   15275:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15276:                                                                             \%codedefaults,
                   15277:                                                                             \@code_order);
                   15278:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15279:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15280:                                 }
                   15281:                                 if (@code_order > 0) {
                   15282:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15283:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15284:                                                                                 $args->{'crscode'})) {
                   15285:                                         $can_clone = 1;
                   15286:                                         last;
                   15287:                                     }
                   15288:                                 }
                   15289:                             }
                   15290:                         }
                   15291:                     }
1.1225    raeburn  15292:                 }
                   15293:             }
                   15294:             unless ($can_clone) {
                   15295:                 my $ccrole = 'cc';
                   15296:                 if ($args->{'crstype'} eq 'Community') {
                   15297:                     $ccrole = 'co';
                   15298:                 }
                   15299: 	        my %roleshash =
                   15300: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15301: 					          $args->{'ccdomain'},
                   15302:                                                   'userroles',['active'],[$ccrole],
                   15303: 					          [$args->{'clonedomain'}]);
                   15304: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15305:                     $can_clone = 1;
                   15306:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15307:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15308:                     $can_clone = 1;
1.1221    raeburn  15309:                 }
                   15310:             }
                   15311:             unless ($can_clone) {
                   15312:                 if ($args->{'crstype'} eq 'Community') {
                   15313:                     $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  15314:                 } else {
1.1221    raeburn  15315:                     $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'});
                   15316:                 }
1.566     albertel 15317: 	    }
1.578     raeburn  15318:         }
1.566     albertel 15319:     }
                   15320:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15321: }
                   15322: 
1.444     albertel 15323: sub construct_course {
1.1262    raeburn  15324:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15325:         $cnum,$category,$coderef) = @_;
1.444     albertel 15326:     my $outcome;
1.541     raeburn  15327:     my $linefeed =  '<br />'."\n";
                   15328:     if ($context eq 'auto') {
                   15329:         $linefeed = "\n";
                   15330:     }
1.566     albertel 15331: 
                   15332: #
                   15333: # Are we cloning?
                   15334: #
                   15335:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15336:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15337: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15338: 	if ($context ne 'auto') {
1.578     raeburn  15339:             if ($clonemsg ne '') {
                   15340: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15341:             }
1.566     albertel 15342: 	}
                   15343: 	$outcome .= $clonemsg.$linefeed;
                   15344: 
                   15345:         if (!$can_clone) {
                   15346: 	    return (0,$outcome);
                   15347: 	}
                   15348:     }
                   15349: 
1.444     albertel 15350: #
                   15351: # Open course
                   15352: #
1.1239    raeburn  15353:     my $showncrstype;
                   15354:     if ($args->{'crstype'} eq 'Placement') {
                   15355:         $showncrstype = 'placement test'; 
                   15356:     } else {  
                   15357:         $showncrstype = lc($args->{'crstype'});
                   15358:     }
1.444     albertel 15359:     my %cenv=();
                   15360:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15361:                                              $args->{'cdescr'},
                   15362:                                              $args->{'curl'},
                   15363:                                              $args->{'course_home'},
                   15364:                                              $args->{'nonstandard'},
                   15365:                                              $args->{'crscode'},
                   15366:                                              $args->{'ccuname'}.':'.
                   15367:                                              $args->{'ccdomain'},
1.882     raeburn  15368:                                              $args->{'crstype'},
1.885     raeburn  15369:                                              $cnum,$context,$category);
1.444     albertel 15370: 
                   15371:     # Note: The testing routines depend on this being output; see 
                   15372:     # Utils::Course. This needs to at least be output as a comment
                   15373:     # if anyone ever decides to not show this, and Utils::Course::new
                   15374:     # will need to be suitably modified.
1.1239    raeburn  15375:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
1.943     raeburn  15376:     if ($$courseid =~ /^error:/) {
                   15377:         return (0,$outcome);
                   15378:     }
                   15379: 
1.444     albertel 15380: #
                   15381: # Check if created correctly
                   15382: #
1.479     albertel 15383:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15384:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15385:     if ($crsuhome eq 'no_host') {
                   15386:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15387:         return (0,$outcome);
                   15388:     }
1.541     raeburn  15389:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15390: 
1.444     albertel 15391: #
1.566     albertel 15392: # Do the cloning
                   15393: #   
                   15394:     if ($can_clone && $cloneid) {
1.1239    raeburn  15395: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
1.566     albertel 15396: 	if ($context ne 'auto') {
                   15397: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15398: 	}
                   15399: 	$outcome .= $clonemsg.$linefeed;
                   15400: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15401: # Copy all files
1.637     www      15402: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15403: # Restore URL
1.566     albertel 15404: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15405: # Restore title
1.566     albertel 15406: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15407: # Restore creation date, creator and creation context.
                   15408:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15409:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15410:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15411: # Mark as cloned
1.566     albertel 15412: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15413: # Need to clone grading mode
                   15414:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15415:         $cenv{'grading'}=$newenv{'grading'};
                   15416: # Do not clone these environment entries
                   15417:         &Apache::lonnet::del('environment',
                   15418:                   ['default_enrollment_start_date',
                   15419:                    'default_enrollment_end_date',
                   15420:                    'question.email',
                   15421:                    'policy.email',
                   15422:                    'comment.email',
                   15423:                    'pch.users.denied',
1.725     raeburn  15424:                    'plc.users.denied',
                   15425:                    'hidefromcat',
1.1121    raeburn  15426:                    'checkforpriv',
1.1166    raeburn  15427:                    'categories',
                   15428:                    'internal.uniquecode'],
1.638     www      15429:                    $$crsudom,$$crsunum);
1.1170    raeburn  15430:         if ($args->{'textbook'}) {
                   15431:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15432:         }
1.444     albertel 15433:     }
1.566     albertel 15434: 
1.444     albertel 15435: #
                   15436: # Set environment (will override cloned, if existing)
                   15437: #
                   15438:     my @sections = ();
                   15439:     my @xlists = ();
                   15440:     if ($args->{'crstype'}) {
                   15441:         $cenv{'type'}=$args->{'crstype'};
                   15442:     }
                   15443:     if ($args->{'crsid'}) {
                   15444:         $cenv{'courseid'}=$args->{'crsid'};
                   15445:     }
                   15446:     if ($args->{'crscode'}) {
                   15447:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15448:     }
                   15449:     if ($args->{'crsquota'} ne '') {
                   15450:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15451:     } else {
                   15452:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15453:     }
                   15454:     if ($args->{'ccuname'}) {
                   15455:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15456:                                         ':'.$args->{'ccdomain'};
                   15457:     } else {
                   15458:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15459:     }
1.1116    raeburn  15460:     if ($args->{'defaultcredits'}) {
                   15461:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15462:     }
1.444     albertel 15463:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15464:     if ($args->{'crssections'}) {
                   15465:         $cenv{'internal.sectionnums'} = '';
                   15466:         if ($args->{'crssections'} =~ m/,/) {
                   15467:             @sections = split/,/,$args->{'crssections'};
                   15468:         } else {
                   15469:             $sections[0] = $args->{'crssections'};
                   15470:         }
                   15471:         if (@sections > 0) {
                   15472:             foreach my $item (@sections) {
                   15473:                 my ($sec,$gp) = split/:/,$item;
                   15474:                 my $class = $args->{'crscode'}.$sec;
                   15475:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15476:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15477:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15478:                     push(@badclasses,$class);
1.444     albertel 15479:                 }
                   15480:             }
                   15481:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15482:         }
                   15483:     }
                   15484: # do not hide course coordinator from staff listing, 
                   15485: # even if privileged
                   15486:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  15487: # add course coordinator's domain to domains to check for privileged users
                   15488: # if different to course domain
                   15489:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15490:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15491:     }
1.444     albertel 15492: # add crosslistings
                   15493:     if ($args->{'crsxlist'}) {
                   15494:         $cenv{'internal.crosslistings'}='';
                   15495:         if ($args->{'crsxlist'} =~ m/,/) {
                   15496:             @xlists = split/,/,$args->{'crsxlist'};
                   15497:         } else {
                   15498:             $xlists[0] = $args->{'crsxlist'};
                   15499:         }
                   15500:         if (@xlists > 0) {
                   15501:             foreach my $item (@xlists) {
                   15502:                 my ($xl,$gp) = split/:/,$item;
                   15503:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15504:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15505:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15506:                     push(@badclasses,$xl);
1.444     albertel 15507:                 }
                   15508:             }
                   15509:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15510:         }
                   15511:     }
                   15512:     if ($args->{'autoadds'}) {
                   15513:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15514:     }
                   15515:     if ($args->{'autodrops'}) {
                   15516:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15517:     }
                   15518: # check for notification of enrollment changes
                   15519:     my @notified = ();
                   15520:     if ($args->{'notify_owner'}) {
                   15521:         if ($args->{'ccuname'} ne '') {
                   15522:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15523:         }
                   15524:     }
                   15525:     if ($args->{'notify_dc'}) {
                   15526:         if ($uname ne '') { 
1.630     raeburn  15527:             push(@notified,$uname.':'.$udom);
1.444     albertel 15528:         }
                   15529:     }
                   15530:     if (@notified > 0) {
                   15531:         my $notifylist;
                   15532:         if (@notified > 1) {
                   15533:             $notifylist = join(',',@notified);
                   15534:         } else {
                   15535:             $notifylist = $notified[0];
                   15536:         }
                   15537:         $cenv{'internal.notifylist'} = $notifylist;
                   15538:     }
                   15539:     if (@badclasses > 0) {
                   15540:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  15541:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15542:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15543:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15544:         );
1.1264    raeburn  15545:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15546:                            &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  15547:         if ($context eq 'auto') {
                   15548:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  15549:         } else {
1.566     albertel 15550:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  15551:         }
                   15552:         foreach my $item (@badclasses) {
1.541     raeburn  15553:             if ($context eq 'auto') {
1.1261    raeburn  15554:                 $outcome .= " - $item\n";
1.541     raeburn  15555:             } else {
1.1261    raeburn  15556:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15557:             }
1.1261    raeburn  15558:         }
                   15559:         if ($context eq 'auto') {
                   15560:             $outcome .= $linefeed;
                   15561:         } else {
                   15562:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  15563:         } 
1.444     albertel 15564:     }
                   15565:     if ($args->{'no_end_date'}) {
                   15566:         $args->{'endaccess'} = 0;
                   15567:     }
                   15568:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15569:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15570:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15571:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15572:     if ($args->{'showphotos'}) {
                   15573:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15574:     }
                   15575:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15576:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15577:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15578:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15579:             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'); 
                   15580:             if ($context eq 'auto') {
                   15581:                 $outcome .= $krb_msg;
                   15582:             } else {
1.566     albertel 15583:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15584:             }
                   15585:             $outcome .= $linefeed;
1.444     albertel 15586:         }
                   15587:     }
                   15588:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15589:        if ($args->{'setpolicy'}) {
                   15590:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15591:        }
                   15592:        if ($args->{'setcontent'}) {
                   15593:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15594:        }
1.1251    raeburn  15595:        if ($args->{'setcomment'}) {
                   15596:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15597:        }
1.444     albertel 15598:     }
                   15599:     if ($args->{'reshome'}) {
                   15600: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15601: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15602:     }
                   15603: #
                   15604: # course has keyed access
                   15605: #
                   15606:     if ($args->{'setkeys'}) {
                   15607:        $cenv{'keyaccess'}='yes';
                   15608:     }
                   15609: # if specified, key authority is not course, but user
                   15610: # only active if keyaccess is yes
                   15611:     if ($args->{'keyauth'}) {
1.487     albertel 15612: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15613: 	$user = &LONCAPA::clean_username($user);
                   15614: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15615: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15616: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15617: 	}
                   15618:     }
                   15619: 
1.1166    raeburn  15620: #
1.1167    raeburn  15621: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  15622: #
                   15623:     if ($args->{'uniquecode'}) {
                   15624:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15625:         if ($code) {
                   15626:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  15627:             my %crsinfo =
                   15628:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15629:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15630:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15631:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15632:             } 
1.1166    raeburn  15633:             if (ref($coderef)) {
                   15634:                 $$coderef = $code;
                   15635:             }
                   15636:         }
                   15637:     }
                   15638: 
1.444     albertel 15639:     if ($args->{'disresdis'}) {
                   15640:         $cenv{'pch.roles.denied'}='st';
                   15641:     }
                   15642:     if ($args->{'disablechat'}) {
                   15643:         $cenv{'plc.roles.denied'}='st';
                   15644:     }
                   15645: 
                   15646:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15647:     # course
                   15648:     $cenv{'course.helper.not.run'} = 1;
                   15649:     #
                   15650:     # Use new Randomseed
                   15651:     #
                   15652:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15653:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15654:     #
                   15655:     # The encryption code and receipt prefix for this course
                   15656:     #
                   15657:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15658:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15659:     #
                   15660:     # By default, use standard grading
                   15661:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15662: 
1.541     raeburn  15663:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15664:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15665: #
                   15666: # Open all assignments
                   15667: #
                   15668:     if ($args->{'openall'}) {
                   15669:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15670:        my %storecontent = ($storeunder         => time,
                   15671:                            $storeunder.'.type' => 'date_start');
                   15672:        
                   15673:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15674:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15675:    }
                   15676: #
                   15677: # Set first page
                   15678: #
                   15679:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15680: 	    || ($cloneid)) {
1.445     albertel 15681: 	use LONCAPA::map;
1.444     albertel 15682: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15683: 
                   15684: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15685:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15686: 
1.444     albertel 15687:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15688:         my $title; my $url;
                   15689:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15690: 	    $title=&mt('Syllabus');
1.444     albertel 15691:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15692:         } else {
1.963     raeburn  15693:             $title=&mt('Table of Contents');
1.444     albertel 15694:             $url='/adm/navmaps';
                   15695:         }
1.445     albertel 15696: 
                   15697:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15698: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15699: 
                   15700: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15701:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15702:     }
1.566     albertel 15703: 
1.1237    raeburn  15704: # 
                   15705: # Set params for Placement Tests
                   15706: #
1.1239    raeburn  15707:     if ($args->{'crstype'} eq 'Placement') {
                   15708:        my %storecontent; 
                   15709:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   15710:        my %defaults = (
                   15711:                         buttonshide   => { value => 'yes',
                   15712:                                            type => 'string_yesno',},
                   15713:                         type          => { value => 'randomizetry',
                   15714:                                            type  => 'string_questiontype',},
                   15715:                         maxtries      => { value => 1,
                   15716:                                            type => 'int_pos',},
                   15717:                         problemstatus => { value => 'no',
                   15718:                                            type  => 'string_problemstatus',},
                   15719:                       );
                   15720:        foreach my $key (keys(%defaults)) {
                   15721:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   15722:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   15723:        }
1.1237    raeburn  15724:        &Apache::lonnet::cput
                   15725:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   15726:     }
                   15727: 
1.566     albertel 15728:     return (1,$outcome);
1.444     albertel 15729: }
                   15730: 
1.1166    raeburn  15731: sub make_unique_code {
                   15732:     my ($cdom,$cnum) = @_;
                   15733:     # get lock on uniquecodes db
                   15734:     my $lockhash = {
                   15735:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15736:                                                   ':'.$env{'user.domain'},
                   15737:                    };
                   15738:     my $tries = 0;
                   15739:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15740:     my ($code,$error);
                   15741:   
                   15742:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15743:         $tries ++;
                   15744:         sleep 1;
                   15745:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15746:     }
                   15747:     if ($gotlock eq 'ok') {
                   15748:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15749:         my $gotcode;
                   15750:         my $attempts = 0;
                   15751:         while ((!$gotcode) && ($attempts < 100)) {
                   15752:             $code = &generate_code();
                   15753:             if (!exists($currcodes{$code})) {
                   15754:                 $gotcode = 1;
                   15755:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15756:                     $error = 'nostore';
                   15757:                 }
                   15758:             }
                   15759:             $attempts ++;
                   15760:         }
                   15761:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15762:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15763:     } else {
                   15764:         $error = 'nolock';
                   15765:     }
                   15766:     return ($code,$error);
                   15767: }
                   15768: 
                   15769: sub generate_code {
                   15770:     my $code;
                   15771:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15772:     for (my $i=0; $i<6; $i++) {
                   15773:         my $lettnum = int (rand 2);
                   15774:         my $item = '';
                   15775:         if ($lettnum) {
                   15776:             $item = $letts[int( rand(18) )];
                   15777:         } else {
                   15778:             $item = 1+int( rand(8) );
                   15779:         }
                   15780:         $code .= $item;
                   15781:     }
                   15782:     return $code;
                   15783: }
                   15784: 
1.444     albertel 15785: ############################################################
                   15786: ############################################################
                   15787: 
1.1237    raeburn  15788: # Community, Course and Placement Test
1.378     raeburn  15789: sub course_type {
                   15790:     my ($cid) = @_;
                   15791:     if (!defined($cid)) {
                   15792:         $cid = $env{'request.course.id'};
                   15793:     }
1.404     albertel 15794:     if (defined($env{'course.'.$cid.'.type'})) {
                   15795:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15796:     } else {
                   15797:         return 'Course';
1.377     raeburn  15798:     }
                   15799: }
1.156     albertel 15800: 
1.406     raeburn  15801: sub group_term {
                   15802:     my $crstype = &course_type();
                   15803:     my %names = (
                   15804:                   'Course' => 'group',
1.865     raeburn  15805:                   'Community' => 'group',
1.1237    raeburn  15806:                   'Placement' => 'group',
1.406     raeburn  15807:                 );
                   15808:     return $names{$crstype};
                   15809: }
                   15810: 
1.902     raeburn  15811: sub course_types {
1.1237    raeburn  15812:     my @types = ('official','unofficial','community','textbook','placement');
1.902     raeburn  15813:     my %typename = (
                   15814:                          official   => 'Official course',
                   15815:                          unofficial => 'Unofficial course',
                   15816:                          community  => 'Community',
1.1165    raeburn  15817:                          textbook   => 'Textbook course',
1.1237    raeburn  15818:                          placement  => 'Placement test',
1.902     raeburn  15819:                    );
                   15820:     return (\@types,\%typename);
                   15821: }
                   15822: 
1.156     albertel 15823: sub icon {
                   15824:     my ($file)=@_;
1.505     albertel 15825:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15826:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15827:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15828:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15829: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15830: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15831: 	            $curfext.".gif") {
                   15832: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15833: 		$curfext.".gif";
                   15834: 	}
                   15835:     }
1.249     albertel 15836:     return &lonhttpdurl($iconname);
1.154     albertel 15837: } 
1.84      albertel 15838: 
1.575     albertel 15839: sub lonhttpdurl {
1.692     www      15840: #
                   15841: # Had been used for "small fry" static images on separate port 8080.
                   15842: # Modify here if lightweight http functionality desired again.
                   15843: # Currently eliminated due to increasing firewall issues.
                   15844: #
1.575     albertel 15845:     my ($url)=@_;
1.692     www      15846:     return $url;
1.215     albertel 15847: }
                   15848: 
1.213     albertel 15849: sub connection_aborted {
                   15850:     my ($r)=@_;
                   15851:     $r->print(" ");$r->rflush();
                   15852:     my $c = $r->connection;
                   15853:     return $c->aborted();
                   15854: }
                   15855: 
1.221     foxr     15856: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15857: #    strings as 'strings'.
                   15858: sub escape_single {
1.221     foxr     15859:     my ($input) = @_;
1.223     albertel 15860:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15861:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15862:     return $input;
                   15863: }
1.223     albertel 15864: 
1.222     foxr     15865: #  Same as escape_single, but escape's "'s  This 
                   15866: #  can be used for  "strings"
                   15867: sub escape_double {
                   15868:     my ($input) = @_;
                   15869:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15870:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15871:     return $input;
                   15872: }
1.223     albertel 15873:  
1.222     foxr     15874: #   Escapes the last element of a full URL.
                   15875: sub escape_url {
                   15876:     my ($url)   = @_;
1.238     raeburn  15877:     my @urlslices = split(/\//, $url,-1);
1.369     www      15878:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  15879:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15880: }
1.462     albertel 15881: 
1.820     raeburn  15882: sub compare_arrays {
                   15883:     my ($arrayref1,$arrayref2) = @_;
                   15884:     my (@difference,%count);
                   15885:     @difference = ();
                   15886:     %count = ();
                   15887:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15888:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15889:         foreach my $element (keys(%count)) {
                   15890:             if ($count{$element} == 1) {
                   15891:                 push(@difference,$element);
                   15892:             }
                   15893:         }
                   15894:     }
                   15895:     return @difference;
                   15896: }
                   15897: 
1.817     bisitz   15898: # -------------------------------------------------------- Initialize user login
1.462     albertel 15899: sub init_user_environment {
1.463     albertel 15900:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15901:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15902: 
                   15903:     my $public=($username eq 'public' && $domain eq 'public');
                   15904: 
                   15905: # See if old ID present, if so, remove
                   15906: 
1.1062    raeburn  15907:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15908:     my $now=time;
                   15909: 
                   15910:     if ($public) {
                   15911: 	my $max_public=100;
                   15912: 	my $oldest;
                   15913: 	my $oldest_time=0;
                   15914: 	for(my $next=1;$next<=$max_public;$next++) {
                   15915: 	    if (-e $lonids."/publicuser_$next.id") {
                   15916: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15917: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15918: 		    $oldest_time=$mtime;
                   15919: 		    $oldest=$next;
                   15920: 		}
                   15921: 	    } else {
                   15922: 		$cookie="publicuser_$next";
                   15923: 		last;
                   15924: 	    }
                   15925: 	}
                   15926: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15927:     } else {
1.463     albertel 15928: 	# if this isn't a robot, kill any existing non-robot sessions
                   15929: 	if (!$args->{'robot'}) {
                   15930: 	    opendir(DIR,$lonids);
                   15931: 	    while ($filename=readdir(DIR)) {
                   15932: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   15933: 		    unlink($lonids.'/'.$filename);
                   15934: 		}
1.462     albertel 15935: 	    }
1.463     albertel 15936: 	    closedir(DIR);
1.1204    raeburn  15937: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15938:             my $namespace = 'nohist_courseeditor';
                   15939:             my $lockingkey = 'paste'."\0".'locked_num';
                   15940:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15941:                                                 $domain,$username);
                   15942:             if (exists($lockhash{$lockingkey})) {
                   15943:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15944:                 unless ($delresult eq 'ok') {
                   15945:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15946:                 }
                   15947:             }
1.462     albertel 15948: 	}
                   15949: # Give them a new cookie
1.463     albertel 15950: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15951: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15952: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15953:     
                   15954: # Initialize roles
                   15955: 
1.1062    raeburn  15956: 	($userroles,$firstaccenv,$timerintenv) = 
                   15957:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15958:     }
                   15959: # ------------------------------------ Check browser type and MathML capability
                   15960: 
1.1194    raeburn  15961:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15962:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15963: 
                   15964: # ------------------------------------------------------------- Get environment
                   15965: 
                   15966:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15967:     my ($tmp) = keys(%userenv);
                   15968:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15969:     } else {
                   15970: 	undef(%userenv);
                   15971:     }
                   15972:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15973: 	$form->{'interface'}=$userenv{'interface'};
                   15974:     }
                   15975:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15976: 
                   15977: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15978:     foreach my $option ('interface','localpath','localres') {
                   15979:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15980:     }
                   15981: # --------------------------------------------------------- Write first profile
                   15982: 
                   15983:     {
                   15984: 	my %initial_env = 
                   15985: 	    ("user.name"          => $username,
                   15986: 	     "user.domain"        => $domain,
                   15987: 	     "user.home"          => $authhost,
                   15988: 	     "browser.type"       => $clientbrowser,
                   15989: 	     "browser.version"    => $clientversion,
                   15990: 	     "browser.mathml"     => $clientmathml,
                   15991: 	     "browser.unicode"    => $clientunicode,
                   15992: 	     "browser.os"         => $clientos,
1.1137    raeburn  15993:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  15994:              "browser.info"       => $clientinfo,
1.1194    raeburn  15995:              "browser.osversion"  => $clientosversion,
1.462     albertel 15996: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15997: 	     "request.course.fn"  => '',
                   15998: 	     "request.course.uri" => '',
                   15999: 	     "request.course.sec" => '',
                   16000: 	     "request.role"       => 'cm',
                   16001: 	     "request.role.adv"   => $env{'user.adv'},
                   16002: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   16003: 
                   16004:         if ($form->{'localpath'}) {
                   16005: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16006: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16007:         }
                   16008: 	
                   16009: 	if ($form->{'interface'}) {
                   16010: 	    $form->{'interface'}=~s/\W//gs;
                   16011: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16012: 	    $env{'browser.interface'}=$form->{'interface'};
                   16013: 	}
                   16014: 
1.1157    raeburn  16015:         if ($form->{'iptoken'}) {
                   16016:             my $lonhost = $r->dir_config('lonHostID');
                   16017:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16018:             $env{'user.noloadbalance'} = $lonhost;
                   16019:         }
                   16020: 
1.1268    raeburn  16021:         if ($form->{'noloadbalance'}) {
                   16022:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16023:             my $hosthere = $form->{'noloadbalance'};
                   16024:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16025:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16026:                 $env{'user.noloadbalance'} = $hosthere;
                   16027:             }
                   16028:         }
                   16029: 
1.981     raeburn  16030:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  16031:         my %domdef;
                   16032:         unless ($domain eq 'public') {
                   16033:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   16034:         }
1.980     raeburn  16035: 
1.1081    raeburn  16036:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  16037:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  16038:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16039:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  16040:         }
                   16041: 
1.1237    raeburn  16042:         foreach my $crstype ('official','unofficial','community','textbook','placement') {
1.765     raeburn  16043:             $userenv{'canrequest.'.$crstype} =
                   16044:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  16045:                                                   'reload','requestcourses',
                   16046:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  16047:         }
                   16048: 
1.1092    raeburn  16049:         $userenv{'canrequest.author'} =
                   16050:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16051:                                         'reload','requestauthor',
                   16052:                                         \%userenv,\%domdef,\%is_adv);
                   16053:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16054:                                              $domain,$username);
                   16055:         my $reqstatus = $reqauthor{'author_status'};
                   16056:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   16057:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   16058:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16059:                                                   $reqauthor{'author'}{'timestamp'};
                   16060:             }
                   16061:         }
                   16062: 
1.462     albertel 16063: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16064: 
1.462     albertel 16065: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16066: 		 &GDBM_WRCREAT(),0640)) {
                   16067: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16068: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16069: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16070:             if (ref($firstaccenv) eq 'HASH') {
                   16071:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16072:             }
                   16073:             if (ref($timerintenv) eq 'HASH') {
                   16074:                 &_add_to_env(\%disk_env,$timerintenv);
                   16075:             }
1.463     albertel 16076: 	    if (ref($args->{'extra_env'})) {
                   16077: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16078: 	    }
1.462     albertel 16079: 	    untie(%disk_env);
                   16080: 	} else {
1.705     tempelho 16081: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16082: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16083: 	    return 'error: '.$!;
                   16084: 	}
                   16085:     }
                   16086:     $env{'request.role'}='cm';
                   16087:     $env{'request.role.adv'}=$env{'user.adv'};
                   16088:     $env{'browser.type'}=$clientbrowser;
                   16089: 
                   16090:     return $cookie;
                   16091: 
                   16092: }
                   16093: 
                   16094: sub _add_to_env {
                   16095:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16096:     if (ref($env_data) eq 'HASH') {
                   16097:         while (my ($key,$value) = each(%$env_data)) {
                   16098: 	    $idf->{$prefix.$key} = $value;
                   16099: 	    $env{$prefix.$key}   = $value;
                   16100:         }
1.462     albertel 16101:     }
                   16102: }
                   16103: 
1.685     tempelho 16104: # --- Get the symbolic name of a problem and the url
                   16105: sub get_symb {
                   16106:     my ($request,$silent) = @_;
1.726     raeburn  16107:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16108:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16109:     if ($symb eq '') {
                   16110:         if (!$silent) {
1.1071    raeburn  16111:             if (ref($request)) { 
                   16112:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16113:             }
1.685     tempelho 16114:             return ();
                   16115:         }
                   16116:     }
                   16117:     &Apache::lonenc::check_decrypt(\$symb);
                   16118:     return ($symb);
                   16119: }
                   16120: 
                   16121: # --------------------------------------------------------------Get annotation
                   16122: 
                   16123: sub get_annotation {
                   16124:     my ($symb,$enc) = @_;
                   16125: 
                   16126:     my $key = $symb;
                   16127:     if (!$enc) {
                   16128:         $key =
                   16129:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16130:     }
                   16131:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16132:     return $annotation{$key};
                   16133: }
                   16134: 
                   16135: sub clean_symb {
1.731     raeburn  16136:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16137: 
                   16138:     &Apache::lonenc::check_decrypt(\$symb);
                   16139:     my $enc = $env{'request.enc'};
1.731     raeburn  16140:     if ($delete_enc) {
1.730     raeburn  16141:         delete($env{'request.enc'});
                   16142:     }
1.685     tempelho 16143: 
                   16144:     return ($symb,$enc);
                   16145: }
1.462     albertel 16146: 
1.1181    raeburn  16147: ############################################################
                   16148: ############################################################
                   16149: 
                   16150: =pod
                   16151: 
                   16152: =head1 Routines for building display used to search for courses
                   16153: 
                   16154: 
                   16155: =over 4
                   16156: 
                   16157: =item * &build_filters()
                   16158: 
                   16159: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  16160: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16161: and quotacheck.pl
                   16162: 
1.1181    raeburn  16163: 
                   16164: Inputs:
                   16165: 
                   16166: filterlist - anonymous array of fields to include as potential filters 
                   16167: 
                   16168: crstype - course type
                   16169: 
                   16170: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16171:               to pop-open a course selector (will contain "extra element"). 
                   16172: 
                   16173: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16174: 
                   16175: filter - anonymous hash of criteria and their values
                   16176: 
                   16177: action - form action
                   16178: 
                   16179: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16180: 
1.1182    raeburn  16181: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  16182: 
                   16183: cloneruname - username of owner of new course who wants to clone
                   16184: 
                   16185: clonerudom - domain of owner of new course who wants to clone
                   16186: 
                   16187: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   16188: 
                   16189: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16190: 
                   16191: codedom - domain
                   16192: 
                   16193: formname - value of form element named "form". 
                   16194: 
                   16195: fixeddom - domain, if fixed.
                   16196: 
                   16197: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   16198: 
                   16199: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   16200: 
                   16201: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16202: 
                   16203: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16204: 
                   16205: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16206: 
                   16207: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16208: 
                   16209: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16210: 
1.1182    raeburn  16211: 
1.1181    raeburn  16212: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16213: 
1.1182    raeburn  16214: 
1.1181    raeburn  16215: Side Effects: None
                   16216: 
                   16217: =cut
                   16218: 
                   16219: # ---------------------------------------------- search for courses based on last activity etc.
                   16220: 
                   16221: sub build_filters {
                   16222:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16223:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16224:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16225:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16226:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  16227:     my ($list,$jscript);
1.1181    raeburn  16228:     my $onchange = 'javascript:updateFilters(this)';
                   16229:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16230:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16231:         $typeselectform,$instcodetitle);
                   16232:     if ($formname eq '') {
                   16233:         $formname = $caller;
                   16234:     }
                   16235:     foreach my $item (@{$filterlist}) {
                   16236:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16237:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16238:             if ($item eq 'domainfilter') {
                   16239:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16240:             } elsif ($item eq 'coursefilter') {
                   16241:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16242:             } elsif ($item eq 'ownerfilter') {
                   16243:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16244:             } elsif ($item eq 'ownerdomfilter') {
                   16245:                 $filter->{'ownerdomfilter'} =
                   16246:                     &LONCAPA::clean_domain($filter->{$item});
                   16247:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16248:                                                        'ownerdomfilter',1);
                   16249:             } elsif ($item eq 'personfilter') {
                   16250:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16251:             } elsif ($item eq 'persondomfilter') {
                   16252:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16253:                                                         'persondomfilter',1);
                   16254:             } else {
                   16255:                 $filter->{$item} =~ s/\W//g;
                   16256:             }
                   16257:             if (!$filter->{$item}) {
                   16258:                 $filter->{$item} = '';
                   16259:             }
                   16260:         }
                   16261:         if ($item eq 'domainfilter') {
                   16262:             my $allow_blank = 1;
                   16263:             if ($formname eq 'portform') {
                   16264:                 $allow_blank=0;
                   16265:             } elsif ($formname eq 'studentform') {
                   16266:                 $allow_blank=0;
                   16267:             }
                   16268:             if ($fixeddom) {
                   16269:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16270:                                     ' value="'.$codedom.'" />'.
                   16271:                                     &Apache::lonnet::domain($codedom,'description');
                   16272:             } else {
                   16273:                 $domainselectform = &select_dom_form($filter->{$item},
                   16274:                                                      'domainfilter',
                   16275:                                                       $allow_blank,'',$onchange);
                   16276:             }
                   16277:         } else {
                   16278:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16279:         }
                   16280:     }
                   16281: 
                   16282:     # last course activity filter and selection
                   16283:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16284: 
                   16285:     # course created filter and selection
                   16286:     if (exists($filter->{'createdfilter'})) {
                   16287:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16288:     }
                   16289: 
1.1239    raeburn  16290:     my $prefix = $crstype;
                   16291:     if ($crstype eq 'Placement') {
                   16292:         $prefix = 'Placement Test'
                   16293:     }
1.1181    raeburn  16294:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  16295:                 'cac' => "$prefix Activity",
                   16296:                 'ccr' => "$prefix Created",
                   16297:                 'cde' => "$prefix Title",
                   16298:                 'cdo' => "$prefix Domain",
1.1181    raeburn  16299:                 'ins' => 'Institutional Code',
                   16300:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  16301:                 'cow' => "$prefix Owner/Co-owner",
                   16302:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  16303:                 'cog' => 'Type',
                   16304:              );
                   16305: 
                   16306:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16307:         my $typeval = 'Course';
                   16308:         if ($crstype eq 'Community') {
                   16309:             $typeval = 'Community';
1.1239    raeburn  16310:         } elsif ($crstype eq 'Placement') {
                   16311:             $typeval = 'Placement';
1.1181    raeburn  16312:         }
                   16313:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16314:     } else {
                   16315:         $typeselectform =  '<select name="type" size="1"';
                   16316:         if ($onchange) {
                   16317:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16318:         }
                   16319:         $typeselectform .= '>'."\n";
1.1237    raeburn  16320:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  16321:             my $shown;
                   16322:             if ($posstype eq 'Placement') {
                   16323:                 $shown = &mt('Placement Test');
                   16324:             } else {
                   16325:                 $shown = &mt($posstype);
                   16326:             }
1.1181    raeburn  16327:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  16328:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  16329:         }
                   16330:         $typeselectform.="</select>";
                   16331:     }
                   16332: 
                   16333:     my ($cloneableonlyform,$cloneabletitle);
                   16334:     if (exists($filter->{'cloneableonly'})) {
                   16335:         my $cloneableon = '';
                   16336:         my $cloneableoff = ' checked="checked"';
                   16337:         if ($filter->{'cloneableonly'}) {
                   16338:             $cloneableon = $cloneableoff;
                   16339:             $cloneableoff = '';
                   16340:         }
                   16341:         $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>';
                   16342:         if ($formname eq 'ccrs') {
1.1187    bisitz   16343:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  16344:         } else {
                   16345:             $cloneabletitle = &mt('Cloneable by you');
                   16346:         }
                   16347:     }
                   16348:     my $officialjs;
                   16349:     if ($crstype eq 'Course') {
                   16350:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  16351: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16352: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16353:             if ($codedom) { 
1.1181    raeburn  16354:                 $officialjs = 1;
                   16355:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16356:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16357:                                                                   $officialjs,$codetitlesref);
                   16358:                 if ($jscript) {
1.1182    raeburn  16359:                     $jscript = '<script type="text/javascript">'."\n".
                   16360:                                '// <![CDATA['."\n".
                   16361:                                $jscript."\n".
                   16362:                                '// ]]>'."\n".
                   16363:                                '</script>'."\n";
1.1181    raeburn  16364:                 }
                   16365:             }
                   16366:             if ($instcodeform eq '') {
                   16367:                 $instcodeform =
                   16368:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16369:                     $list->{'instcodefilter'}.'" />';
                   16370:                 $instcodetitle = $lt{'ins'};
                   16371:             } else {
                   16372:                 $instcodetitle = $lt{'inc'};
                   16373:             }
                   16374:             if ($fixeddom) {
                   16375:                 $instcodetitle .= '<br />('.$codedom.')';
                   16376:             }
                   16377:         }
                   16378:     }
                   16379:     my $output = qq|
                   16380: <form method="post" name="filterpicker" action="$action">
                   16381: <input type="hidden" name="form" value="$formname" />
                   16382: |;
                   16383:     if ($formname eq 'modifycourse') {
                   16384:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16385:                    '<input type="hidden" name="prevphase" value="'.
                   16386:                    $prevphase.'" />'."\n";
1.1198    musolffc 16387:     } elsif ($formname eq 'quotacheck') {
                   16388:         $output .= qq|
                   16389: <input type="hidden" name="sortby" value="" />
                   16390: <input type="hidden" name="sortorder" value="" />
                   16391: |;
                   16392:     } else {
1.1181    raeburn  16393:         my $name_input;
                   16394:         if ($cnameelement ne '') {
                   16395:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16396:                           $cnameelement.'" />';
                   16397:         }
                   16398:         $output .= qq|
1.1182    raeburn  16399: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16400: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  16401: $name_input
                   16402: $roleelement
                   16403: $multelement
                   16404: $typeelement
                   16405: |;
                   16406:         if ($formname eq 'portform') {
                   16407:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16408:         }
                   16409:     }
                   16410:     if ($fixeddom) {
                   16411:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16412:     }
                   16413:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16414:     if ($sincefilterform) {
                   16415:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16416:                   .$sincefilterform
                   16417:                   .&Apache::lonhtmlcommon::row_closure();
                   16418:     }
                   16419:     if ($createdfilterform) {
                   16420:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16421:                   .$createdfilterform
                   16422:                   .&Apache::lonhtmlcommon::row_closure();
                   16423:     }
                   16424:     if ($domainselectform) {
                   16425:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16426:                   .$domainselectform
                   16427:                   .&Apache::lonhtmlcommon::row_closure();
                   16428:     }
                   16429:     if ($typeselectform) {
                   16430:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16431:             $output .= $typeselectform;
                   16432:         } else {
                   16433:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16434:                       .$typeselectform
                   16435:                       .&Apache::lonhtmlcommon::row_closure();
                   16436:         }
                   16437:     }
                   16438:     if ($instcodeform) {
                   16439:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16440:                   .$instcodeform
                   16441:                   .&Apache::lonhtmlcommon::row_closure();
                   16442:     }
                   16443:     if (exists($filter->{'ownerfilter'})) {
                   16444:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16445:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16446:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16447:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16448:                    $ownerdomselectform.'</td></tr></table>'.
                   16449:                    &Apache::lonhtmlcommon::row_closure();
                   16450:     }
                   16451:     if (exists($filter->{'personfilter'})) {
                   16452:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16453:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16454:                    '<input type="text" name="personfilter" size="20" value="'.
                   16455:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16456:                    $persondomselectform.'</td></tr></table>'.
                   16457:                    &Apache::lonhtmlcommon::row_closure();
                   16458:     }
                   16459:     if (exists($filter->{'coursefilter'})) {
                   16460:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16461:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16462:                   .$list->{'coursefilter'}.'" />'
                   16463:                   .&Apache::lonhtmlcommon::row_closure();
                   16464:     }
                   16465:     if ($cloneableonlyform) {
                   16466:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16467:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16468:     }
                   16469:     if (exists($filter->{'descriptfilter'})) {
                   16470:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16471:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16472:                   .$list->{'descriptfilter'}.'" />'
                   16473:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16474:     }
                   16475:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16476:                '<input type="hidden" name="updater" value="" />'."\n".
                   16477:                '<input type="submit" name="gosearch" value="'.
                   16478:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16479:     return $jscript.$clonewarning.$output;
                   16480: }
                   16481: 
                   16482: =pod 
                   16483: 
                   16484: =item * &timebased_select_form()
                   16485: 
1.1182    raeburn  16486: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  16487: filter e.g., Course Activity, Course Created, when searching for courses
                   16488: or communities
                   16489: 
                   16490: Inputs:
                   16491: 
                   16492: item - name of form element (sincefilter or createdfilter)
                   16493: 
                   16494: filter - anonymous hash of criteria and their values
                   16495: 
                   16496: Returns: HTML for a select box contained a blank, then six time selections,
                   16497:          with value set in incoming form variables currently selected. 
                   16498: 
                   16499: Side Effects: None
                   16500: 
                   16501: =cut
                   16502: 
                   16503: sub timebased_select_form {
                   16504:     my ($item,$filter) = @_;
                   16505:     if (ref($filter) eq 'HASH') {
                   16506:         $filter->{$item} =~ s/[^\d-]//g;
                   16507:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16508:         return &select_form(
                   16509:                             $filter->{$item},
                   16510:                             $item,
                   16511:                             {      '-1' => '',
                   16512:                                 '86400' => &mt('today'),
                   16513:                                '604800' => &mt('last week'),
                   16514:                               '2592000' => &mt('last month'),
                   16515:                               '7776000' => &mt('last three months'),
                   16516:                              '15552000' => &mt('last six months'),
                   16517:                              '31104000' => &mt('last year'),
                   16518:                     'select_form_order' =>
                   16519:                            ['-1','86400','604800','2592000','7776000',
                   16520:                             '15552000','31104000']});
                   16521:     }
                   16522: }
                   16523: 
                   16524: =pod
                   16525: 
                   16526: =item * &js_changer()
                   16527: 
                   16528: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  16529: when course type or domain is changed, and also to hide 'Searching ...' on
                   16530: page load completion for page showing search result.
1.1181    raeburn  16531: 
                   16532: Inputs: None
                   16533: 
1.1183    raeburn  16534: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  16535: 
                   16536: Side Effects: None
                   16537: 
                   16538: =cut
                   16539: 
                   16540: sub js_changer {
                   16541:     return <<ENDJS;
                   16542: <script type="text/javascript">
                   16543: // <![CDATA[
                   16544: function updateFilters(caller) {
                   16545:     if (typeof(caller) != "undefined") {
                   16546:         document.filterpicker.updater.value = caller.name;
                   16547:     }
                   16548:     document.filterpicker.submit();
                   16549: }
1.1183    raeburn  16550: 
                   16551: function hideSearching() {
                   16552:     if (document.getElementById('searching')) {
                   16553:         document.getElementById('searching').style.display = 'none';
                   16554:     }
                   16555:     return;
                   16556: }
                   16557: 
1.1181    raeburn  16558: // ]]>
                   16559: </script>
                   16560: 
                   16561: ENDJS
                   16562: }
                   16563: 
                   16564: =pod
                   16565: 
1.1182    raeburn  16566: =item * &search_courses()
                   16567: 
                   16568: Process selected filters form course search form and pass to lonnet::courseiddump
                   16569: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16570: 
                   16571: Inputs:
                   16572: 
                   16573: dom - domain being searched 
                   16574: 
                   16575: type - course type ('Course' or 'Community' or '.' if any).
                   16576: 
                   16577: filter - anonymous hash of criteria and their values
                   16578: 
                   16579: numtitles - for institutional codes - number of categories
                   16580: 
                   16581: cloneruname - optional username of new course owner
                   16582: 
                   16583: clonerudom - optional domain of new course owner
                   16584: 
1.1221    raeburn  16585: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  16586:             (used when DC is using course creation form)
                   16587: 
                   16588: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16589: 
1.1221    raeburn  16590: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16591:            (and so can clone automatically)
                   16592: 
                   16593: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16594: 
                   16595: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   16596:               courses to clone 
1.1182    raeburn  16597: 
                   16598: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16599: 
                   16600: 
                   16601: Side Effects: None
                   16602: 
                   16603: =cut
                   16604: 
                   16605: 
                   16606: sub search_courses {
1.1221    raeburn  16607:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16608:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  16609:     my (%courses,%showcourses,$cloner);
                   16610:     if (($filter->{'ownerfilter'} ne '') ||
                   16611:         ($filter->{'ownerdomfilter'} ne '')) {
                   16612:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16613:                                        $filter->{'ownerdomfilter'};
                   16614:     }
                   16615:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16616:         if (!$filter->{$item}) {
                   16617:             $filter->{$item}='.';
                   16618:         }
                   16619:     }
                   16620:     my $now = time;
                   16621:     my $timefilter =
                   16622:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16623:     my ($createdbefore,$createdafter);
                   16624:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16625:         $createdbefore = $now;
                   16626:         $createdafter = $now-$filter->{'createdfilter'};
                   16627:     }
                   16628:     my ($instcodefilter,$regexpok);
                   16629:     if ($numtitles) {
                   16630:         if ($env{'form.official'} eq 'on') {
                   16631:             $instcodefilter =
                   16632:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16633:             $regexpok = 1;
                   16634:         } elsif ($env{'form.official'} eq 'off') {
                   16635:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16636:             unless ($instcodefilter eq '') {
                   16637:                 $regexpok = -1;
                   16638:             }
                   16639:         }
                   16640:     } else {
                   16641:         $instcodefilter = $filter->{'instcodefilter'};
                   16642:     }
                   16643:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16644:     if ($type eq '') { $type = '.'; }
                   16645: 
                   16646:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16647:         $cloner = $cloneruname.':'.$clonerudom;
                   16648:     }
                   16649:     %courses = &Apache::lonnet::courseiddump($dom,
                   16650:                                              $filter->{'descriptfilter'},
                   16651:                                              $timefilter,
                   16652:                                              $instcodefilter,
                   16653:                                              $filter->{'combownerfilter'},
                   16654:                                              $filter->{'coursefilter'},
                   16655:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  16656:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  16657:                                              $filter->{'cloneableonly'},
                   16658:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  16659:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  16660:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16661:         my $ccrole;
                   16662:         if ($type eq 'Community') {
                   16663:             $ccrole = 'co';
                   16664:         } else {
                   16665:             $ccrole = 'cc';
                   16666:         }
                   16667:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16668:                                                      $filter->{'persondomfilter'},
                   16669:                                                      'userroles',undef,
                   16670:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16671:                                                      $dom);
                   16672:         foreach my $role (keys(%rolehash)) {
                   16673:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16674:             my $cid = $cdom.'_'.$cnum;
                   16675:             if (exists($courses{$cid})) {
                   16676:                 if (ref($courses{$cid}) eq 'HASH') {
                   16677:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16678:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  16679:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  16680:                         }
                   16681:                     } else {
                   16682:                         $courses{$cid}{roles} = [$courserole];
                   16683:                     }
                   16684:                     $showcourses{$cid} = $courses{$cid};
                   16685:                 }
                   16686:             }
                   16687:         }
                   16688:         %courses = %showcourses;
                   16689:     }
                   16690:     return %courses;
                   16691: }
                   16692: 
                   16693: =pod
                   16694: 
1.1181    raeburn  16695: =back
                   16696: 
1.1207    raeburn  16697: =head1 Routines for version requirements for current course.
                   16698: 
                   16699: =over 4
                   16700: 
                   16701: =item * &check_release_required()
                   16702: 
                   16703: Compares required LON-CAPA version with version on server, and
                   16704: if required version is newer looks for a server with the required version.
                   16705: 
                   16706: Looks first at servers in user's owen domain; if none suitable, looks at
                   16707: servers in course's domain are permitted to host sessions for user's domain.
                   16708: 
                   16709: Inputs:
                   16710: 
                   16711: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16712: 
                   16713: $courseid - Course ID of current course
                   16714: 
                   16715: $rolecode - User's current role in course (for switchserver query string).
                   16716: 
                   16717: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16718: 
                   16719: 
                   16720: Returns:
                   16721: 
                   16722: $switchserver - query string tp append to /adm/switchserver call (if 
                   16723:                 current server's LON-CAPA version is too old. 
                   16724: 
                   16725: $warning - Message is displayed if no suitable server could be found.
                   16726: 
                   16727: =cut
                   16728: 
                   16729: sub check_release_required {
                   16730:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16731:     my ($switchserver,$warning);
                   16732:     if ($required ne '') {
                   16733:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16734:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16735:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16736:             my $otherserver;
                   16737:             if (($major eq '' && $minor eq '') ||
                   16738:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16739:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16740:                 my $switchlcrev =
                   16741:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16742:                                                            $userdomserver);
                   16743:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16744:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16745:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16746:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16747:                     if ($cdom ne $env{'user.domain'}) {
                   16748:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16749:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16750:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16751:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16752:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16753:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16754:                         my $canhost =
                   16755:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16756:                                                               $coursedomserver,
                   16757:                                                               $remoterev,
                   16758:                                                               $udomdefaults{'remotesessions'},
                   16759:                                                               $defdomdefaults{'hostedsessions'});
                   16760: 
                   16761:                         if ($canhost) {
                   16762:                             $otherserver = $coursedomserver;
                   16763:                         } else {
                   16764:                             $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.");
                   16765:                         }
                   16766:                     } else {
                   16767:                         $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).");
                   16768:                     }
                   16769:                 } else {
                   16770:                     $otherserver = $userdomserver;
                   16771:                 }
                   16772:             }
                   16773:             if ($otherserver ne '') {
                   16774:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16775:             }
                   16776:         }
                   16777:     }
                   16778:     return ($switchserver,$warning);
                   16779: }
                   16780: 
                   16781: =pod
                   16782: 
                   16783: =item * &check_release_result()
                   16784: 
                   16785: Inputs:
                   16786: 
                   16787: $switchwarning - Warning message if no suitable server found to host session.
                   16788: 
                   16789: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16790:                 and current role.
                   16791: 
                   16792: Returns: HTML to display with information about requirement to switch server.
                   16793:          Either displaying warning with link to Roles/Courses screen or
                   16794:          display link to switchserver.
                   16795: 
1.1181    raeburn  16796: =cut
                   16797: 
1.1207    raeburn  16798: sub check_release_result {
                   16799:     my ($switchwarning,$switchserver) = @_;
                   16800:     my $output = &start_page('Selected course unavailable on this server').
                   16801:                  '<p class="LC_warning">';
                   16802:     if ($switchwarning) {
                   16803:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16804:         if (&show_course()) {
                   16805:             $output .= &mt('Display courses');
                   16806:         } else {
                   16807:             $output .= &mt('Display roles');
                   16808:         }
                   16809:         $output .= '</a>';
                   16810:     } elsif ($switchserver) {
                   16811:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16812:                    '<br />'.
                   16813:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16814:                    &mt('Switch Server').
                   16815:                    '</a>';
                   16816:     }
                   16817:     $output .= '</p>'.&end_page();
                   16818:     return $output;
                   16819: }
                   16820: 
                   16821: =pod
                   16822: 
                   16823: =item * &needs_coursereinit()
                   16824: 
                   16825: Determine if course contents stored for user's session needs to be
                   16826: refreshed, because content has changed since "Big Hash" last tied.
                   16827: 
                   16828: Check for change is made if time last checked is more than 10 minutes ago
                   16829: (by default).
                   16830: 
                   16831: Inputs:
                   16832: 
                   16833: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16834: 
                   16835: $interval (optional) - Time which may elapse (in s) between last check for content
                   16836:                        change in current course. (default: 600 s).  
                   16837: 
                   16838: Returns: an array; first element is:
                   16839: 
                   16840: =over 4
                   16841: 
                   16842: 'switch' - if content updates mean user's session
                   16843:            needs to be switched to a server running a newer LON-CAPA version
                   16844:  
                   16845: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16846:            on current server hosting user's session                
                   16847: 
                   16848: ''       - if no action required.
                   16849: 
                   16850: =back
                   16851: 
                   16852: If first item element is 'switch':
                   16853: 
                   16854: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   16855: 
                   16856: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16857:                               and current role. 
                   16858: 
                   16859: otherwise: no other elements returned.
                   16860: 
                   16861: =back
                   16862: 
                   16863: =cut
                   16864: 
                   16865: sub needs_coursereinit {
                   16866:     my ($loncaparev,$interval) = @_;
                   16867:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16868:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16869:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16870:     my $now = time;
                   16871:     if ($interval eq '') {
                   16872:         $interval = 600;
                   16873:     }
                   16874:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16875:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16876:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16877:         if ($lastchange > $env{'request.course.tied'}) {
                   16878:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16879:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16880:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16881:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16882:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16883:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16884:                     my ($switchserver,$switchwarning) =
                   16885:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16886:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16887:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16888:                         return ('switch',$switchwarning,$switchserver);
                   16889:                     }
                   16890:                 }
                   16891:             }
                   16892:             return ('update');
                   16893:         }
                   16894:     }
                   16895:     return ();
                   16896: }
1.1181    raeburn  16897: 
1.1083    raeburn  16898: sub update_content_constraints {
                   16899:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16900:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16901:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16902:     my %checkresponsetypes;
                   16903:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  16904:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  16905:         if ($item eq 'resourcetag') {
                   16906:             if ($name eq 'responsetype') {
                   16907:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16908:             }
                   16909:         }
                   16910:     }
                   16911:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16912:     if (defined($navmap)) {
                   16913:         my %allresponses;
                   16914:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16915:             my %responses = $res->responseTypes();
                   16916:             foreach my $key (keys(%responses)) {
                   16917:                 next unless(exists($checkresponsetypes{$key}));
                   16918:                 $allresponses{$key} += $responses{$key};
                   16919:             }
                   16920:         }
                   16921:         foreach my $key (keys(%allresponses)) {
                   16922:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16923:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16924:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16925:             }
                   16926:         }
                   16927:         undef($navmap);
                   16928:     }
                   16929:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16930:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16931:     }
                   16932:     return;
                   16933: }
                   16934: 
1.1110    raeburn  16935: sub allmaps_incourse {
                   16936:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16937:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16938:         $cid = $env{'request.course.id'};
                   16939:         $cdom = $env{'course.'.$cid.'.domain'};
                   16940:         $cnum = $env{'course.'.$cid.'.num'};
                   16941:         $chome = $env{'course.'.$cid.'.home'};
                   16942:     }
                   16943:     my %allmaps = ();
                   16944:     my $lastchange =
                   16945:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16946:     if ($lastchange > $env{'request.course.tied'}) {
                   16947:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16948:         unless ($ferr) {
                   16949:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16950:         }
                   16951:     }
                   16952:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16953:     if (defined($navmap)) {
                   16954:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16955:             $allmaps{$res->src()} = 1;
                   16956:         }
                   16957:     }
                   16958:     return \%allmaps;
                   16959: }
                   16960: 
1.1083    raeburn  16961: sub parse_supplemental_title {
                   16962:     my ($title) = @_;
                   16963: 
                   16964:     my ($foldertitle,$renametitle);
                   16965:     if ($title =~ /&amp;&amp;&amp;/) {
                   16966:         $title = &HTML::Entites::decode($title);
                   16967:     }
                   16968:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16969:         $renametitle=$4;
                   16970:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16971:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16972:         my $name =  &plainname($uname,$udom);
                   16973:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16974:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16975:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16976:             $name.': <br />'.$foldertitle;
                   16977:     }
                   16978:     if (wantarray) {
                   16979:         return ($title,$foldertitle,$renametitle);
                   16980:     }
                   16981:     return $title;
                   16982: }
                   16983: 
1.1143    raeburn  16984: sub recurse_supplemental {
                   16985:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16986:     if ($suppmap) {
                   16987:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16988:         if ($fatal) {
                   16989:             $errors ++;
                   16990:         } else {
                   16991:             if ($#LONCAPA::map::resources > 0) {
                   16992:                 foreach my $res (@LONCAPA::map::resources) {
                   16993:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16994:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  16995:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16996:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  16997:                         } else {
                   16998:                             $numfiles ++;
                   16999:                         }
                   17000:                     }
                   17001:                 }
                   17002:             }
                   17003:         }
                   17004:     }
                   17005:     return ($numfiles,$errors);
                   17006: }
                   17007: 
1.1101    raeburn  17008: sub symb_to_docspath {
1.1267    raeburn  17009:     my ($symb,$navmapref) = @_;
                   17010:     return unless ($symb && ref($navmapref));
1.1101    raeburn  17011:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17012:     if ($resurl=~/\.(sequence|page)$/) {
                   17013:         $mapurl=$resurl;
                   17014:     } elsif ($resurl eq 'adm/navmaps') {
                   17015:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17016:     }
                   17017:     my $mapresobj;
1.1267    raeburn  17018:     unless (ref($$navmapref)) {
                   17019:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17020:     }
                   17021:     if (ref($$navmapref)) {
                   17022:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  17023:     }
                   17024:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17025:     my $type=$2;
                   17026:     my $path;
                   17027:     if (ref($mapresobj)) {
                   17028:         my $pcslist = $mapresobj->map_hierarchy();
                   17029:         if ($pcslist ne '') {
                   17030:             foreach my $pc (split(/,/,$pcslist)) {
                   17031:                 next if ($pc <= 1);
1.1267    raeburn  17032:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  17033:                 if (ref($res)) {
                   17034:                     my $thisurl = $res->src();
                   17035:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17036:                     my $thistitle = $res->title();
                   17037:                     $path .= '&'.
                   17038:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  17039:                              &escape($thistitle).
1.1101    raeburn  17040:                              ':'.$res->randompick().
                   17041:                              ':'.$res->randomout().
                   17042:                              ':'.$res->encrypted().
                   17043:                              ':'.$res->randomorder().
                   17044:                              ':'.$res->is_page();
                   17045:                 }
                   17046:             }
                   17047:         }
                   17048:         $path =~ s/^\&//;
                   17049:         my $maptitle = $mapresobj->title();
                   17050:         if ($mapurl eq 'default') {
1.1129    raeburn  17051:             $maptitle = 'Main Content';
1.1101    raeburn  17052:         }
                   17053:         $path .= (($path ne '')? '&' : '').
                   17054:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17055:                  &escape($maptitle).
1.1101    raeburn  17056:                  ':'.$mapresobj->randompick().
                   17057:                  ':'.$mapresobj->randomout().
                   17058:                  ':'.$mapresobj->encrypted().
                   17059:                  ':'.$mapresobj->randomorder().
                   17060:                  ':'.$mapresobj->is_page();
                   17061:     } else {
                   17062:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17063:         my $ispage = (($type eq 'page')? 1 : '');
                   17064:         if ($mapurl eq 'default') {
1.1129    raeburn  17065:             $maptitle = 'Main Content';
1.1101    raeburn  17066:         }
                   17067:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17068:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  17069:     }
                   17070:     unless ($mapurl eq 'default') {
                   17071:         $path = 'default&'.
1.1146    raeburn  17072:                 &escape('Main Content').
1.1101    raeburn  17073:                 ':::::&'.$path;
                   17074:     }
                   17075:     return $path;
                   17076: }
                   17077: 
1.1094    raeburn  17078: sub captcha_display {
                   17079:     my ($context,$lonhost) = @_;
                   17080:     my ($output,$error);
1.1234    raeburn  17081:     my ($captcha,$pubkey,$privkey,$version) = 
                   17082:         &get_captcha_config($context,$lonhost);
1.1095    raeburn  17083:     if ($captcha eq 'original') {
1.1094    raeburn  17084:         $output = &create_captcha();
                   17085:         unless ($output) {
1.1172    raeburn  17086:             $error = 'captcha';
1.1094    raeburn  17087:         }
                   17088:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17089:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  17090:         unless ($output) {
1.1172    raeburn  17091:             $error = 'recaptcha';
1.1094    raeburn  17092:         }
                   17093:     }
1.1234    raeburn  17094:     return ($output,$error,$captcha,$version);
1.1094    raeburn  17095: }
                   17096: 
                   17097: sub captcha_response {
                   17098:     my ($context,$lonhost) = @_;
                   17099:     my ($captcha_chk,$captcha_error);
1.1234    raeburn  17100:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  17101:     if ($captcha eq 'original') {
1.1094    raeburn  17102:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17103:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17104:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  17105:     } else {
                   17106:         $captcha_chk = 1;
                   17107:     }
                   17108:     return ($captcha_chk,$captcha_error);
                   17109: }
                   17110: 
                   17111: sub get_captcha_config {
                   17112:     my ($context,$lonhost) = @_;
1.1234    raeburn  17113:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  17114:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17115:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17116:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  17117:     if ($context eq 'usercreation') {
                   17118:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17119:         if (ref($domconfig{$context}) eq 'HASH') {
                   17120:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17121:             if (ref($hashtocheck) eq 'HASH') {
                   17122:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17123:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17124:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17125:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17126:                     }
                   17127:                     if ($privkey && $pubkey) {
                   17128:                         $captcha = 'recaptcha';
1.1234    raeburn  17129:                         $version = $hashtocheck->{'recaptchaversion'};
                   17130:                         if ($version ne '2') {
                   17131:                             $version = 1;
                   17132:                         }
1.1095    raeburn  17133:                     } else {
                   17134:                         $captcha = 'original';
                   17135:                     }
                   17136:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17137:                     $captcha = 'original';
                   17138:                 }
1.1094    raeburn  17139:             }
1.1095    raeburn  17140:         } else {
                   17141:             $captcha = 'captcha';
                   17142:         }
                   17143:     } elsif ($context eq 'login') {
                   17144:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17145:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17146:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17147:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  17148:             if ($privkey && $pubkey) {
                   17149:                 $captcha = 'recaptcha';
1.1234    raeburn  17150:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17151:                 if ($version ne '2') {
                   17152:                     $version = 1; 
                   17153:                 }
1.1095    raeburn  17154:             } else {
                   17155:                 $captcha = 'original';
1.1094    raeburn  17156:             }
1.1095    raeburn  17157:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17158:             $captcha = 'original';
1.1094    raeburn  17159:         }
                   17160:     }
1.1234    raeburn  17161:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  17162: }
                   17163: 
                   17164: sub create_captcha {
                   17165:     my %captcha_params = &captcha_settings();
                   17166:     my ($output,$maxtries,$tries) = ('',10,0);
                   17167:     while ($tries < $maxtries) {
                   17168:         $tries ++;
                   17169:         my $captcha = Authen::Captcha->new (
                   17170:                                            output_folder => $captcha_params{'output_dir'},
                   17171:                                            data_folder   => $captcha_params{'db_dir'},
                   17172:                                           );
                   17173:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17174: 
                   17175:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17176:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17177:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  17178:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17179:                       '<br />'.
                   17180:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  17181:             last;
                   17182:         }
                   17183:     }
                   17184:     return $output;
                   17185: }
                   17186: 
                   17187: sub captcha_settings {
                   17188:     my %captcha_params = (
                   17189:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17190:                            www_output_dir => "/captchaspool",
                   17191:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17192:                            numchars       => '5',
                   17193:                          );
                   17194:     return %captcha_params;
                   17195: }
                   17196: 
                   17197: sub check_captcha {
                   17198:     my ($captcha_chk,$captcha_error);
                   17199:     my $code = $env{'form.code'};
                   17200:     my $md5sum = $env{'form.crypt'};
                   17201:     my %captcha_params = &captcha_settings();
                   17202:     my $captcha = Authen::Captcha->new(
                   17203:                       output_folder => $captcha_params{'output_dir'},
                   17204:                       data_folder   => $captcha_params{'db_dir'},
                   17205:                   );
1.1109    raeburn  17206:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  17207:     my %captcha_hash = (
                   17208:                         0       => 'Code not checked (file error)',
                   17209:                        -1      => 'Failed: code expired',
                   17210:                        -2      => 'Failed: invalid code (not in database)',
                   17211:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17212:     );
                   17213:     if ($captcha_chk != 1) {
                   17214:         $captcha_error = $captcha_hash{$captcha_chk}
                   17215:     }
                   17216:     return ($captcha_chk,$captcha_error);
                   17217: }
                   17218: 
                   17219: sub create_recaptcha {
1.1234    raeburn  17220:     my ($pubkey,$version) = @_;
                   17221:     if ($version >= 2) {
                   17222:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17223:     } else {
                   17224:         my $use_ssl;
                   17225:         if ($ENV{'SERVER_PORT'} == 443) {
                   17226:             $use_ssl = 1;
                   17227:         }
                   17228:         my $captcha = Captcha::reCAPTCHA->new;
                   17229:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17230:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17231:                &mt('If the text is hard to read, [_1] will replace them.',
                   17232:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17233:                '<br /><br />';
                   17234:     }
1.1094    raeburn  17235: }
                   17236: 
                   17237: sub check_recaptcha {
1.1234    raeburn  17238:     my ($privkey,$version) = @_;
1.1094    raeburn  17239:     my $captcha_chk;
1.1234    raeburn  17240:     if ($version >= 2) {
                   17241:         my $ua = LWP::UserAgent->new;
                   17242:         $ua->timeout(10);
                   17243:         my %info = (
                   17244:                      secret   => $privkey, 
                   17245:                      response => $env{'form.g-recaptcha-response'},
                   17246:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17247:                    );
                   17248:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17249:         if ($response->is_success)  {
                   17250:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17251:             if (ref($data) eq 'HASH') {
                   17252:                 if ($data->{'success'}) {
                   17253:                     $captcha_chk = 1;
                   17254:                 }
                   17255:             }
                   17256:         }
                   17257:     } else {
                   17258:         my $captcha = Captcha::reCAPTCHA->new;
                   17259:         my $captcha_result =
                   17260:             $captcha->check_answer(
                   17261:                                     $privkey,
                   17262:                                     $ENV{'REMOTE_ADDR'},
                   17263:                                     $env{'form.recaptcha_challenge_field'},
                   17264:                                     $env{'form.recaptcha_response_field'},
                   17265:                                   );
                   17266:         if ($captcha_result->{is_valid}) {
                   17267:             $captcha_chk = 1;
                   17268:         }
1.1094    raeburn  17269:     }
                   17270:     return $captcha_chk;
                   17271: }
                   17272: 
1.1174    raeburn  17273: sub emailusername_info {
1.1244    raeburn  17274:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  17275:     my %titles = &Apache::lonlocal::texthash (
                   17276:                      lastname      => 'Last Name',
                   17277:                      firstname     => 'First Name',
                   17278:                      institution   => 'School/college/university',
                   17279:                      location      => "School's city, state/province, country",
                   17280:                      web           => "School's web address",
                   17281:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  17282:                      id            => 'Student/Employee ID',
1.1174    raeburn  17283:                  );
                   17284:     return (\@fields,\%titles);
                   17285: }
                   17286: 
1.1161    raeburn  17287: sub cleanup_html {
                   17288:     my ($incoming) = @_;
                   17289:     my $outgoing;
                   17290:     if ($incoming ne '') {
                   17291:         $outgoing = $incoming;
                   17292:         $outgoing =~ s/;/&#059;/g;
                   17293:         $outgoing =~ s/\#/&#035;/g;
                   17294:         $outgoing =~ s/\&/&#038;/g;
                   17295:         $outgoing =~ s/</&#060;/g;
                   17296:         $outgoing =~ s/>/&#062;/g;
                   17297:         $outgoing =~ s/\(/&#040/g;
                   17298:         $outgoing =~ s/\)/&#041;/g;
                   17299:         $outgoing =~ s/"/&#034;/g;
                   17300:         $outgoing =~ s/'/&#039;/g;
                   17301:         $outgoing =~ s/\$/&#036;/g;
                   17302:         $outgoing =~ s{/}{&#047;}g;
                   17303:         $outgoing =~ s/=/&#061;/g;
                   17304:         $outgoing =~ s/\\/&#092;/g
                   17305:     }
                   17306:     return $outgoing;
                   17307: }
                   17308: 
1.1190    musolffc 17309: # Checks for critical messages and returns a redirect url if one exists.
                   17310: # $interval indicates how often to check for messages.
                   17311: sub critical_redirect {
                   17312:     my ($interval) = @_;
                   17313:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   17314:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   17315:                                         $env{'user.name'});
                   17316:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  17317:         my $redirecturl;
1.1190    musolffc 17318:         if ($what[0]) {
                   17319: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17320: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  17321: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17322:                 return (1, $url);
1.1190    musolffc 17323:             }
1.1191    raeburn  17324:         }
                   17325:     } 
                   17326:     return ();
1.1190    musolffc 17327: }
                   17328: 
1.1174    raeburn  17329: # Use:
                   17330: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17331: #
                   17332: ##################################################
                   17333: #          password associated functions         #
                   17334: ##################################################
                   17335: sub des_keys {
                   17336:     # Make a new key for DES encryption.
                   17337:     # Each key has two parts which are returned separately.
                   17338:     # Please note:  Each key must be passed through the &hex function
                   17339:     # before it is output to the web browser.  The hex versions cannot
                   17340:     # be used to decrypt.
                   17341:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17342:                 '8','9','a','b','c','d','e','f');
                   17343:     my $lkey='';
                   17344:     for (0..7) {
                   17345:         $lkey.=$hexstr[rand(15)];
                   17346:     }
                   17347:     my $ukey='';
                   17348:     for (0..7) {
                   17349:         $ukey.=$hexstr[rand(15)];
                   17350:     }
                   17351:     return ($lkey,$ukey);
                   17352: }
                   17353: 
                   17354: sub des_decrypt {
                   17355:     my ($key,$cyphertext) = @_;
                   17356:     my $keybin=pack("H16",$key);
                   17357:     my $cypher;
                   17358:     if ($Crypt::DES::VERSION>=2.03) {
                   17359:         $cypher=new Crypt::DES $keybin;
                   17360:     } else {
                   17361:         $cypher=new DES $keybin;
                   17362:     }
1.1233    raeburn  17363:     my $plaintext='';
                   17364:     my $cypherlength = length($cyphertext);
                   17365:     my $numchunks = int($cypherlength/32);
                   17366:     for (my $j=0; $j<$numchunks; $j++) {
                   17367:         my $start = $j*32;
                   17368:         my $cypherblock = substr($cyphertext,$start,32);
                   17369:         my $chunk =
                   17370:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17371:         $chunk .=
                   17372:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17373:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17374:         $plaintext .= $chunk;
                   17375:     }
1.1174    raeburn  17376:     return $plaintext;
                   17377: }
                   17378: 
1.112     bowersj2 17379: 1;
                   17380: __END__;
1.41      ng       17381: 

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