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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1267  ! raeburn     4: # $Id: loncommon.pm,v 1.1266 2016/11/26 19:40:44 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+)$}) {
                   5865:             $role = &mt('Helpdesk[_1]','&nbsp;'.$2); 
                   5866:         } else {
                   5867:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  5868:         }
1.898     raeburn  5869:         if ($env{'request.course.sec'}) {
                   5870:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5871:         }   
1.359     albertel 5872: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5873:     } else {
                   5874:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5875:     }
1.433     albertel 5876: 
1.359     albertel 5877:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5878: 
1.438     albertel 5879:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5880: 
1.101     www      5881: # construct main body tag
1.359     albertel 5882:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  5883: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5884: 
1.1131    raeburn  5885:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5886: 
1.1130    raeburn  5887:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5888:         return $bodytag;
1.1130    raeburn  5889:     }
1.359     albertel 5890: 
1.954     raeburn  5891:     if ($public) {
1.433     albertel 5892: 	undef($role);
                   5893:     }
1.359     albertel 5894:     
1.762     bisitz   5895:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5896:     #
                   5897:     # Extra info if you are the DC
                   5898:     my $dc_info = '';
                   5899:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5900:                         $env{'course.'.$env{'request.course.id'}.
                   5901:                                  '.domain'}.'/'})) {
                   5902:         my $cid = $env{'request.course.id'};
1.917     raeburn  5903:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5904:         $dc_info =~ s/\s+$//;
1.359     albertel 5905:     }
                   5906: 
1.1237    raeburn  5907:     my $crstype;
                   5908:     if ($env{'request.course.id'}) {
                   5909:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   5910:     } elsif ($args->{'crstype'}) {
                   5911:         $crstype = $args->{'crstype'};
                   5912:     }
                   5913:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   5914:         undef($role);
                   5915:     } else {
1.1242    raeburn  5916:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  5917:     }
1.853     droeschl 5918: 
1.903     droeschl 5919:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5920: 
                   5921:         #    if ($env{'request.state'} eq 'construct') {
                   5922:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5923:         #    }
                   5924: 
1.1130    raeburn  5925:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5926:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5927: 
1.1237    raeburn  5928:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
1.359     albertel 5929: 
1.916     droeschl 5930:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5931:              if ($dc_info) {
                   5932:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5933:              }
1.1130    raeburn  5934:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5935:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5936:             return $bodytag;
                   5937:         }
1.894     droeschl 5938: 
1.927     raeburn  5939:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5940:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5941:         }
1.916     droeschl 5942: 
1.1130    raeburn  5943:         $bodytag .= $right;
1.852     droeschl 5944: 
1.917     raeburn  5945:         if ($dc_info) {
                   5946:             $dc_info = &dc_courseid_toggle($dc_info);
                   5947:         }
                   5948:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5949: 
1.1169    raeburn  5950:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5951:         if ($args->{'no_secondary_menu'}) {
                   5952:             return $bodytag;
                   5953:         }
1.1169    raeburn  5954:         #don't show menus for public users
1.954     raeburn  5955:         if (!$public){
1.1154    raeburn  5956:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5957:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5958:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5959:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5960:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5961:                                 $args->{'bread_crumbs'});
1.1096    raeburn  5962:             } elsif ($forcereg) {
                   5963:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  5964:                                                             $args->{'group'},
                   5965:                                                             $args->{'hide_buttons'});
1.1096    raeburn  5966:             } else {
                   5967:                 $bodytag .= 
                   5968:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5969:                                                         $forcereg,$args->{'group'},
                   5970:                                                         $args->{'bread_crumbs'},
                   5971:                                                         $advtoolsref);
1.920     raeburn  5972:             }
1.903     droeschl 5973:         }else{
                   5974:             # this is to seperate menu from content when there's no secondary
                   5975:             # menu. Especially needed for public accessible ressources.
                   5976:             $bodytag .= '<hr style="clear:both" />';
                   5977:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5978:         }
1.903     droeschl 5979: 
1.235     raeburn  5980:         return $bodytag;
1.182     matthew  5981: }
                   5982: 
1.917     raeburn  5983: sub dc_courseid_toggle {
                   5984:     my ($dc_info) = @_;
1.980     raeburn  5985:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5986:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5987:            &mt('(More ...)').'</a></span>'.
                   5988:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5989: }
                   5990: 
1.330     albertel 5991: sub make_attr_string {
                   5992:     my ($register,$attr_ref) = @_;
                   5993: 
                   5994:     if ($attr_ref && !ref($attr_ref)) {
                   5995: 	die("addentries Must be a hash ref ".
                   5996: 	    join(':',caller(1))." ".
                   5997: 	    join(':',caller(0))." ");
                   5998:     }
                   5999: 
                   6000:     if ($register) {
1.339     albertel 6001: 	my ($on_load,$on_unload);
                   6002: 	foreach my $key (keys(%{$attr_ref})) {
                   6003: 	    if      (lc($key) eq 'onload') {
                   6004: 		$on_load.=$attr_ref->{$key}.';';
                   6005: 		delete($attr_ref->{$key});
                   6006: 
                   6007: 	    } elsif (lc($key) eq 'onunload') {
                   6008: 		$on_unload.=$attr_ref->{$key}.';';
                   6009: 		delete($attr_ref->{$key});
                   6010: 	    }
                   6011: 	}
1.953     droeschl 6012: 	$attr_ref->{'onload'}  = $on_load;
                   6013: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6014:     }
1.339     albertel 6015: 
1.330     albertel 6016:     my $attr_string;
1.1159    raeburn  6017:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6018: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6019:     }
                   6020:     return $attr_string;
                   6021: }
                   6022: 
                   6023: 
1.182     matthew  6024: ###############################################
1.251     albertel 6025: ###############################################
                   6026: 
                   6027: =pod
                   6028: 
                   6029: =item * &endbodytag()
                   6030: 
                   6031: Returns a uniform footer for LON-CAPA web pages.
                   6032: 
1.635     raeburn  6033: Inputs: 1 - optional reference to an args hash
                   6034: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6035: a 'Continue' link is not displayed if the page contains an
                   6036: internal redirect in the <head></head> section,
                   6037: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6038: 
                   6039: =cut
                   6040: 
                   6041: sub endbodytag {
1.635     raeburn  6042:     my ($args) = @_;
1.1080    raeburn  6043:     my $endbodytag;
                   6044:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6045:         $endbodytag='</body>';
                   6046:     }
1.315     albertel 6047:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6048:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6049: 	    $endbodytag=
                   6050: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6051: 	        &mt('Continue').'</a>'.
                   6052: 	        $endbodytag;
                   6053:         }
1.315     albertel 6054:     }
1.251     albertel 6055:     return $endbodytag;
                   6056: }
                   6057: 
1.352     albertel 6058: =pod
                   6059: 
                   6060: =item * &standard_css()
                   6061: 
                   6062: Returns a style sheet
                   6063: 
                   6064: Inputs: (all optional)
                   6065:             domain         -> force to color decorate a page for a specific
                   6066:                                domain
                   6067:             function       -> force usage of a specific rolish color scheme
                   6068:             bgcolor        -> override the default page bgcolor
                   6069: 
                   6070: =cut
                   6071: 
1.343     albertel 6072: sub standard_css {
1.345     albertel 6073:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6074:     $function  = &get_users_function() if (!$function);
                   6075:     my $img    = &designparm($function.'.img',   $domain);
                   6076:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6077:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6078:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6079: #second colour for later usage
1.345     albertel 6080:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6081:     my $pgbg_or_bgcolor =
                   6082: 	         $bgcolor ||
1.352     albertel 6083: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6084:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6085:     my $alink  = &designparm($function.'.alink', $domain);
                   6086:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6087:     my $link   = &designparm($function.'.link',  $domain);
                   6088: 
1.602     albertel 6089:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6090:     my $mono                 = 'monospace';
1.850     bisitz   6091:     my $data_table_head      = $sidebg;
                   6092:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6093:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6094:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6095:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6096:     my $mail_new             = '#FFBB77';
                   6097:     my $mail_new_hover       = '#DD9955';
                   6098:     my $mail_read            = '#BBBB77';
                   6099:     my $mail_read_hover      = '#999944';
                   6100:     my $mail_replied         = '#AAAA88';
                   6101:     my $mail_replied_hover   = '#888855';
                   6102:     my $mail_other           = '#99BBBB';
                   6103:     my $mail_other_hover     = '#669999';
1.391     albertel 6104:     my $table_header         = '#DDDDDD';
1.489     raeburn  6105:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6106:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6107:     my $button_hover         = '#BF2317';
1.392     albertel 6108: 
1.608     albertel 6109:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6110:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6111:                                              : '0 3px 0 4px';
1.448     albertel 6112: 
1.523     albertel 6113: 
1.343     albertel 6114:     return <<END;
1.947     droeschl 6115: 
                   6116: /* needed for iframe to allow 100% height in FF */
                   6117: body, html { 
                   6118:     margin: 0;
                   6119:     padding: 0 0.5%;
                   6120:     height: 99%; /* to avoid scrollbars */
                   6121: }
                   6122: 
1.795     www      6123: body {
1.911     bisitz   6124:   font-family: $sans;
                   6125:   line-height:130%;
                   6126:   font-size:0.83em;
                   6127:   color:$font;
1.795     www      6128: }
                   6129: 
1.959     onken    6130: a:focus,
                   6131: a:focus img {
1.795     www      6132:   color: red;
                   6133: }
1.698     harmsja  6134: 
1.911     bisitz   6135: form, .inline {
                   6136:   display: inline;
1.795     www      6137: }
1.721     harmsja  6138: 
1.795     www      6139: .LC_right {
1.911     bisitz   6140:   text-align:right;
1.795     www      6141: }
                   6142: 
                   6143: .LC_middle {
1.911     bisitz   6144:   vertical-align:middle;
1.795     www      6145: }
1.721     harmsja  6146: 
1.1130    raeburn  6147: .LC_floatleft {
                   6148:   float: left;
                   6149: }
                   6150: 
                   6151: .LC_floatright {
                   6152:   float: right;
                   6153: }
                   6154: 
1.911     bisitz   6155: .LC_400Box {
                   6156:   width:400px;
                   6157: }
1.721     harmsja  6158: 
1.947     droeschl 6159: .LC_iframecontainer {
                   6160:     width: 98%;
                   6161:     margin: 0;
                   6162:     position: fixed;
                   6163:     top: 8.5em;
                   6164:     bottom: 0;
                   6165: }
                   6166: 
                   6167: .LC_iframecontainer iframe{
                   6168:     border: none;
                   6169:     width: 100%;
                   6170:     height: 100%;
                   6171: }
                   6172: 
1.778     bisitz   6173: .LC_filename {
                   6174:   font-family: $mono;
                   6175:   white-space:pre;
1.921     bisitz   6176:   font-size: 120%;
1.778     bisitz   6177: }
                   6178: 
                   6179: .LC_fileicon {
                   6180:   border: none;
                   6181:   height: 1.3em;
                   6182:   vertical-align: text-bottom;
                   6183:   margin-right: 0.3em;
                   6184:   text-decoration:none;
                   6185: }
                   6186: 
1.1008    www      6187: .LC_setting {
                   6188:   text-decoration:underline;
                   6189: }
                   6190: 
1.350     albertel 6191: .LC_error {
                   6192:   color: red;
                   6193: }
1.795     www      6194: 
1.1097    bisitz   6195: .LC_warning {
                   6196:   color: darkorange;
                   6197: }
                   6198: 
1.457     albertel 6199: .LC_diff_removed {
1.733     bisitz   6200:   color: red;
1.394     albertel 6201: }
1.532     albertel 6202: 
                   6203: .LC_info,
1.457     albertel 6204: .LC_success,
                   6205: .LC_diff_added {
1.350     albertel 6206:   color: green;
                   6207: }
1.795     www      6208: 
1.802     bisitz   6209: div.LC_confirm_box {
                   6210:   background-color: #FAFAFA;
                   6211:   border: 1px solid $lg_border_color;
                   6212:   margin-right: 0;
                   6213:   padding: 5px;
                   6214: }
                   6215: 
                   6216: div.LC_confirm_box .LC_error img,
                   6217: div.LC_confirm_box .LC_success img {
                   6218:   vertical-align: middle;
                   6219: }
                   6220: 
1.1242    raeburn  6221: .LC_maxwidth {
                   6222:   max-width: 100%;
                   6223:   height: auto;
                   6224: }
                   6225: 
1.1243    raeburn  6226: .LC_textsize_mobile {
                   6227:   \@media only screen and (max-device-width: 480px) {
                   6228:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6229:   }
                   6230: }
                   6231: 
1.440     albertel 6232: .LC_icon {
1.771     droeschl 6233:   border: none;
1.790     droeschl 6234:   vertical-align: middle;
1.771     droeschl 6235: }
                   6236: 
1.543     albertel 6237: .LC_docs_spacer {
                   6238:   width: 25px;
                   6239:   height: 1px;
1.771     droeschl 6240:   border: none;
1.543     albertel 6241: }
1.346     albertel 6242: 
1.532     albertel 6243: .LC_internal_info {
1.735     bisitz   6244:   color: #999999;
1.532     albertel 6245: }
                   6246: 
1.794     www      6247: .LC_discussion {
1.1050    www      6248:   background: $data_table_dark;
1.911     bisitz   6249:   border: 1px solid black;
                   6250:   margin: 2px;
1.794     www      6251: }
                   6252: 
                   6253: .LC_disc_action_left {
1.1050    www      6254:   background: $sidebg;
1.911     bisitz   6255:   text-align: left;
1.1050    www      6256:   padding: 4px;
                   6257:   margin: 2px;
1.794     www      6258: }
                   6259: 
                   6260: .LC_disc_action_right {
1.1050    www      6261:   background: $sidebg;
1.911     bisitz   6262:   text-align: right;
1.1050    www      6263:   padding: 4px;
                   6264:   margin: 2px;
1.794     www      6265: }
                   6266: 
                   6267: .LC_disc_new_item {
1.911     bisitz   6268:   background: white;
                   6269:   border: 2px solid red;
1.1050    www      6270:   margin: 4px;
                   6271:   padding: 4px;
1.794     www      6272: }
                   6273: 
                   6274: .LC_disc_old_item {
1.911     bisitz   6275:   background: white;
1.1050    www      6276:   margin: 4px;
                   6277:   padding: 4px;
1.794     www      6278: }
                   6279: 
1.458     albertel 6280: table.LC_pastsubmission {
                   6281:   border: 1px solid black;
                   6282:   margin: 2px;
                   6283: }
                   6284: 
1.924     bisitz   6285: table#LC_menubuttons {
1.345     albertel 6286:   width: 100%;
                   6287:   background: $pgbg;
1.392     albertel 6288:   border: 2px;
1.402     albertel 6289:   border-collapse: separate;
1.803     bisitz   6290:   padding: 0;
1.345     albertel 6291: }
1.392     albertel 6292: 
1.801     tempelho 6293: table#LC_title_bar a {
                   6294:   color: $fontmenu;
                   6295: }
1.836     bisitz   6296: 
1.807     droeschl 6297: table#LC_title_bar {
1.819     tempelho 6298:   clear: both;
1.836     bisitz   6299:   display: none;
1.807     droeschl 6300: }
                   6301: 
1.795     www      6302: table#LC_title_bar,
1.933     droeschl 6303: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6304: table#LC_title_bar.LC_with_remote {
1.359     albertel 6305:   width: 100%;
1.392     albertel 6306:   border-color: $pgbg;
                   6307:   border-style: solid;
                   6308:   border-width: $border;
1.379     albertel 6309:   background: $pgbg;
1.801     tempelho 6310:   color: $fontmenu;
1.392     albertel 6311:   border-collapse: collapse;
1.803     bisitz   6312:   padding: 0;
1.819     tempelho 6313:   margin: 0;
1.359     albertel 6314: }
1.795     www      6315: 
1.933     droeschl 6316: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6317:     margin: 0;
                   6318:     padding: 0;
1.933     droeschl 6319:     position: relative;
                   6320:     list-style: none;
1.913     droeschl 6321: }
1.933     droeschl 6322: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6323:     display: inline;
                   6324: }
1.933     droeschl 6325: 
                   6326: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6327:     padding: 0;
1.933     droeschl 6328:     margin: 0;
                   6329:     float: left;
1.913     droeschl 6330: }
1.933     droeschl 6331: .LC_breadcrumb_tools_tools {
                   6332:     padding: 0;
                   6333:     margin: 0;
1.913     droeschl 6334:     float: right;
                   6335: }
                   6336: 
1.1240    raeburn  6337: .LC_placement_prog {
                   6338:     padding-right: 20px;
                   6339:     font-weight: bold;
                   6340:     font-size: 90%;
                   6341: }
                   6342: 
1.359     albertel 6343: table#LC_title_bar td {
                   6344:   background: $tabbg;
                   6345: }
1.795     www      6346: 
1.911     bisitz   6347: table#LC_menubuttons img {
1.803     bisitz   6348:   border: none;
1.346     albertel 6349: }
1.795     www      6350: 
1.842     droeschl 6351: .LC_breadcrumbs_component {
1.911     bisitz   6352:   float: right;
                   6353:   margin: 0 1em;
1.357     albertel 6354: }
1.842     droeschl 6355: .LC_breadcrumbs_component img {
1.911     bisitz   6356:   vertical-align: middle;
1.777     tempelho 6357: }
1.795     www      6358: 
1.1243    raeburn  6359: .LC_breadcrumbs_hoverable {
                   6360:   background: $sidebg;
                   6361: }
                   6362: 
1.383     albertel 6363: td.LC_table_cell_checkbox {
                   6364:   text-align: center;
                   6365: }
1.795     www      6366: 
                   6367: .LC_fontsize_small {
1.911     bisitz   6368:   font-size: 70%;
1.705     tempelho 6369: }
                   6370: 
1.844     bisitz   6371: #LC_breadcrumbs {
1.911     bisitz   6372:   clear:both;
                   6373:   background: $sidebg;
                   6374:   border-bottom: 1px solid $lg_border_color;
                   6375:   line-height: 2.5em;
1.933     droeschl 6376:   overflow: hidden;
1.911     bisitz   6377:   margin: 0;
                   6378:   padding: 0;
1.995     raeburn  6379:   text-align: left;
1.819     tempelho 6380: }
1.862     bisitz   6381: 
1.1098    bisitz   6382: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6383:   clear:both;
                   6384:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6385:   border: 1px solid $sidebg;
1.1098    bisitz   6386:   margin: 0 0 10px 0;
1.966     bisitz   6387:   padding: 3px;
1.995     raeburn  6388:   text-align: left;
1.822     bisitz   6389: }
                   6390: 
1.795     www      6391: .LC_fontsize_medium {
1.911     bisitz   6392:   font-size: 85%;
1.705     tempelho 6393: }
                   6394: 
1.795     www      6395: .LC_fontsize_large {
1.911     bisitz   6396:   font-size: 120%;
1.705     tempelho 6397: }
                   6398: 
1.346     albertel 6399: .LC_menubuttons_inline_text {
                   6400:   color: $font;
1.698     harmsja  6401:   font-size: 90%;
1.701     harmsja  6402:   padding-left:3px;
1.346     albertel 6403: }
                   6404: 
1.934     droeschl 6405: .LC_menubuttons_inline_text img{
                   6406:   vertical-align: middle;
                   6407: }
                   6408: 
1.1051    www      6409: li.LC_menubuttons_inline_text img {
1.951     onken    6410:   cursor:pointer;
1.1002    droeschl 6411:   text-decoration: none;
1.951     onken    6412: }
                   6413: 
1.526     www      6414: .LC_menubuttons_link {
                   6415:   text-decoration: none;
                   6416: }
1.795     www      6417: 
1.522     albertel 6418: .LC_menubuttons_category {
1.521     www      6419:   color: $font;
1.526     www      6420:   background: $pgbg;
1.521     www      6421:   font-size: larger;
                   6422:   font-weight: bold;
                   6423: }
                   6424: 
1.346     albertel 6425: td.LC_menubuttons_text {
1.911     bisitz   6426:   color: $font;
1.346     albertel 6427: }
1.706     harmsja  6428: 
1.346     albertel 6429: .LC_current_location {
                   6430:   background: $tabbg;
                   6431: }
1.795     www      6432: 
1.938     bisitz   6433: table.LC_data_table {
1.347     albertel 6434:   border: 1px solid #000000;
1.402     albertel 6435:   border-collapse: separate;
1.426     albertel 6436:   border-spacing: 1px;
1.610     albertel 6437:   background: $pgbg;
1.347     albertel 6438: }
1.795     www      6439: 
1.422     albertel 6440: .LC_data_table_dense {
                   6441:   font-size: small;
                   6442: }
1.795     www      6443: 
1.507     raeburn  6444: table.LC_nested_outer {
                   6445:   border: 1px solid #000000;
1.589     raeburn  6446:   border-collapse: collapse;
1.803     bisitz   6447:   border-spacing: 0;
1.507     raeburn  6448:   width: 100%;
                   6449: }
1.795     www      6450: 
1.879     raeburn  6451: table.LC_innerpickbox,
1.507     raeburn  6452: table.LC_nested {
1.803     bisitz   6453:   border: none;
1.589     raeburn  6454:   border-collapse: collapse;
1.803     bisitz   6455:   border-spacing: 0;
1.507     raeburn  6456:   width: 100%;
                   6457: }
1.795     www      6458: 
1.911     bisitz   6459: table.LC_data_table tr th,
                   6460: table.LC_calendar tr th,
1.879     raeburn  6461: table.LC_prior_tries tr th,
                   6462: table.LC_innerpickbox tr th {
1.349     albertel 6463:   font-weight: bold;
                   6464:   background-color: $data_table_head;
1.801     tempelho 6465:   color:$fontmenu;
1.701     harmsja  6466:   font-size:90%;
1.347     albertel 6467: }
1.795     www      6468: 
1.879     raeburn  6469: table.LC_innerpickbox tr th,
                   6470: table.LC_innerpickbox tr td {
                   6471:   vertical-align: top;
                   6472: }
                   6473: 
1.711     raeburn  6474: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6475:   background-color: #CCCCCC;
1.711     raeburn  6476:   font-weight: bold;
                   6477:   text-align: left;
                   6478: }
1.795     www      6479: 
1.912     bisitz   6480: table.LC_data_table tr.LC_odd_row > td {
                   6481:   background-color: $data_table_light;
                   6482:   padding: 2px;
                   6483:   vertical-align: top;
                   6484: }
                   6485: 
1.809     bisitz   6486: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6487:   background-color: $data_table_light;
1.912     bisitz   6488:   vertical-align: top;
                   6489: }
                   6490: 
                   6491: table.LC_data_table tr.LC_even_row > td {
                   6492:   background-color: $data_table_dark;
1.425     albertel 6493:   padding: 2px;
1.900     bisitz   6494:   vertical-align: top;
1.347     albertel 6495: }
1.795     www      6496: 
1.809     bisitz   6497: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6498:   background-color: $data_table_dark;
1.900     bisitz   6499:   vertical-align: top;
1.347     albertel 6500: }
1.795     www      6501: 
1.425     albertel 6502: table.LC_data_table tr.LC_data_table_highlight td {
                   6503:   background-color: $data_table_darker;
                   6504: }
1.795     www      6505: 
1.639     raeburn  6506: table.LC_data_table tr td.LC_leftcol_header {
                   6507:   background-color: $data_table_head;
                   6508:   font-weight: bold;
                   6509: }
1.795     www      6510: 
1.451     albertel 6511: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6512: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6513:   font-weight: bold;
                   6514:   font-style: italic;
                   6515:   text-align: center;
                   6516:   padding: 8px;
1.347     albertel 6517: }
1.795     www      6518: 
1.1114    raeburn  6519: table.LC_data_table tr.LC_empty_row td,
                   6520: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6521:   background-color: $sidebg;
                   6522: }
                   6523: 
                   6524: table.LC_nested tr.LC_empty_row td {
                   6525:   background-color: #FFFFFF;
                   6526: }
                   6527: 
1.890     droeschl 6528: table.LC_caption {
                   6529: }
                   6530: 
1.507     raeburn  6531: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6532:   padding: 4ex
                   6533: }
1.795     www      6534: 
1.507     raeburn  6535: table.LC_nested_outer tr th {
                   6536:   font-weight: bold;
1.801     tempelho 6537:   color:$fontmenu;
1.507     raeburn  6538:   background-color: $data_table_head;
1.701     harmsja  6539:   font-size: small;
1.507     raeburn  6540:   border-bottom: 1px solid #000000;
                   6541: }
1.795     www      6542: 
1.507     raeburn  6543: table.LC_nested_outer tr td.LC_subheader {
                   6544:   background-color: $data_table_head;
                   6545:   font-weight: bold;
                   6546:   font-size: small;
                   6547:   border-bottom: 1px solid #000000;
                   6548:   text-align: right;
1.451     albertel 6549: }
1.795     www      6550: 
1.507     raeburn  6551: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6552:   background-color: #CCCCCC;
1.451     albertel 6553:   font-weight: bold;
                   6554:   font-size: small;
1.507     raeburn  6555:   text-align: center;
                   6556: }
1.795     www      6557: 
1.589     raeburn  6558: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6559: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6560:   text-align: left;
1.451     albertel 6561: }
1.795     www      6562: 
1.507     raeburn  6563: table.LC_nested td {
1.735     bisitz   6564:   background-color: #FFFFFF;
1.451     albertel 6565:   font-size: small;
1.507     raeburn  6566: }
1.795     www      6567: 
1.507     raeburn  6568: table.LC_nested_outer tr th.LC_right_item,
                   6569: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6570: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6571: table.LC_nested tr td.LC_right_item {
1.451     albertel 6572:   text-align: right;
                   6573: }
                   6574: 
1.507     raeburn  6575: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6576:   background-color: #EEEEEE;
1.451     albertel 6577: }
                   6578: 
1.473     raeburn  6579: table.LC_createuser {
                   6580: }
                   6581: 
                   6582: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6583:   font-size: small;
1.473     raeburn  6584: }
                   6585: 
                   6586: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6587:   background-color: #CCCCCC;
1.473     raeburn  6588:   font-weight: bold;
                   6589:   text-align: center;
                   6590: }
                   6591: 
1.349     albertel 6592: table.LC_calendar {
                   6593:   border: 1px solid #000000;
                   6594:   border-collapse: collapse;
1.917     raeburn  6595:   width: 98%;
1.349     albertel 6596: }
1.795     www      6597: 
1.349     albertel 6598: table.LC_calendar_pickdate {
                   6599:   font-size: xx-small;
                   6600: }
1.795     www      6601: 
1.349     albertel 6602: table.LC_calendar tr td {
                   6603:   border: 1px solid #000000;
                   6604:   vertical-align: top;
1.917     raeburn  6605:   width: 14%;
1.349     albertel 6606: }
1.795     www      6607: 
1.349     albertel 6608: table.LC_calendar tr td.LC_calendar_day_empty {
                   6609:   background-color: $data_table_dark;
                   6610: }
1.795     www      6611: 
1.779     bisitz   6612: table.LC_calendar tr td.LC_calendar_day_current {
                   6613:   background-color: $data_table_highlight;
1.777     tempelho 6614: }
1.795     www      6615: 
1.938     bisitz   6616: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6617:   background-color: $mail_new;
                   6618: }
1.795     www      6619: 
1.938     bisitz   6620: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6621:   background-color: $mail_new_hover;
                   6622: }
1.795     www      6623: 
1.938     bisitz   6624: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6625:   background-color: $mail_read;
                   6626: }
1.795     www      6627: 
1.938     bisitz   6628: /*
                   6629: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6630:   background-color: $mail_read_hover;
                   6631: }
1.938     bisitz   6632: */
1.795     www      6633: 
1.938     bisitz   6634: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6635:   background-color: $mail_replied;
                   6636: }
1.795     www      6637: 
1.938     bisitz   6638: /*
                   6639: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6640:   background-color: $mail_replied_hover;
                   6641: }
1.938     bisitz   6642: */
1.795     www      6643: 
1.938     bisitz   6644: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6645:   background-color: $mail_other;
                   6646: }
1.795     www      6647: 
1.938     bisitz   6648: /*
                   6649: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6650:   background-color: $mail_other_hover;
                   6651: }
1.938     bisitz   6652: */
1.494     raeburn  6653: 
1.777     tempelho 6654: table.LC_data_table tr > td.LC_browser_file,
                   6655: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6656:   background: #AAEE77;
1.389     albertel 6657: }
1.795     www      6658: 
1.777     tempelho 6659: table.LC_data_table tr > td.LC_browser_file_locked,
                   6660: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6661:   background: #FFAA99;
1.387     albertel 6662: }
1.795     www      6663: 
1.777     tempelho 6664: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6665:   background: #888888;
1.779     bisitz   6666: }
1.795     www      6667: 
1.777     tempelho 6668: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6669: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6670:   background: #F8F866;
1.777     tempelho 6671: }
1.795     www      6672: 
1.696     bisitz   6673: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6674:   background: #E0E8FF;
1.387     albertel 6675: }
1.696     bisitz   6676: 
1.707     bisitz   6677: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6678:   /* background: #77FF77; */
1.707     bisitz   6679: }
1.795     www      6680: 
1.707     bisitz   6681: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6682:   border-right: 8px solid #FFFF77;
1.707     bisitz   6683: }
1.795     www      6684: 
1.707     bisitz   6685: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6686:   border-right: 8px solid #FFAA77;
1.707     bisitz   6687: }
1.795     www      6688: 
1.707     bisitz   6689: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6690:   border-right: 8px solid #FF7777;
1.707     bisitz   6691: }
1.795     www      6692: 
1.707     bisitz   6693: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6694:   border-right: 8px solid #AAFF77;
1.707     bisitz   6695: }
1.795     www      6696: 
1.707     bisitz   6697: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6698:   border-right: 8px solid #11CC55;
1.707     bisitz   6699: }
                   6700: 
1.388     albertel 6701: span.LC_current_location {
1.701     harmsja  6702:   font-size:larger;
1.388     albertel 6703:   background: $pgbg;
                   6704: }
1.387     albertel 6705: 
1.1029    www      6706: span.LC_current_nav_location {
                   6707:   font-weight:bold;
                   6708:   background: $sidebg;
                   6709: }
                   6710: 
1.395     albertel 6711: span.LC_parm_menu_item {
                   6712:   font-size: larger;
                   6713: }
1.795     www      6714: 
1.395     albertel 6715: span.LC_parm_scope_all {
                   6716:   color: red;
                   6717: }
1.795     www      6718: 
1.395     albertel 6719: span.LC_parm_scope_folder {
                   6720:   color: green;
                   6721: }
1.795     www      6722: 
1.395     albertel 6723: span.LC_parm_scope_resource {
                   6724:   color: orange;
                   6725: }
1.795     www      6726: 
1.395     albertel 6727: span.LC_parm_part {
                   6728:   color: blue;
                   6729: }
1.795     www      6730: 
1.911     bisitz   6731: span.LC_parm_folder,
                   6732: span.LC_parm_symb {
1.395     albertel 6733:   font-size: x-small;
                   6734:   font-family: $mono;
                   6735:   color: #AAAAAA;
                   6736: }
                   6737: 
1.977     bisitz   6738: ul.LC_parm_parmlist li {
                   6739:   display: inline-block;
                   6740:   padding: 0.3em 0.8em;
                   6741:   vertical-align: top;
                   6742:   width: 150px;
                   6743:   border-top:1px solid $lg_border_color;
                   6744: }
                   6745: 
1.795     www      6746: td.LC_parm_overview_level_menu,
                   6747: td.LC_parm_overview_map_menu,
                   6748: td.LC_parm_overview_parm_selectors,
                   6749: td.LC_parm_overview_restrictions  {
1.396     albertel 6750:   border: 1px solid black;
                   6751:   border-collapse: collapse;
                   6752: }
1.795     www      6753: 
1.396     albertel 6754: table.LC_parm_overview_restrictions td {
                   6755:   border-width: 1px 4px 1px 4px;
                   6756:   border-style: solid;
                   6757:   border-color: $pgbg;
                   6758:   text-align: center;
                   6759: }
1.795     www      6760: 
1.396     albertel 6761: table.LC_parm_overview_restrictions th {
                   6762:   background: $tabbg;
                   6763:   border-width: 1px 4px 1px 4px;
                   6764:   border-style: solid;
                   6765:   border-color: $pgbg;
                   6766: }
1.795     www      6767: 
1.398     albertel 6768: table#LC_helpmenu {
1.803     bisitz   6769:   border: none;
1.398     albertel 6770:   height: 55px;
1.803     bisitz   6771:   border-spacing: 0;
1.398     albertel 6772: }
                   6773: 
                   6774: table#LC_helpmenu fieldset legend {
                   6775:   font-size: larger;
                   6776: }
1.795     www      6777: 
1.397     albertel 6778: table#LC_helpmenu_links {
                   6779:   width: 100%;
                   6780:   border: 1px solid black;
                   6781:   background: $pgbg;
1.803     bisitz   6782:   padding: 0;
1.397     albertel 6783:   border-spacing: 1px;
                   6784: }
1.795     www      6785: 
1.397     albertel 6786: table#LC_helpmenu_links tr td {
                   6787:   padding: 1px;
                   6788:   background: $tabbg;
1.399     albertel 6789:   text-align: center;
                   6790:   font-weight: bold;
1.397     albertel 6791: }
1.396     albertel 6792: 
1.795     www      6793: table#LC_helpmenu_links a:link,
                   6794: table#LC_helpmenu_links a:visited,
1.397     albertel 6795: table#LC_helpmenu_links a:active {
                   6796:   text-decoration: none;
                   6797:   color: $font;
                   6798: }
1.795     www      6799: 
1.397     albertel 6800: table#LC_helpmenu_links a:hover {
                   6801:   text-decoration: underline;
                   6802:   color: $vlink;
                   6803: }
1.396     albertel 6804: 
1.417     albertel 6805: .LC_chrt_popup_exists {
                   6806:   border: 1px solid #339933;
                   6807:   margin: -1px;
                   6808: }
1.795     www      6809: 
1.417     albertel 6810: .LC_chrt_popup_up {
                   6811:   border: 1px solid yellow;
                   6812:   margin: -1px;
                   6813: }
1.795     www      6814: 
1.417     albertel 6815: .LC_chrt_popup {
                   6816:   border: 1px solid #8888FF;
                   6817:   background: #CCCCFF;
                   6818: }
1.795     www      6819: 
1.421     albertel 6820: table.LC_pick_box {
                   6821:   border-collapse: separate;
                   6822:   background: white;
                   6823:   border: 1px solid black;
                   6824:   border-spacing: 1px;
                   6825: }
1.795     www      6826: 
1.421     albertel 6827: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6828:   background: $sidebg;
1.421     albertel 6829:   font-weight: bold;
1.900     bisitz   6830:   text-align: left;
1.740     bisitz   6831:   vertical-align: top;
1.421     albertel 6832:   width: 184px;
                   6833:   padding: 8px;
                   6834: }
1.795     www      6835: 
1.579     raeburn  6836: table.LC_pick_box td.LC_pick_box_value {
                   6837:   text-align: left;
                   6838:   padding: 8px;
                   6839: }
1.795     www      6840: 
1.579     raeburn  6841: table.LC_pick_box td.LC_pick_box_select {
                   6842:   text-align: left;
                   6843:   padding: 8px;
                   6844: }
1.795     www      6845: 
1.424     albertel 6846: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6847:   padding: 0;
1.421     albertel 6848:   height: 1px;
                   6849:   background: black;
                   6850: }
1.795     www      6851: 
1.421     albertel 6852: table.LC_pick_box td.LC_pick_box_submit {
                   6853:   text-align: right;
                   6854: }
1.795     www      6855: 
1.579     raeburn  6856: table.LC_pick_box td.LC_evenrow_value {
                   6857:   text-align: left;
                   6858:   padding: 8px;
                   6859:   background-color: $data_table_light;
                   6860: }
1.795     www      6861: 
1.579     raeburn  6862: table.LC_pick_box td.LC_oddrow_value {
                   6863:   text-align: left;
                   6864:   padding: 8px;
                   6865:   background-color: $data_table_light;
                   6866: }
1.795     www      6867: 
1.579     raeburn  6868: span.LC_helpform_receipt_cat {
                   6869:   font-weight: bold;
                   6870: }
1.795     www      6871: 
1.424     albertel 6872: table.LC_group_priv_box {
                   6873:   background: white;
                   6874:   border: 1px solid black;
                   6875:   border-spacing: 1px;
                   6876: }
1.795     www      6877: 
1.424     albertel 6878: table.LC_group_priv_box td.LC_pick_box_title {
                   6879:   background: $tabbg;
                   6880:   font-weight: bold;
                   6881:   text-align: right;
                   6882:   width: 184px;
                   6883: }
1.795     www      6884: 
1.424     albertel 6885: table.LC_group_priv_box td.LC_groups_fixed {
                   6886:   background: $data_table_light;
                   6887:   text-align: center;
                   6888: }
1.795     www      6889: 
1.424     albertel 6890: table.LC_group_priv_box td.LC_groups_optional {
                   6891:   background: $data_table_dark;
                   6892:   text-align: center;
                   6893: }
1.795     www      6894: 
1.424     albertel 6895: table.LC_group_priv_box td.LC_groups_functionality {
                   6896:   background: $data_table_darker;
                   6897:   text-align: center;
                   6898:   font-weight: bold;
                   6899: }
1.795     www      6900: 
1.424     albertel 6901: table.LC_group_priv td {
                   6902:   text-align: left;
1.803     bisitz   6903:   padding: 0;
1.424     albertel 6904: }
                   6905: 
                   6906: .LC_navbuttons {
                   6907:   margin: 2ex 0ex 2ex 0ex;
                   6908: }
1.795     www      6909: 
1.423     albertel 6910: .LC_topic_bar {
                   6911:   font-weight: bold;
                   6912:   background: $tabbg;
1.918     wenzelju 6913:   margin: 1em 0em 1em 2em;
1.805     bisitz   6914:   padding: 3px;
1.918     wenzelju 6915:   font-size: 1.2em;
1.423     albertel 6916: }
1.795     www      6917: 
1.423     albertel 6918: .LC_topic_bar span {
1.918     wenzelju 6919:   left: 0.5em;
                   6920:   position: absolute;
1.423     albertel 6921:   vertical-align: middle;
1.918     wenzelju 6922:   font-size: 1.2em;
1.423     albertel 6923: }
1.795     www      6924: 
1.423     albertel 6925: table.LC_course_group_status {
                   6926:   margin: 20px;
                   6927: }
1.795     www      6928: 
1.423     albertel 6929: table.LC_status_selector td {
                   6930:   vertical-align: top;
                   6931:   text-align: center;
1.424     albertel 6932:   padding: 4px;
                   6933: }
1.795     www      6934: 
1.599     albertel 6935: div.LC_feedback_link {
1.616     albertel 6936:   clear: both;
1.829     kalberla 6937:   background: $sidebg;
1.779     bisitz   6938:   width: 100%;
1.829     kalberla 6939:   padding-bottom: 10px;
                   6940:   border: 1px $tabbg solid;
1.833     kalberla 6941:   height: 22px;
                   6942:   line-height: 22px;
                   6943:   padding-top: 5px;
                   6944: }
                   6945: 
                   6946: div.LC_feedback_link img {
                   6947:   height: 22px;
1.867     kalberla 6948:   vertical-align:middle;
1.829     kalberla 6949: }
                   6950: 
1.911     bisitz   6951: div.LC_feedback_link a {
1.829     kalberla 6952:   text-decoration: none;
1.489     raeburn  6953: }
1.795     www      6954: 
1.867     kalberla 6955: div.LC_comblock {
1.911     bisitz   6956:   display:inline;
1.867     kalberla 6957:   color:$font;
                   6958:   font-size:90%;
                   6959: }
                   6960: 
                   6961: div.LC_feedback_link div.LC_comblock {
                   6962:   padding-left:5px;
                   6963: }
                   6964: 
                   6965: div.LC_feedback_link div.LC_comblock a {
                   6966:   color:$font;
                   6967: }
                   6968: 
1.489     raeburn  6969: span.LC_feedback_link {
1.858     bisitz   6970:   /* background: $feedback_link_bg; */
1.599     albertel 6971:   font-size: larger;
                   6972: }
1.795     www      6973: 
1.599     albertel 6974: span.LC_message_link {
1.858     bisitz   6975:   /* background: $feedback_link_bg; */
1.599     albertel 6976:   font-size: larger;
                   6977:   position: absolute;
                   6978:   right: 1em;
1.489     raeburn  6979: }
1.421     albertel 6980: 
1.515     albertel 6981: table.LC_prior_tries {
1.524     albertel 6982:   border: 1px solid #000000;
                   6983:   border-collapse: separate;
                   6984:   border-spacing: 1px;
1.515     albertel 6985: }
1.523     albertel 6986: 
1.515     albertel 6987: table.LC_prior_tries td {
1.524     albertel 6988:   padding: 2px;
1.515     albertel 6989: }
1.523     albertel 6990: 
                   6991: .LC_answer_correct {
1.795     www      6992:   background: lightgreen;
                   6993:   color: darkgreen;
                   6994:   padding: 6px;
1.523     albertel 6995: }
1.795     www      6996: 
1.523     albertel 6997: .LC_answer_charged_try {
1.797     www      6998:   background: #FFAAAA;
1.795     www      6999:   color: darkred;
                   7000:   padding: 6px;
1.523     albertel 7001: }
1.795     www      7002: 
1.779     bisitz   7003: .LC_answer_not_charged_try,
1.523     albertel 7004: .LC_answer_no_grade,
                   7005: .LC_answer_late {
1.795     www      7006:   background: lightyellow;
1.523     albertel 7007:   color: black;
1.795     www      7008:   padding: 6px;
1.523     albertel 7009: }
1.795     www      7010: 
1.523     albertel 7011: .LC_answer_previous {
1.795     www      7012:   background: lightblue;
                   7013:   color: darkblue;
                   7014:   padding: 6px;
1.523     albertel 7015: }
1.795     www      7016: 
1.779     bisitz   7017: .LC_answer_no_message {
1.777     tempelho 7018:   background: #FFFFFF;
                   7019:   color: black;
1.795     www      7020:   padding: 6px;
1.779     bisitz   7021: }
1.795     www      7022: 
1.779     bisitz   7023: .LC_answer_unknown {
                   7024:   background: orange;
                   7025:   color: black;
1.795     www      7026:   padding: 6px;
1.777     tempelho 7027: }
1.795     www      7028: 
1.529     albertel 7029: span.LC_prior_numerical,
                   7030: span.LC_prior_string,
                   7031: span.LC_prior_custom,
                   7032: span.LC_prior_reaction,
                   7033: span.LC_prior_math {
1.925     bisitz   7034:   font-family: $mono;
1.523     albertel 7035:   white-space: pre;
                   7036: }
                   7037: 
1.525     albertel 7038: span.LC_prior_string {
1.925     bisitz   7039:   font-family: $mono;
1.525     albertel 7040:   white-space: pre;
                   7041: }
                   7042: 
1.523     albertel 7043: table.LC_prior_option {
                   7044:   width: 100%;
                   7045:   border-collapse: collapse;
                   7046: }
1.795     www      7047: 
1.911     bisitz   7048: table.LC_prior_rank,
1.795     www      7049: table.LC_prior_match {
1.528     albertel 7050:   border-collapse: collapse;
                   7051: }
1.795     www      7052: 
1.528     albertel 7053: table.LC_prior_option tr td,
                   7054: table.LC_prior_rank tr td,
                   7055: table.LC_prior_match tr td {
1.524     albertel 7056:   border: 1px solid #000000;
1.515     albertel 7057: }
                   7058: 
1.855     bisitz   7059: .LC_nobreak {
1.544     albertel 7060:   white-space: nowrap;
1.519     raeburn  7061: }
                   7062: 
1.576     raeburn  7063: span.LC_cusr_emph {
                   7064:   font-style: italic;
                   7065: }
                   7066: 
1.633     raeburn  7067: span.LC_cusr_subheading {
                   7068:   font-weight: normal;
                   7069:   font-size: 85%;
                   7070: }
                   7071: 
1.861     bisitz   7072: div.LC_docs_entry_move {
1.859     bisitz   7073:   border: 1px solid #BBBBBB;
1.545     albertel 7074:   background: #DDDDDD;
1.861     bisitz   7075:   width: 22px;
1.859     bisitz   7076:   padding: 1px;
                   7077:   margin: 0;
1.545     albertel 7078: }
                   7079: 
1.861     bisitz   7080: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7081: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7082:   font-size: x-small;
                   7083: }
1.795     www      7084: 
1.861     bisitz   7085: .LC_docs_entry_parameter {
                   7086:   white-space: nowrap;
                   7087: }
                   7088: 
1.544     albertel 7089: .LC_docs_copy {
1.545     albertel 7090:   color: #000099;
1.544     albertel 7091: }
1.795     www      7092: 
1.544     albertel 7093: .LC_docs_cut {
1.545     albertel 7094:   color: #550044;
1.544     albertel 7095: }
1.795     www      7096: 
1.544     albertel 7097: .LC_docs_rename {
1.545     albertel 7098:   color: #009900;
1.544     albertel 7099: }
1.795     www      7100: 
1.544     albertel 7101: .LC_docs_remove {
1.545     albertel 7102:   color: #990000;
                   7103: }
                   7104: 
1.547     albertel 7105: .LC_docs_reinit_warn,
                   7106: .LC_docs_ext_edit {
                   7107:   font-size: x-small;
                   7108: }
                   7109: 
1.545     albertel 7110: table.LC_docs_adddocs td,
                   7111: table.LC_docs_adddocs th {
                   7112:   border: 1px solid #BBBBBB;
                   7113:   padding: 4px;
                   7114:   background: #DDDDDD;
1.543     albertel 7115: }
                   7116: 
1.584     albertel 7117: table.LC_sty_begin {
                   7118:   background: #BBFFBB;
                   7119: }
1.795     www      7120: 
1.584     albertel 7121: table.LC_sty_end {
                   7122:   background: #FFBBBB;
                   7123: }
                   7124: 
1.589     raeburn  7125: table.LC_double_column {
1.803     bisitz   7126:   border-width: 0;
1.589     raeburn  7127:   border-collapse: collapse;
                   7128:   width: 100%;
                   7129:   padding: 2px;
                   7130: }
                   7131: 
                   7132: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7133:   top: 2px;
1.589     raeburn  7134:   left: 2px;
                   7135:   width: 47%;
                   7136:   vertical-align: top;
                   7137: }
                   7138: 
                   7139: table.LC_double_column tr td.LC_right_col {
                   7140:   top: 2px;
1.779     bisitz   7141:   right: 2px;
1.589     raeburn  7142:   width: 47%;
                   7143:   vertical-align: top;
                   7144: }
                   7145: 
1.591     raeburn  7146: div.LC_left_float {
                   7147:   float: left;
                   7148:   padding-right: 5%;
1.597     albertel 7149:   padding-bottom: 4px;
1.591     raeburn  7150: }
                   7151: 
                   7152: div.LC_clear_float_header {
1.597     albertel 7153:   padding-bottom: 2px;
1.591     raeburn  7154: }
                   7155: 
                   7156: div.LC_clear_float_footer {
1.597     albertel 7157:   padding-top: 10px;
1.591     raeburn  7158:   clear: both;
                   7159: }
                   7160: 
1.597     albertel 7161: div.LC_grade_show_user {
1.941     bisitz   7162: /*  border-left: 5px solid $sidebg; */
                   7163:   border-top: 5px solid #000000;
                   7164:   margin: 50px 0 0 0;
1.936     bisitz   7165:   padding: 15px 0 5px 10px;
1.597     albertel 7166: }
1.795     www      7167: 
1.936     bisitz   7168: div.LC_grade_show_user_odd_row {
1.941     bisitz   7169: /*  border-left: 5px solid #000000; */
                   7170: }
                   7171: 
                   7172: div.LC_grade_show_user div.LC_Box {
                   7173:   margin-right: 50px;
1.597     albertel 7174: }
                   7175: 
                   7176: div.LC_grade_submissions,
                   7177: div.LC_grade_message_center,
1.936     bisitz   7178: div.LC_grade_info_links {
1.597     albertel 7179:   margin: 5px;
                   7180:   width: 99%;
                   7181:   background: #FFFFFF;
                   7182: }
1.795     www      7183: 
1.597     albertel 7184: div.LC_grade_submissions_header,
1.936     bisitz   7185: div.LC_grade_message_center_header {
1.705     tempelho 7186:   font-weight: bold;
                   7187:   font-size: large;
1.597     albertel 7188: }
1.795     www      7189: 
1.597     albertel 7190: div.LC_grade_submissions_body,
1.936     bisitz   7191: div.LC_grade_message_center_body {
1.597     albertel 7192:   border: 1px solid black;
                   7193:   width: 99%;
                   7194:   background: #FFFFFF;
                   7195: }
1.795     www      7196: 
1.613     albertel 7197: table.LC_scantron_action {
                   7198:   width: 100%;
                   7199: }
1.795     www      7200: 
1.613     albertel 7201: table.LC_scantron_action tr th {
1.698     harmsja  7202:   font-weight:bold;
                   7203:   font-style:normal;
1.613     albertel 7204: }
1.795     www      7205: 
1.779     bisitz   7206: .LC_edit_problem_header,
1.614     albertel 7207: div.LC_edit_problem_footer {
1.705     tempelho 7208:   font-weight: normal;
                   7209:   font-size:  medium;
1.602     albertel 7210:   margin: 2px;
1.1060    bisitz   7211:   background-color: $sidebg;
1.600     albertel 7212: }
1.795     www      7213: 
1.600     albertel 7214: div.LC_edit_problem_header,
1.602     albertel 7215: div.LC_edit_problem_header div,
1.614     albertel 7216: div.LC_edit_problem_footer,
                   7217: div.LC_edit_problem_footer div,
1.602     albertel 7218: div.LC_edit_problem_editxml_header,
                   7219: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7220:   z-index: 100;
1.600     albertel 7221: }
1.795     www      7222: 
1.600     albertel 7223: div.LC_edit_problem_header_title {
1.705     tempelho 7224:   font-weight: bold;
                   7225:   font-size: larger;
1.602     albertel 7226:   background: $tabbg;
                   7227:   padding: 3px;
1.1060    bisitz   7228:   margin: 0 0 5px 0;
1.602     albertel 7229: }
1.795     www      7230: 
1.602     albertel 7231: table.LC_edit_problem_header_title {
                   7232:   width: 100%;
1.600     albertel 7233:   background: $tabbg;
1.602     albertel 7234: }
                   7235: 
1.1205    golterma 7236: div.LC_edit_actionbar {
                   7237:     background-color: $sidebg;
1.1218    droeschl 7238:     margin: 0;
                   7239:     padding: 0;
                   7240:     line-height: 200%;
1.602     albertel 7241: }
1.795     www      7242: 
1.1218    droeschl 7243: div.LC_edit_actionbar div{
                   7244:     padding: 0;
                   7245:     margin: 0;
                   7246:     display: inline-block;
1.600     albertel 7247: }
1.795     www      7248: 
1.1124    bisitz   7249: .LC_edit_opt {
                   7250:   padding-left: 1em;
                   7251:   white-space: nowrap;
                   7252: }
                   7253: 
1.1152    golterma 7254: .LC_edit_problem_latexhelper{
                   7255:     text-align: right;
                   7256: }
                   7257: 
                   7258: #LC_edit_problem_colorful div{
                   7259:     margin-left: 40px;
                   7260: }
                   7261: 
1.1205    golterma 7262: #LC_edit_problem_codemirror div{
                   7263:     margin-left: 0px;
                   7264: }
                   7265: 
1.911     bisitz   7266: img.stift {
1.803     bisitz   7267:   border-width: 0;
                   7268:   vertical-align: middle;
1.677     riegler  7269: }
1.680     riegler  7270: 
1.923     bisitz   7271: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7272:   vertical-align: top;
1.777     tempelho 7273: }
1.795     www      7274: 
1.716     raeburn  7275: div.LC_createcourse {
1.911     bisitz   7276:   margin: 10px 10px 10px 10px;
1.716     raeburn  7277: }
                   7278: 
1.917     raeburn  7279: .LC_dccid {
1.1130    raeburn  7280:   float: right;
1.917     raeburn  7281:   margin: 0.2em 0 0 0;
                   7282:   padding: 0;
                   7283:   font-size: 90%;
                   7284:   display:none;
                   7285: }
                   7286: 
1.897     wenzelju 7287: ol.LC_primary_menu a:hover,
1.721     harmsja  7288: ol#LC_MenuBreadcrumbs a:hover,
                   7289: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7290: ul#LC_secondary_menu a:hover,
1.721     harmsja  7291: .LC_FormSectionClearButton input:hover
1.795     www      7292: ul.LC_TabContent   li:hover a {
1.952     onken    7293:   color:$button_hover;
1.911     bisitz   7294:   text-decoration:none;
1.693     droeschl 7295: }
                   7296: 
1.779     bisitz   7297: h1 {
1.911     bisitz   7298:   padding: 0;
                   7299:   line-height:130%;
1.693     droeschl 7300: }
1.698     harmsja  7301: 
1.911     bisitz   7302: h2,
                   7303: h3,
                   7304: h4,
                   7305: h5,
                   7306: h6 {
                   7307:   margin: 5px 0 5px 0;
                   7308:   padding: 0;
                   7309:   line-height:130%;
1.693     droeschl 7310: }
1.795     www      7311: 
                   7312: .LC_hcell {
1.911     bisitz   7313:   padding:3px 15px 3px 15px;
                   7314:   margin: 0;
                   7315:   background-color:$tabbg;
                   7316:   color:$fontmenu;
                   7317:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7318: }
1.795     www      7319: 
1.840     bisitz   7320: .LC_Box > .LC_hcell {
1.911     bisitz   7321:   margin: 0 -10px 10px -10px;
1.835     bisitz   7322: }
                   7323: 
1.721     harmsja  7324: .LC_noBorder {
1.911     bisitz   7325:   border: 0;
1.698     harmsja  7326: }
1.693     droeschl 7327: 
1.721     harmsja  7328: .LC_FormSectionClearButton input {
1.911     bisitz   7329:   background-color:transparent;
                   7330:   border: none;
                   7331:   cursor:pointer;
                   7332:   text-decoration:underline;
1.693     droeschl 7333: }
1.763     bisitz   7334: 
                   7335: .LC_help_open_topic {
1.911     bisitz   7336:   color: #FFFFFF;
                   7337:   background-color: #EEEEFF;
                   7338:   margin: 1px;
                   7339:   padding: 4px;
                   7340:   border: 1px solid #000033;
                   7341:   white-space: nowrap;
                   7342:   /* vertical-align: middle; */
1.759     neumanie 7343: }
1.693     droeschl 7344: 
1.911     bisitz   7345: dl,
                   7346: ul,
                   7347: div,
                   7348: fieldset {
                   7349:   margin: 10px 10px 10px 0;
                   7350:   /* overflow: hidden; */
1.693     droeschl 7351: }
1.795     www      7352: 
1.1211    raeburn  7353: article.geogebraweb div {
                   7354:     margin: 0;
                   7355: }
                   7356: 
1.838     bisitz   7357: fieldset > legend {
1.911     bisitz   7358:   font-weight: bold;
                   7359:   padding: 0 5px 0 5px;
1.838     bisitz   7360: }
                   7361: 
1.813     bisitz   7362: #LC_nav_bar {
1.911     bisitz   7363:   float: left;
1.995     raeburn  7364:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7365:   margin: 0 0 2px 0;
1.807     droeschl 7366: }
                   7367: 
1.916     droeschl 7368: #LC_realm {
                   7369:   margin: 0.2em 0 0 0;
                   7370:   padding: 0;
                   7371:   font-weight: bold;
                   7372:   text-align: center;
1.995     raeburn  7373:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7374: }
                   7375: 
1.911     bisitz   7376: #LC_nav_bar em {
                   7377:   font-weight: bold;
                   7378:   font-style: normal;
1.807     droeschl 7379: }
                   7380: 
1.897     wenzelju 7381: ol.LC_primary_menu {
1.934     droeschl 7382:   margin: 0;
1.1076    raeburn  7383:   padding: 0;
1.807     droeschl 7384: }
                   7385: 
1.852     droeschl 7386: ol#LC_PathBreadcrumbs {
1.911     bisitz   7387:   margin: 0;
1.693     droeschl 7388: }
                   7389: 
1.897     wenzelju 7390: ol.LC_primary_menu li {
1.1076    raeburn  7391:   color: RGB(80, 80, 80);
                   7392:   vertical-align: middle;
                   7393:   text-align: left;
                   7394:   list-style: none;
1.1205    golterma 7395:   position: relative;
1.1076    raeburn  7396:   float: left;
1.1205    golterma 7397:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7398:   line-height: 1.5em;
1.1076    raeburn  7399: }
                   7400: 
1.1205    golterma 7401: ol.LC_primary_menu li a,
                   7402: ol.LC_primary_menu li p {
1.1076    raeburn  7403:   display: block;
                   7404:   margin: 0;
                   7405:   padding: 0 5px 0 10px;
                   7406:   text-decoration: none;
                   7407: }
                   7408: 
1.1205    golterma 7409: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7410:   display: inline-block;
                   7411:   width: 95%;
                   7412:   text-align: left;
                   7413: }
                   7414: 
                   7415: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7416:   display: inline-block;	
                   7417:   width: 5%;
                   7418:   float: right;
                   7419:   text-align: right;
                   7420:   font-size: 70%;
                   7421: }
                   7422: 
                   7423: ol.LC_primary_menu ul {
1.1076    raeburn  7424:   display: none;
1.1205    golterma 7425:   width: 15em;
1.1076    raeburn  7426:   background-color: $data_table_light;
1.1205    golterma 7427:   position: absolute;
                   7428:   top: 100%;
1.1076    raeburn  7429: }
                   7430: 
1.1205    golterma 7431: ol.LC_primary_menu ul ul {
                   7432:   left: 100%;
                   7433:   top: 0;
                   7434: }
                   7435: 
                   7436: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7437:   display: block;
                   7438:   position: absolute;
                   7439:   margin: 0;
                   7440:   padding: 0;
1.1078    raeburn  7441:   z-index: 2;
1.1076    raeburn  7442: }
                   7443: 
                   7444: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7445: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7446:   font-size: 90%;
1.911     bisitz   7447:   vertical-align: top;
1.1076    raeburn  7448:   float: none;
1.1079    raeburn  7449:   border-left: 1px solid black;
                   7450:   border-right: 1px solid black;
1.1205    golterma 7451: /* A dark bottom border to visualize different menu options; 
                   7452: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7453:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7454: }
                   7455: 
1.1205    golterma 7456: ol.LC_primary_menu li li p:hover {
                   7457:   color:$button_hover;
                   7458:   text-decoration:none;
                   7459:   background-color:$data_table_dark;
1.1076    raeburn  7460: }
                   7461: 
                   7462: ol.LC_primary_menu li li a:hover {
                   7463:    color:$button_hover;
                   7464:    background-color:$data_table_dark;
1.693     droeschl 7465: }
                   7466: 
1.1205    golterma 7467: /* Font-size equal to the size of the predecessors*/
                   7468: ol.LC_primary_menu li:hover li li {
                   7469:   font-size: 100%;
                   7470: }
                   7471: 
1.897     wenzelju 7472: ol.LC_primary_menu li img {
1.911     bisitz   7473:   vertical-align: bottom;
1.934     droeschl 7474:   height: 1.1em;
1.1077    raeburn  7475:   margin: 0.2em 0 0 0;
1.693     droeschl 7476: }
                   7477: 
1.897     wenzelju 7478: ol.LC_primary_menu a {
1.911     bisitz   7479:   color: RGB(80, 80, 80);
                   7480:   text-decoration: none;
1.693     droeschl 7481: }
1.795     www      7482: 
1.949     droeschl 7483: ol.LC_primary_menu a.LC_new_message {
                   7484:   font-weight:bold;
                   7485:   color: darkred;
                   7486: }
                   7487: 
1.975     raeburn  7488: ol.LC_docs_parameters {
                   7489:   margin-left: 0;
                   7490:   padding: 0;
                   7491:   list-style: none;
                   7492: }
                   7493: 
                   7494: ol.LC_docs_parameters li {
                   7495:   margin: 0;
                   7496:   padding-right: 20px;
                   7497:   display: inline;
                   7498: }
                   7499: 
1.976     raeburn  7500: ol.LC_docs_parameters li:before {
                   7501:   content: "\\002022 \\0020";
                   7502: }
                   7503: 
                   7504: li.LC_docs_parameters_title {
                   7505:   font-weight: bold;
                   7506: }
                   7507: 
                   7508: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7509:   content: "";
                   7510: }
                   7511: 
1.897     wenzelju 7512: ul#LC_secondary_menu {
1.1107    raeburn  7513:   clear: right;
1.911     bisitz   7514:   color: $fontmenu;
                   7515:   background: $tabbg;
                   7516:   list-style: none;
                   7517:   padding: 0;
                   7518:   margin: 0;
                   7519:   width: 100%;
1.995     raeburn  7520:   text-align: left;
1.1107    raeburn  7521:   float: left;
1.808     droeschl 7522: }
                   7523: 
1.897     wenzelju 7524: ul#LC_secondary_menu li {
1.911     bisitz   7525:   font-weight: bold;
                   7526:   line-height: 1.8em;
1.1107    raeburn  7527:   border-right: 1px solid black;
                   7528:   float: left;
                   7529: }
                   7530: 
                   7531: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7532:   background-color: $data_table_light;
                   7533: }
                   7534: 
                   7535: ul#LC_secondary_menu li a {
1.911     bisitz   7536:   padding: 0 0.8em;
1.1107    raeburn  7537: }
                   7538: 
                   7539: ul#LC_secondary_menu li ul {
                   7540:   display: none;
                   7541: }
                   7542: 
                   7543: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7544:   display: block;
                   7545:   position: absolute;
                   7546:   margin: 0;
                   7547:   padding: 0;
                   7548:   list-style:none;
                   7549:   float: none;
                   7550:   background-color: $data_table_light;
                   7551:   z-index: 2;
                   7552:   margin-left: -1px;
                   7553: }
                   7554: 
                   7555: ul#LC_secondary_menu li ul li {
                   7556:   font-size: 90%;
                   7557:   vertical-align: top;
                   7558:   border-left: 1px solid black;
1.911     bisitz   7559:   border-right: 1px solid black;
1.1119    raeburn  7560:   background-color: $data_table_light;
1.1107    raeburn  7561:   list-style:none;
                   7562:   float: none;
                   7563: }
                   7564: 
                   7565: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7566:   background-color: $data_table_dark;
1.807     droeschl 7567: }
                   7568: 
1.847     tempelho 7569: ul.LC_TabContent {
1.911     bisitz   7570:   display:block;
                   7571:   background: $sidebg;
                   7572:   border-bottom: solid 1px $lg_border_color;
                   7573:   list-style:none;
1.1020    raeburn  7574:   margin: -1px -10px 0 -10px;
1.911     bisitz   7575:   padding: 0;
1.693     droeschl 7576: }
                   7577: 
1.795     www      7578: ul.LC_TabContent li,
                   7579: ul.LC_TabContentBigger li {
1.911     bisitz   7580:   float:left;
1.741     harmsja  7581: }
1.795     www      7582: 
1.897     wenzelju 7583: ul#LC_secondary_menu li a {
1.911     bisitz   7584:   color: $fontmenu;
                   7585:   text-decoration: none;
1.693     droeschl 7586: }
1.795     www      7587: 
1.721     harmsja  7588: ul.LC_TabContent {
1.952     onken    7589:   min-height:20px;
1.721     harmsja  7590: }
1.795     www      7591: 
                   7592: ul.LC_TabContent li {
1.911     bisitz   7593:   vertical-align:middle;
1.959     onken    7594:   padding: 0 16px 0 10px;
1.911     bisitz   7595:   background-color:$tabbg;
                   7596:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7597:   border-left: solid 1px $font;
1.721     harmsja  7598: }
1.795     www      7599: 
1.847     tempelho 7600: ul.LC_TabContent .right {
1.911     bisitz   7601:   float:right;
1.847     tempelho 7602: }
                   7603: 
1.911     bisitz   7604: ul.LC_TabContent li a,
                   7605: ul.LC_TabContent li {
                   7606:   color:rgb(47,47,47);
                   7607:   text-decoration:none;
                   7608:   font-size:95%;
                   7609:   font-weight:bold;
1.952     onken    7610:   min-height:20px;
                   7611: }
                   7612: 
1.959     onken    7613: ul.LC_TabContent li a:hover,
                   7614: ul.LC_TabContent li a:focus {
1.952     onken    7615:   color: $button_hover;
1.959     onken    7616:   background:none;
                   7617:   outline:none;
1.952     onken    7618: }
                   7619: 
                   7620: ul.LC_TabContent li:hover {
                   7621:   color: $button_hover;
                   7622:   cursor:pointer;
1.721     harmsja  7623: }
1.795     www      7624: 
1.911     bisitz   7625: ul.LC_TabContent li.active {
1.952     onken    7626:   color: $font;
1.911     bisitz   7627:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7628:   border-bottom:solid 1px #FFFFFF;
                   7629:   cursor: default;
1.744     ehlerst  7630: }
1.795     www      7631: 
1.959     onken    7632: ul.LC_TabContent li.active a {
                   7633:   color:$font;
                   7634:   background:#FFFFFF;
                   7635:   outline: none;
                   7636: }
1.1047    raeburn  7637: 
                   7638: ul.LC_TabContent li.goback {
                   7639:   float: left;
                   7640:   border-left: none;
                   7641: }
                   7642: 
1.870     tempelho 7643: #maincoursedoc {
1.911     bisitz   7644:   clear:both;
1.870     tempelho 7645: }
                   7646: 
                   7647: ul.LC_TabContentBigger {
1.911     bisitz   7648:   display:block;
                   7649:   list-style:none;
                   7650:   padding: 0;
1.870     tempelho 7651: }
                   7652: 
1.795     www      7653: ul.LC_TabContentBigger li {
1.911     bisitz   7654:   vertical-align:bottom;
                   7655:   height: 30px;
                   7656:   font-size:110%;
                   7657:   font-weight:bold;
                   7658:   color: #737373;
1.841     tempelho 7659: }
                   7660: 
1.957     onken    7661: ul.LC_TabContentBigger li.active {
                   7662:   position: relative;
                   7663:   top: 1px;
                   7664: }
                   7665: 
1.870     tempelho 7666: ul.LC_TabContentBigger li a {
1.911     bisitz   7667:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7668:   height: 30px;
                   7669:   line-height: 30px;
                   7670:   text-align: center;
                   7671:   display: block;
                   7672:   text-decoration: none;
1.958     onken    7673:   outline: none;  
1.741     harmsja  7674: }
1.795     www      7675: 
1.870     tempelho 7676: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7677:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7678:   color:$font;
1.744     ehlerst  7679: }
1.795     www      7680: 
1.870     tempelho 7681: ul.LC_TabContentBigger li b {
1.911     bisitz   7682:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7683:   display: block;
                   7684:   float: left;
                   7685:   padding: 0 30px;
1.957     onken    7686:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7687: }
                   7688: 
1.956     onken    7689: ul.LC_TabContentBigger li:hover b {
                   7690:   color:$button_hover;
                   7691: }
                   7692: 
1.870     tempelho 7693: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7694:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7695:   color:$font;
1.957     onken    7696:   border: 0;
1.741     harmsja  7697: }
1.693     droeschl 7698: 
1.870     tempelho 7699: 
1.862     bisitz   7700: ul.LC_CourseBreadcrumbs {
                   7701:   background: $sidebg;
1.1020    raeburn  7702:   height: 2em;
1.862     bisitz   7703:   padding-left: 10px;
1.1020    raeburn  7704:   margin: 0;
1.862     bisitz   7705:   list-style-position: inside;
                   7706: }
                   7707: 
1.911     bisitz   7708: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7709: ol#LC_PathBreadcrumbs {
1.911     bisitz   7710:   padding-left: 10px;
                   7711:   margin: 0;
1.933     droeschl 7712:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7713: }
                   7714: 
1.911     bisitz   7715: ol#LC_MenuBreadcrumbs li,
                   7716: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7717: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7718:   display: inline;
1.933     droeschl 7719:   white-space: normal;  
1.693     droeschl 7720: }
                   7721: 
1.823     bisitz   7722: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7723: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7724:   text-decoration: none;
                   7725:   font-size:90%;
1.693     droeschl 7726: }
1.795     www      7727: 
1.969     droeschl 7728: ol#LC_MenuBreadcrumbs h1 {
                   7729:   display: inline;
                   7730:   font-size: 90%;
                   7731:   line-height: 2.5em;
                   7732:   margin: 0;
                   7733:   padding: 0;
                   7734: }
                   7735: 
1.795     www      7736: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7737:   text-decoration:none;
                   7738:   font-size:100%;
                   7739:   font-weight:bold;
1.693     droeschl 7740: }
1.795     www      7741: 
1.840     bisitz   7742: .LC_Box {
1.911     bisitz   7743:   border: solid 1px $lg_border_color;
                   7744:   padding: 0 10px 10px 10px;
1.746     neumanie 7745: }
1.795     www      7746: 
1.1020    raeburn  7747: .LC_DocsBox {
                   7748:   border: solid 1px $lg_border_color;
                   7749:   padding: 0 0 10px 10px;
                   7750: }
                   7751: 
1.795     www      7752: .LC_AboutMe_Image {
1.911     bisitz   7753:   float:left;
                   7754:   margin-right:10px;
1.747     neumanie 7755: }
1.795     www      7756: 
                   7757: .LC_Clear_AboutMe_Image {
1.911     bisitz   7758:   clear:left;
1.747     neumanie 7759: }
1.795     www      7760: 
1.721     harmsja  7761: dl.LC_ListStyleClean dt {
1.911     bisitz   7762:   padding-right: 5px;
                   7763:   display: table-header-group;
1.693     droeschl 7764: }
                   7765: 
1.721     harmsja  7766: dl.LC_ListStyleClean dd {
1.911     bisitz   7767:   display: table-row;
1.693     droeschl 7768: }
                   7769: 
1.721     harmsja  7770: .LC_ListStyleClean,
                   7771: .LC_ListStyleSimple,
                   7772: .LC_ListStyleNormal,
1.795     www      7773: .LC_ListStyleSpecial {
1.911     bisitz   7774:   /* display:block; */
                   7775:   list-style-position: inside;
                   7776:   list-style-type: none;
                   7777:   overflow: hidden;
                   7778:   padding: 0;
1.693     droeschl 7779: }
                   7780: 
1.721     harmsja  7781: .LC_ListStyleSimple li,
                   7782: .LC_ListStyleSimple dd,
                   7783: .LC_ListStyleNormal li,
                   7784: .LC_ListStyleNormal dd,
                   7785: .LC_ListStyleSpecial li,
1.795     www      7786: .LC_ListStyleSpecial dd {
1.911     bisitz   7787:   margin: 0;
                   7788:   padding: 5px 5px 5px 10px;
                   7789:   clear: both;
1.693     droeschl 7790: }
                   7791: 
1.721     harmsja  7792: .LC_ListStyleClean li,
                   7793: .LC_ListStyleClean dd {
1.911     bisitz   7794:   padding-top: 0;
                   7795:   padding-bottom: 0;
1.693     droeschl 7796: }
                   7797: 
1.721     harmsja  7798: .LC_ListStyleSimple dd,
1.795     www      7799: .LC_ListStyleSimple li {
1.911     bisitz   7800:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7801: }
                   7802: 
1.721     harmsja  7803: .LC_ListStyleSpecial li,
                   7804: .LC_ListStyleSpecial dd {
1.911     bisitz   7805:   list-style-type: none;
                   7806:   background-color: RGB(220, 220, 220);
                   7807:   margin-bottom: 4px;
1.693     droeschl 7808: }
                   7809: 
1.721     harmsja  7810: table.LC_SimpleTable {
1.911     bisitz   7811:   margin:5px;
                   7812:   border:solid 1px $lg_border_color;
1.795     www      7813: }
1.693     droeschl 7814: 
1.721     harmsja  7815: table.LC_SimpleTable tr {
1.911     bisitz   7816:   padding: 0;
                   7817:   border:solid 1px $lg_border_color;
1.693     droeschl 7818: }
1.795     www      7819: 
                   7820: table.LC_SimpleTable thead {
1.911     bisitz   7821:   background:rgb(220,220,220);
1.693     droeschl 7822: }
                   7823: 
1.721     harmsja  7824: div.LC_columnSection {
1.911     bisitz   7825:   display: block;
                   7826:   clear: both;
                   7827:   overflow: hidden;
                   7828:   margin: 0;
1.693     droeschl 7829: }
                   7830: 
1.721     harmsja  7831: div.LC_columnSection>* {
1.911     bisitz   7832:   float: left;
                   7833:   margin: 10px 20px 10px 0;
                   7834:   overflow:hidden;
1.693     droeschl 7835: }
1.721     harmsja  7836: 
1.795     www      7837: table em {
1.911     bisitz   7838:   font-weight: bold;
                   7839:   font-style: normal;
1.748     schulted 7840: }
1.795     www      7841: 
1.779     bisitz   7842: table.LC_tableBrowseRes,
1.795     www      7843: table.LC_tableOfContent {
1.911     bisitz   7844:   border:none;
                   7845:   border-spacing: 1px;
                   7846:   padding: 3px;
                   7847:   background-color: #FFFFFF;
                   7848:   font-size: 90%;
1.753     droeschl 7849: }
1.789     droeschl 7850: 
1.911     bisitz   7851: table.LC_tableOfContent {
                   7852:   border-collapse: collapse;
1.789     droeschl 7853: }
                   7854: 
1.771     droeschl 7855: table.LC_tableBrowseRes a,
1.768     schulted 7856: table.LC_tableOfContent a {
1.911     bisitz   7857:   background-color: transparent;
                   7858:   text-decoration: none;
1.753     droeschl 7859: }
                   7860: 
1.795     www      7861: table.LC_tableOfContent img {
1.911     bisitz   7862:   border: none;
                   7863:   height: 1.3em;
                   7864:   vertical-align: text-bottom;
                   7865:   margin-right: 0.3em;
1.753     droeschl 7866: }
1.757     schulted 7867: 
1.795     www      7868: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7869:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7870: }
                   7871: 
1.795     www      7872: a#LC_content_toolbar_everything {
1.911     bisitz   7873:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7874: }
                   7875: 
1.795     www      7876: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7877:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7878: }
                   7879: 
1.795     www      7880: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7881:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7882: }
                   7883: 
1.795     www      7884: a#LC_content_toolbar_changefolder {
1.911     bisitz   7885:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7886: }
                   7887: 
1.795     www      7888: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7889:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7890: }
                   7891: 
1.1043    raeburn  7892: a#LC_content_toolbar_edittoplevel {
                   7893:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7894: }
                   7895: 
1.795     www      7896: ul#LC_toolbar li a:hover {
1.911     bisitz   7897:   background-position: bottom center;
1.757     schulted 7898: }
                   7899: 
1.795     www      7900: ul#LC_toolbar {
1.911     bisitz   7901:   padding: 0;
                   7902:   margin: 2px;
                   7903:   list-style:none;
                   7904:   position:relative;
                   7905:   background-color:white;
1.1082    raeburn  7906:   overflow: auto;
1.757     schulted 7907: }
                   7908: 
1.795     www      7909: ul#LC_toolbar li {
1.911     bisitz   7910:   border:1px solid white;
                   7911:   padding: 0;
                   7912:   margin: 0;
                   7913:   float: left;
                   7914:   display:inline;
                   7915:   vertical-align:middle;
1.1082    raeburn  7916:   white-space: nowrap;
1.911     bisitz   7917: }
1.757     schulted 7918: 
1.783     amueller 7919: 
1.795     www      7920: a.LC_toolbarItem {
1.911     bisitz   7921:   display:block;
                   7922:   padding: 0;
                   7923:   margin: 0;
                   7924:   height: 32px;
                   7925:   width: 32px;
                   7926:   color:white;
                   7927:   border: none;
                   7928:   background-repeat:no-repeat;
                   7929:   background-color:transparent;
1.757     schulted 7930: }
                   7931: 
1.915     droeschl 7932: ul.LC_funclist {
                   7933:     margin: 0;
                   7934:     padding: 0.5em 1em 0.5em 0;
                   7935: }
                   7936: 
1.933     droeschl 7937: ul.LC_funclist > li:first-child {
                   7938:     font-weight:bold; 
                   7939:     margin-left:0.8em;
                   7940: }
                   7941: 
1.915     droeschl 7942: ul.LC_funclist + ul.LC_funclist {
                   7943:     /* 
                   7944:        left border as a seperator if we have more than
                   7945:        one list 
                   7946:     */
                   7947:     border-left: 1px solid $sidebg;
                   7948:     /* 
                   7949:        this hides the left border behind the border of the 
                   7950:        outer box if element is wrapped to the next 'line' 
                   7951:     */
                   7952:     margin-left: -1px;
                   7953: }
                   7954: 
1.843     bisitz   7955: ul.LC_funclist li {
1.915     droeschl 7956:   display: inline;
1.782     bisitz   7957:   white-space: nowrap;
1.915     droeschl 7958:   margin: 0 0 0 25px;
                   7959:   line-height: 150%;
1.782     bisitz   7960: }
                   7961: 
1.974     wenzelju 7962: .LC_hidden {
                   7963:   display: none;
                   7964: }
                   7965: 
1.1030    www      7966: .LCmodal-overlay {
                   7967: 		position:fixed;
                   7968: 		top:0;
                   7969: 		right:0;
                   7970: 		bottom:0;
                   7971: 		left:0;
                   7972: 		height:100%;
                   7973: 		width:100%;
                   7974: 		margin:0;
                   7975: 		padding:0;
                   7976: 		background:#999;
                   7977: 		opacity:.75;
                   7978: 		filter: alpha(opacity=75);
                   7979: 		-moz-opacity: 0.75;
                   7980: 		z-index:101;
                   7981: }
                   7982: 
                   7983: * html .LCmodal-overlay {   
                   7984: 		position: absolute;
                   7985: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7986: }
                   7987: 
                   7988: .LCmodal-window {
                   7989: 		position:fixed;
                   7990: 		top:50%;
                   7991: 		left:50%;
                   7992: 		margin:0;
                   7993: 		padding:0;
                   7994: 		z-index:102;
                   7995: 	}
                   7996: 
                   7997: * html .LCmodal-window {
                   7998: 		position:absolute;
                   7999: }
                   8000: 
                   8001: .LCclose-window {
                   8002: 		position:absolute;
                   8003: 		width:32px;
                   8004: 		height:32px;
                   8005: 		right:8px;
                   8006: 		top:8px;
                   8007: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8008: 		text-indent:-99999px;
                   8009: 		overflow:hidden;
                   8010: 		cursor:pointer;
                   8011: }
                   8012: 
1.1100    raeburn  8013: /*
1.1231    damieng  8014:   styles used for response display
                   8015: */
                   8016: div.LC_radiofoil, div.LC_rankfoil {
                   8017:   margin: .5em 0em .5em 0em;
                   8018: }
                   8019: table.LC_itemgroup {
                   8020:   margin-top: 1em;
                   8021: }
                   8022: 
                   8023: /*
1.1100    raeburn  8024:   styles used by TTH when "Default set of options to pass to tth/m
                   8025:   when converting TeX" in course settings has been set
                   8026: 
                   8027:   option passed: -t
                   8028: 
                   8029: */
                   8030: 
                   8031: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8032: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8033: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8034: td div.norm {line-height:normal;}
                   8035: 
                   8036: /*
                   8037:   option passed -y3
                   8038: */
                   8039: 
                   8040: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8041: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8042: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8043: 
1.1230    damieng  8044: /*
                   8045:   sections with roles, for content only
                   8046: */
                   8047: section[class^="role-"] {
                   8048:   padding-left: 10px;
                   8049:   padding-right: 5px;
                   8050:   margin-top: 8px;
                   8051:   margin-bottom: 8px;
                   8052:   border: 1px solid #2A4;
                   8053:   border-radius: 5px;
                   8054:   box-shadow: 0px 1px 1px #BBB;
                   8055: }
                   8056: section[class^="role-"]>h1 {
                   8057:   position: relative;
                   8058:   margin: 0px;
                   8059:   padding-top: 10px;
                   8060:   padding-left: 40px;
                   8061: }
                   8062: section[class^="role-"]>h1:before {
                   8063:   position: absolute;
                   8064:   left: -5px;
                   8065:   top: 5px;
                   8066: }
                   8067: section.role-activity>h1:before {
                   8068:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8069: }
                   8070: section.role-advice>h1:before {
                   8071:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8072: }
                   8073: section.role-bibliography>h1:before {
                   8074:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8075: }
                   8076: section.role-citation>h1:before {
                   8077:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8078: }
                   8079: section.role-conclusion>h1:before {
                   8080:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8081: }
                   8082: section.role-definition>h1:before {
                   8083:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8084: }
                   8085: section.role-demonstration>h1:before {
                   8086:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8087: }
                   8088: section.role-example>h1:before {
                   8089:   content:url('/adm/daxe/images/section_icons/example.png');
                   8090: }
                   8091: section.role-explanation>h1:before {
                   8092:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8093: }
                   8094: section.role-introduction>h1:before {
                   8095:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8096: }
                   8097: section.role-method>h1:before {
                   8098:   content:url('/adm/daxe/images/section_icons/method.png');
                   8099: }
                   8100: section.role-more_information>h1:before {
                   8101:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8102: }
                   8103: section.role-objectives>h1:before {
                   8104:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8105: }
                   8106: section.role-prerequisites>h1:before {
                   8107:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8108: }
                   8109: section.role-remark>h1:before {
                   8110:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8111: }
                   8112: section.role-reminder>h1:before {
                   8113:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8114: }
                   8115: section.role-summary>h1:before {
                   8116:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8117: }
                   8118: section.role-syntax>h1:before {
                   8119:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8120: }
                   8121: section.role-warning>h1:before {
                   8122:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8123: }
                   8124: 
1.343     albertel 8125: END
                   8126: }
                   8127: 
1.306     albertel 8128: =pod
                   8129: 
                   8130: =item * &headtag()
                   8131: 
                   8132: Returns a uniform footer for LON-CAPA web pages.
                   8133: 
1.307     albertel 8134: Inputs: $title - optional title for the head
                   8135:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8136:         $args - optional arguments
1.319     albertel 8137:             force_register - if is true call registerurl so the remote is 
                   8138:                              informed
1.415     albertel 8139:             redirect       -> array ref of
                   8140:                                    1- seconds before redirect occurs
                   8141:                                    2- url to redirect to
                   8142:                                    3- whether the side effect should occur
1.315     albertel 8143:                            (side effect of setting 
                   8144:                                $env{'internal.head.redirect'} to the url 
                   8145:                                redirected too)
1.352     albertel 8146:             domain         -> force to color decorate a page for a specific
                   8147:                                domain
                   8148:             function       -> force usage of a specific rolish color scheme
                   8149:             bgcolor        -> override the default page bgcolor
1.460     albertel 8150:             no_auto_mt_title
                   8151:                            -> prevent &mt()ing the title arg
1.464     albertel 8152: 
1.306     albertel 8153: =cut
                   8154: 
                   8155: sub headtag {
1.313     albertel 8156:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8157:     
1.363     albertel 8158:     my $function = $args->{'function'} || &get_users_function();
                   8159:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8160:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8161:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8162:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8163: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8164: 		   #time(),
1.418     albertel 8165: 		   $env{'environment.color.timestamp'},
1.363     albertel 8166: 		   $function,$domain,$bgcolor);
                   8167: 
1.369     www      8168:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8169: 
1.308     albertel 8170:     my $result =
                   8171: 	'<head>'.
1.1160    raeburn  8172: 	&font_settings($args);
1.319     albertel 8173: 
1.1188    raeburn  8174:     my $inhibitprint;
                   8175:     if ($args->{'print_suppress'}) {
                   8176:         $inhibitprint = &print_suppression();
                   8177:     }
1.1064    raeburn  8178: 
1.461     albertel 8179:     if (!$args->{'frameset'}) {
                   8180: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8181:     }
1.962     droeschl 8182:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8183:         $result .= Apache::lonxml::display_title();
1.319     albertel 8184:     }
1.436     albertel 8185:     if (!$args->{'no_nav_bar'} 
                   8186: 	&& !$args->{'only_body'}
                   8187: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8188: 	$result .= &help_menu_js($httphost);
1.1032    www      8189:         $result.=&modal_window();
1.1038    www      8190:         $result.=&togglebox_script();
1.1034    www      8191:         $result.=&wishlist_window();
1.1041    www      8192:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8193:     } else {
                   8194:         if ($args->{'add_modal'}) {
                   8195:            $result.=&modal_window();
                   8196:         }
                   8197:         if ($args->{'add_wishlist'}) {
                   8198:            $result.=&wishlist_window();
                   8199:         }
1.1038    www      8200:         if ($args->{'add_togglebox'}) {
                   8201:            $result.=&togglebox_script();
                   8202:         }
1.1041    www      8203:         if ($args->{'add_progressbar'}) {
                   8204:            $result.=&LCprogressbarUpdate_script();
                   8205:         }
1.436     albertel 8206:     }
1.314     albertel 8207:     if (ref($args->{'redirect'})) {
1.414     albertel 8208: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8209: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8210: 	if (!$inhibit_continue) {
                   8211: 	    $env{'internal.head.redirect'} = $url;
                   8212: 	}
1.313     albertel 8213: 	$result.=<<ADDMETA
                   8214: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8215: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8216: ADDMETA
1.1210    raeburn  8217:     } else {
                   8218:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8219:             my $requrl = $env{'request.uri'};
                   8220:             if ($requrl eq '') {
                   8221:                 $requrl = $ENV{'REQUEST_URI'};
                   8222:                 $requrl =~ s/\?.+$//;
                   8223:             }
                   8224:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8225:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8226:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8227:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8228:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8229:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   8230:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8231:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   8232:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   8233:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8234:                             if (($newserver) && ($newserver ne $lonhost)) {
                   8235:                                 my $numsec = 5;
                   8236:                                 my $timeout = $numsec * 1000;
                   8237:                                 my ($newurl,$locknum,%locks,$msg);
                   8238:                                 if ($env{'request.role.adv'}) {
                   8239:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8240:                                 }
                   8241:                                 my $disable_submit = 0;
                   8242:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   8243:                                     $disable_submit = 1;
                   8244:                                 }
                   8245:                                 if ($locknum) {
                   8246:                                     my @lockinfo = sort(values(%locks));
                   8247:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   8248:                                            join(", ",sort(values(%locks)))."\\n".
                   8249:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   8250:                                 } else {
                   8251:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8252:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   8253:                                     }
                   8254:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8255:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8256:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8257:                                         $newurl .= '&role='.$env{'request.role'};
                   8258:                                     }
                   8259:                                     if ($env{'request.symb'}) {
                   8260:                                         $newurl .= '&symb='.$env{'request.symb'};
                   8261:                                     } else {
                   8262:                                         $newurl .= '&origurl='.$requrl;
                   8263:                                     }
                   8264:                                 }
1.1222    damieng  8265:                                 &js_escape(\$msg);
1.1210    raeburn  8266:                                 $result.=<<OFFLOAD
                   8267: <meta http-equiv="pragma" content="no-cache" />
                   8268: <script type="text/javascript">
1.1215    raeburn  8269: // <![CDATA[
1.1210    raeburn  8270: function LC_Offload_Now() {
                   8271:     var dest = "$newurl";
                   8272:     if (dest != '') {
                   8273:         window.location.href="$newurl";
                   8274:     }
                   8275: }
1.1214    raeburn  8276: \$(document).ready(function () {
                   8277:     window.alert('$msg');
                   8278:     if ($disable_submit) {
1.1210    raeburn  8279:         \$(".LC_hwk_submit").prop("disabled", true);
                   8280:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8281:     }
                   8282:     setTimeout('LC_Offload_Now()', $timeout);
                   8283: });
1.1215    raeburn  8284: // ]]>
1.1210    raeburn  8285: </script>
                   8286: OFFLOAD
                   8287:                             }
                   8288:                         }
                   8289:                     }
                   8290:                 }
                   8291:             }
                   8292:         }
1.313     albertel 8293:     }
1.306     albertel 8294:     if (!defined($title)) {
                   8295: 	$title = 'The LearningOnline Network with CAPA';
                   8296:     }
1.460     albertel 8297:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8298:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8299: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8300:     if (!$args->{'frameset'}) {
                   8301:         $result .= ' /';
                   8302:     }
                   8303:     $result .= '>' 
1.1064    raeburn  8304:         .$inhibitprint
1.414     albertel 8305: 	.$head_extra;
1.1242    raeburn  8306:     my $clientmobile;
                   8307:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8308:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8309:     } else {
                   8310:         $clientmobile = $env{'browser.mobile'};
                   8311:     }
                   8312:     if ($clientmobile) {
1.1137    raeburn  8313:         $result .= '
                   8314: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8315: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8316:     }
1.962     droeschl 8317:     return $result.'</head>';
1.306     albertel 8318: }
                   8319: 
                   8320: =pod
                   8321: 
1.340     albertel 8322: =item * &font_settings()
                   8323: 
                   8324: Returns neccessary <meta> to set the proper encoding
                   8325: 
1.1160    raeburn  8326: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8327: 
                   8328: =cut
                   8329: 
                   8330: sub font_settings {
1.1160    raeburn  8331:     my ($args) = @_;
1.340     albertel 8332:     my $headerstring='';
1.1160    raeburn  8333:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8334:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8335:         $headerstring.=
                   8336:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8337:         if (!$args->{'frameset'}) {
                   8338: 	    $headerstring.= ' /';
                   8339:         }
                   8340: 	$headerstring .= '>'."\n";
1.340     albertel 8341:     }
                   8342:     return $headerstring;
                   8343: }
                   8344: 
1.341     albertel 8345: =pod
                   8346: 
1.1064    raeburn  8347: =item * &print_suppression()
                   8348: 
                   8349: In course context returns css which causes the body to be blank when media="print",
                   8350: if printout generation is unavailable for the current resource.
                   8351: 
                   8352: This could be because:
                   8353: 
                   8354: (a) printstartdate is in the future
                   8355: 
                   8356: (b) printenddate is in the past
                   8357: 
                   8358: (c) there is an active exam block with "printout"
                   8359: functionality blocked
                   8360: 
                   8361: Users with pav, pfo or evb privileges are exempt.
                   8362: 
                   8363: Inputs: none
                   8364: 
                   8365: =cut
                   8366: 
                   8367: 
                   8368: sub print_suppression {
                   8369:     my $noprint;
                   8370:     if ($env{'request.course.id'}) {
                   8371:         my $scope = $env{'request.course.id'};
                   8372:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8373:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8374:             return;
                   8375:         }
                   8376:         if ($env{'request.course.sec'} ne '') {
                   8377:             $scope .= "/$env{'request.course.sec'}";
                   8378:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8379:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8380:                 return;
1.1064    raeburn  8381:             }
                   8382:         }
                   8383:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8384:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8385:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8386:         if ($blocked) {
                   8387:             my $checkrole = "cm./$cdom/$cnum";
                   8388:             if ($env{'request.course.sec'} ne '') {
                   8389:                 $checkrole .= "/$env{'request.course.sec'}";
                   8390:             }
                   8391:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8392:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8393:                 $noprint = 1;
                   8394:             }
                   8395:         }
                   8396:         unless ($noprint) {
                   8397:             my $symb = &Apache::lonnet::symbread();
                   8398:             if ($symb ne '') {
                   8399:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8400:                 if (ref($navmap)) {
                   8401:                     my $res = $navmap->getBySymb($symb);
                   8402:                     if (ref($res)) {
                   8403:                         if (!$res->resprintable()) {
                   8404:                             $noprint = 1;
                   8405:                         }
                   8406:                     }
                   8407:                 }
                   8408:             }
                   8409:         }
                   8410:         if ($noprint) {
                   8411:             return <<"ENDSTYLE";
                   8412: <style type="text/css" media="print">
                   8413:     body { display:none }
                   8414: </style>
                   8415: ENDSTYLE
                   8416:         }
                   8417:     }
                   8418:     return;
                   8419: }
                   8420: 
                   8421: =pod
                   8422: 
1.341     albertel 8423: =item * &xml_begin()
                   8424: 
                   8425: Returns the needed doctype and <html>
                   8426: 
                   8427: Inputs: none
                   8428: 
                   8429: =cut
                   8430: 
                   8431: sub xml_begin {
1.1168    raeburn  8432:     my ($is_frameset) = @_;
1.341     albertel 8433:     my $output='';
                   8434: 
                   8435:     if ($env{'browser.mathml'}) {
                   8436: 	$output='<?xml version="1.0"?>'
                   8437:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8438: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8439:             
                   8440: #	    .'<!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">] >'
                   8441: 	    .'<!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">'
                   8442:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8443: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8444:     } elsif ($is_frameset) {
                   8445:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8446:                 '<html>'."\n";
1.341     albertel 8447:     } else {
1.1168    raeburn  8448: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8449:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8450:     }
                   8451:     return $output;
                   8452: }
1.340     albertel 8453: 
                   8454: =pod
                   8455: 
1.306     albertel 8456: =item * &start_page()
                   8457: 
                   8458: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8459: 
1.648     raeburn  8460: Inputs:
                   8461: 
                   8462: =over 4
                   8463: 
                   8464: $title - optional title for the page
                   8465: 
                   8466: $head_extra - optional extra HTML to incude inside the <head>
                   8467: 
                   8468: $args - additional optional args supported are:
                   8469: 
                   8470: =over 8
                   8471: 
                   8472:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8473:                                     arg on
1.814     bisitz   8474:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8475:              add_entries    -> additional attributes to add to the  <body>
                   8476:              domain         -> force to color decorate a page for a 
1.317     albertel 8477:                                     specific domain
1.648     raeburn  8478:              function       -> force usage of a specific rolish color
1.317     albertel 8479:                                     scheme
1.648     raeburn  8480:              redirect       -> see &headtag()
                   8481:              bgcolor        -> override the default page bg color
                   8482:              js_ready       -> return a string ready for being used in 
1.317     albertel 8483:                                     a javascript writeln
1.648     raeburn  8484:              html_encode    -> return a string ready for being used in 
1.320     albertel 8485:                                     a html attribute
1.648     raeburn  8486:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8487:                                     $forcereg arg
1.648     raeburn  8488:              frameset       -> if true will start with a <frameset>
1.330     albertel 8489:                                     rather than <body>
1.648     raeburn  8490:              skip_phases    -> hash ref of 
1.338     albertel 8491:                                     head -> skip the <html><head> generation
                   8492:                                     body -> skip all <body> generation
1.648     raeburn  8493:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8494:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8495:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  8496:              group          -> includes the current group, if page is for a 
                   8497:                                specific group  
1.361     albertel 8498: 
1.648     raeburn  8499: =back
1.460     albertel 8500: 
1.648     raeburn  8501: =back
1.562     albertel 8502: 
1.306     albertel 8503: =cut
                   8504: 
                   8505: sub start_page {
1.309     albertel 8506:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8507:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8508: 
1.315     albertel 8509:     $env{'internal.start_page'}++;
1.1096    raeburn  8510:     my ($result,@advtools);
1.964     droeschl 8511: 
1.338     albertel 8512:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8513:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8514:     }
                   8515:     
                   8516:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8517: 	if ($args->{'frameset'}) {
                   8518: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8519: 						$args->{'add_entries'});
                   8520: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8521:         } else {
                   8522:             $result .=
                   8523:                 &bodytag($title, 
                   8524:                          $args->{'function'},       $args->{'add_entries'},
                   8525:                          $args->{'only_body'},      $args->{'domain'},
                   8526:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8527:                          $args->{'bgcolor'},        $args,
                   8528:                          \@advtools);
1.831     bisitz   8529:         }
1.330     albertel 8530:     }
1.338     albertel 8531: 
1.315     albertel 8532:     if ($args->{'js_ready'}) {
1.713     kaisler  8533: 		$result = &js_ready($result);
1.315     albertel 8534:     }
1.320     albertel 8535:     if ($args->{'html_encode'}) {
1.713     kaisler  8536: 		$result = &html_encode($result);
                   8537:     }
                   8538: 
1.813     bisitz   8539:     # Preparation for new and consistent functionlist at top of screen
                   8540:     # if ($args->{'functionlist'}) {
                   8541:     #            $result .= &build_functionlist();
                   8542:     #}
                   8543: 
1.964     droeschl 8544:     # Don't add anything more if only_body wanted or in const space
                   8545:     return $result if    $args->{'only_body'} 
                   8546:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8547: 
                   8548:     #Breadcrumbs
1.758     kaisler  8549:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8550: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8551: 		#if any br links exists, add them to the breadcrumbs
                   8552: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8553: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8554: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8555: 			}
                   8556: 		}
1.1096    raeburn  8557:                 # if @advtools array contains items add then to the breadcrumbs
                   8558:                 if (@advtools > 0) {
                   8559:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8560:                 }
1.758     kaisler  8561: 
                   8562: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8563: 		if(exists($args->{'bread_crumbs_component'})){
                   8564: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
1.1237    raeburn  8565: 		} elsif ($args->{'crstype'} eq 'Placement') {
                   8566: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','','','','','','','','',
                   8567:                                                                        $args->{'crstype'});
                   8568:                 } else {
1.758     kaisler  8569: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   8570: 		}
1.320     albertel 8571:     }
1.315     albertel 8572:     return $result;
1.306     albertel 8573: }
                   8574: 
                   8575: sub end_page {
1.315     albertel 8576:     my ($args) = @_;
                   8577:     $env{'internal.end_page'}++;
1.330     albertel 8578:     my $result;
1.335     albertel 8579:     if ($args->{'discussion'}) {
                   8580: 	my ($target,$parser);
                   8581: 	if (ref($args->{'discussion'})) {
                   8582: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8583: 				$args->{'discussion'}{'parser'});
                   8584: 	}
                   8585: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8586:     }
1.330     albertel 8587:     if ($args->{'frameset'}) {
                   8588: 	$result .= '</frameset>';
                   8589:     } else {
1.635     raeburn  8590: 	$result .= &endbodytag($args);
1.330     albertel 8591:     }
1.1080    raeburn  8592:     unless ($args->{'notbody'}) {
                   8593:         $result .= "\n</html>";
                   8594:     }
1.330     albertel 8595: 
1.315     albertel 8596:     if ($args->{'js_ready'}) {
1.317     albertel 8597: 	$result = &js_ready($result);
1.315     albertel 8598:     }
1.335     albertel 8599: 
1.320     albertel 8600:     if ($args->{'html_encode'}) {
                   8601: 	$result = &html_encode($result);
                   8602:     }
1.335     albertel 8603: 
1.315     albertel 8604:     return $result;
                   8605: }
                   8606: 
1.1034    www      8607: sub wishlist_window {
                   8608:     return(<<'ENDWISHLIST');
1.1046    raeburn  8609: <script type="text/javascript">
1.1034    www      8610: // <![CDATA[
                   8611: // <!-- BEGIN LON-CAPA Internal
                   8612: function set_wishlistlink(title, path) {
                   8613:     if (!title) {
                   8614:         title = document.title;
                   8615:         title = title.replace(/^LON-CAPA /,'');
                   8616:     }
1.1175    raeburn  8617:     title = encodeURIComponent(title);
1.1203    raeburn  8618:     title = title.replace("'","\\\'");
1.1034    www      8619:     if (!path) {
                   8620:         path = location.pathname;
                   8621:     }
1.1175    raeburn  8622:     path = encodeURIComponent(path);
1.1203    raeburn  8623:     path = path.replace("'","\\\'");
1.1034    www      8624:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8625:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8626: }
                   8627: // END LON-CAPA Internal -->
                   8628: // ]]>
                   8629: </script>
                   8630: ENDWISHLIST
                   8631: }
                   8632: 
1.1030    www      8633: sub modal_window {
                   8634:     return(<<'ENDMODAL');
1.1046    raeburn  8635: <script type="text/javascript">
1.1030    www      8636: // <![CDATA[
                   8637: // <!-- BEGIN LON-CAPA Internal
                   8638: var modalWindow = {
                   8639: 	parent:"body",
                   8640: 	windowId:null,
                   8641: 	content:null,
                   8642: 	width:null,
                   8643: 	height:null,
                   8644: 	close:function()
                   8645: 	{
                   8646: 	        $(".LCmodal-window").remove();
                   8647: 	        $(".LCmodal-overlay").remove();
                   8648: 	},
                   8649: 	open:function()
                   8650: 	{
                   8651: 		var modal = "";
                   8652: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8653: 		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;\">";
                   8654: 		modal += this.content;
                   8655: 		modal += "</div>";	
                   8656: 
                   8657: 		$(this.parent).append(modal);
                   8658: 
                   8659: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8660: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8661: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8662: 	}
                   8663: };
1.1140    raeburn  8664: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8665: 	{
1.1266    raeburn  8666:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8667: 		modalWindow.windowId = "myModal";
                   8668: 		modalWindow.width = width;
                   8669: 		modalWindow.height = height;
1.1196    raeburn  8670: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8671: 		modalWindow.open();
1.1208    raeburn  8672: 	};
1.1030    www      8673: // END LON-CAPA Internal -->
                   8674: // ]]>
                   8675: </script>
                   8676: ENDMODAL
                   8677: }
                   8678: 
                   8679: sub modal_link {
1.1140    raeburn  8680:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8681:     unless ($width) { $width=480; }
                   8682:     unless ($height) { $height=400; }
1.1031    www      8683:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8684:     unless ($transparency) { $transparency='true'; }
                   8685: 
1.1074    raeburn  8686:     my $target_attr;
                   8687:     if (defined($target)) {
                   8688:         $target_attr = 'target="'.$target.'"';
                   8689:     }
                   8690:     return <<"ENDLINK";
1.1140    raeburn  8691: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8692:            $linktext</a>
                   8693: ENDLINK
1.1030    www      8694: }
                   8695: 
1.1032    www      8696: sub modal_adhoc_script {
                   8697:     my ($funcname,$width,$height,$content)=@_;
                   8698:     return (<<ENDADHOC);
1.1046    raeburn  8699: <script type="text/javascript">
1.1032    www      8700: // <![CDATA[
                   8701:         var $funcname = function()
                   8702:         {
                   8703:                 modalWindow.windowId = "myModal";
                   8704:                 modalWindow.width = $width;
                   8705:                 modalWindow.height = $height;
                   8706:                 modalWindow.content = '$content';
                   8707:                 modalWindow.open();
                   8708:         };  
                   8709: // ]]>
                   8710: </script>
                   8711: ENDADHOC
                   8712: }
                   8713: 
1.1041    www      8714: sub modal_adhoc_inner {
                   8715:     my ($funcname,$width,$height,$content)=@_;
                   8716:     my $innerwidth=$width-20;
                   8717:     $content=&js_ready(
1.1140    raeburn  8718:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8719:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8720:                  $content.
1.1041    www      8721:                  &end_scrollbox().
1.1140    raeburn  8722:                  &end_page()
1.1041    www      8723:              );
                   8724:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8725: }
                   8726: 
                   8727: sub modal_adhoc_window {
                   8728:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8729:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8730:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8731: }
                   8732: 
                   8733: sub modal_adhoc_launch {
                   8734:     my ($funcname,$width,$height,$content)=@_;
                   8735:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8736: <script type="text/javascript">
                   8737: // <![CDATA[
                   8738: $funcname();
                   8739: // ]]>
                   8740: </script>
                   8741: ENDLAUNCH
                   8742: }
                   8743: 
                   8744: sub modal_adhoc_close {
                   8745:     return (<<ENDCLOSE);
                   8746: <script type="text/javascript">
                   8747: // <![CDATA[
                   8748: modalWindow.close();
                   8749: // ]]>
                   8750: </script>
                   8751: ENDCLOSE
                   8752: }
                   8753: 
1.1038    www      8754: sub togglebox_script {
                   8755:    return(<<ENDTOGGLE);
                   8756: <script type="text/javascript"> 
                   8757: // <![CDATA[
                   8758: function LCtoggleDisplay(id,hidetext,showtext) {
                   8759:    link = document.getElementById(id + "link").childNodes[0];
                   8760:    with (document.getElementById(id).style) {
                   8761:       if (display == "none" ) {
                   8762:           display = "inline";
                   8763:           link.nodeValue = hidetext;
                   8764:         } else {
                   8765:           display = "none";
                   8766:           link.nodeValue = showtext;
                   8767:        }
                   8768:    }
                   8769: }
                   8770: // ]]>
                   8771: </script>
                   8772: ENDTOGGLE
                   8773: }
                   8774: 
1.1039    www      8775: sub start_togglebox {
                   8776:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8777:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8778:     unless ($showtext) { $showtext=&mt('show'); }
                   8779:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8780:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8781:     return &start_data_table().
                   8782:            &start_data_table_header_row().
                   8783:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8784:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8785:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8786:            &end_data_table_header_row().
                   8787:            '<tr id="'.$id.'" style="display:none""><td>';
                   8788: }
                   8789: 
                   8790: sub end_togglebox {
                   8791:     return '</td></tr>'.&end_data_table();
                   8792: }
                   8793: 
1.1041    www      8794: sub LCprogressbar_script {
1.1045    www      8795:    my ($id)=@_;
1.1041    www      8796:    return(<<ENDPROGRESS);
                   8797: <script type="text/javascript">
                   8798: // <![CDATA[
1.1045    www      8799: \$('#progressbar$id').progressbar({
1.1041    www      8800:   value: 0,
                   8801:   change: function(event, ui) {
                   8802:     var newVal = \$(this).progressbar('option', 'value');
                   8803:     \$('.pblabel', this).text(LCprogressTxt);
                   8804:   }
                   8805: });
                   8806: // ]]>
                   8807: </script>
                   8808: ENDPROGRESS
                   8809: }
                   8810: 
                   8811: sub LCprogressbarUpdate_script {
                   8812:    return(<<ENDPROGRESSUPDATE);
                   8813: <style type="text/css">
                   8814: .ui-progressbar { position:relative; }
                   8815: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8816: </style>
                   8817: <script type="text/javascript">
                   8818: // <![CDATA[
1.1045    www      8819: var LCprogressTxt='---';
                   8820: 
                   8821: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8822:    LCprogressTxt=progresstext;
1.1045    www      8823:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8824: }
                   8825: // ]]>
                   8826: </script>
                   8827: ENDPROGRESSUPDATE
                   8828: }
                   8829: 
1.1042    www      8830: my $LClastpercent;
1.1045    www      8831: my $LCidcnt;
                   8832: my $LCcurrentid;
1.1042    www      8833: 
1.1041    www      8834: sub LCprogressbar {
1.1042    www      8835:     my ($r)=(@_);
                   8836:     $LClastpercent=0;
1.1045    www      8837:     $LCidcnt++;
                   8838:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8839:     my $starting=&mt('Starting');
                   8840:     my $content=(<<ENDPROGBAR);
1.1045    www      8841:   <div id="progressbar$LCcurrentid">
1.1041    www      8842:     <span class="pblabel">$starting</span>
                   8843:   </div>
                   8844: ENDPROGBAR
1.1045    www      8845:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8846: }
                   8847: 
                   8848: sub LCprogressbarUpdate {
1.1042    www      8849:     my ($r,$val,$text)=@_;
                   8850:     unless ($val) { 
                   8851:        if ($LClastpercent) {
                   8852:            $val=$LClastpercent;
                   8853:        } else {
                   8854:            $val=0;
                   8855:        }
                   8856:     }
1.1041    www      8857:     if ($val<0) { $val=0; }
                   8858:     if ($val>100) { $val=0; }
1.1042    www      8859:     $LClastpercent=$val;
1.1041    www      8860:     unless ($text) { $text=$val.'%'; }
                   8861:     $text=&js_ready($text);
1.1044    www      8862:     &r_print($r,<<ENDUPDATE);
1.1041    www      8863: <script type="text/javascript">
                   8864: // <![CDATA[
1.1045    www      8865: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8866: // ]]>
                   8867: </script>
                   8868: ENDUPDATE
1.1035    www      8869: }
                   8870: 
1.1042    www      8871: sub LCprogressbarClose {
                   8872:     my ($r)=@_;
                   8873:     $LClastpercent=0;
1.1044    www      8874:     &r_print($r,<<ENDCLOSE);
1.1042    www      8875: <script type="text/javascript">
                   8876: // <![CDATA[
1.1045    www      8877: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8878: // ]]>
                   8879: </script>
                   8880: ENDCLOSE
1.1044    www      8881: }
                   8882: 
                   8883: sub r_print {
                   8884:     my ($r,$to_print)=@_;
                   8885:     if ($r) {
                   8886:       $r->print($to_print);
                   8887:       $r->rflush();
                   8888:     } else {
                   8889:       print($to_print);
                   8890:     }
1.1042    www      8891: }
                   8892: 
1.320     albertel 8893: sub html_encode {
                   8894:     my ($result) = @_;
                   8895: 
1.322     albertel 8896:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8897:     
                   8898:     return $result;
                   8899: }
1.1044    www      8900: 
1.317     albertel 8901: sub js_ready {
                   8902:     my ($result) = @_;
                   8903: 
1.323     albertel 8904:     $result =~ s/[\n\r]/ /xmsg;
                   8905:     $result =~ s/\\/\\\\/xmsg;
                   8906:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8907:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8908:     
                   8909:     return $result;
                   8910: }
                   8911: 
1.315     albertel 8912: sub validate_page {
                   8913:     if (  exists($env{'internal.start_page'})
1.316     albertel 8914: 	  &&     $env{'internal.start_page'} > 1) {
                   8915: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8916: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8917: 				 $ENV{'request.filename'});
1.315     albertel 8918:     }
                   8919:     if (  exists($env{'internal.end_page'})
1.316     albertel 8920: 	  &&     $env{'internal.end_page'} > 1) {
                   8921: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8922: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8923: 				 $env{'request.filename'});
1.315     albertel 8924:     }
                   8925:     if (     exists($env{'internal.start_page'})
                   8926: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8927: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8928: 				 $env{'request.filename'});
1.315     albertel 8929:     }
                   8930:     if (   ! exists($env{'internal.start_page'})
                   8931: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8932: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8933: 				 $env{'request.filename'});
1.315     albertel 8934:     }
1.306     albertel 8935: }
1.315     albertel 8936: 
1.996     www      8937: 
                   8938: sub start_scrollbox {
1.1140    raeburn  8939:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8940:     unless ($outerwidth) { $outerwidth='520px'; }
                   8941:     unless ($width) { $width='500px'; }
                   8942:     unless ($height) { $height='200px'; }
1.1075    raeburn  8943:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8944:     if ($id ne '') {
1.1140    raeburn  8945:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  8946:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8947:     }
1.1075    raeburn  8948:     if ($bgcolor ne '') {
                   8949:         $tdcol = "background-color: $bgcolor;";
                   8950:     }
1.1137    raeburn  8951:     my $nicescroll_js;
                   8952:     if ($env{'browser.mobile'}) {
1.1140    raeburn  8953:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8954:     }
                   8955:     return <<"END";
                   8956: $nicescroll_js
                   8957: 
                   8958: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   8959: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   8960: END
                   8961: }
                   8962: 
                   8963: sub end_scrollbox {
                   8964:     return '</div></td></tr></table>';
                   8965: }
                   8966: 
                   8967: sub nicescroll_javascript {
                   8968:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8969:     my %options;
                   8970:     if (ref($cursor) eq 'HASH') {
                   8971:         %options = %{$cursor};
                   8972:     }
                   8973:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8974:         $options{'railalign'} = 'left';
                   8975:     }
                   8976:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8977:         my $function  = &get_users_function();
                   8978:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  8979:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  8980:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  8981:         }
1.1140    raeburn  8982:     }
                   8983:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8984:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  8985:             $options{'cursoropacity'}='1.0';
                   8986:         }
1.1140    raeburn  8987:     } else {
                   8988:         $options{'cursoropacity'}='1.0';
                   8989:     }
                   8990:     if ($options{'cursorfixedheight'} eq 'none') {
                   8991:         delete($options{'cursorfixedheight'});
                   8992:     } else {
                   8993:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8994:     }
                   8995:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8996:         delete($options{'railoffset'});
                   8997:     }
                   8998:     my @niceoptions;
                   8999:     while (my($key,$value) = each(%options)) {
                   9000:         if ($value =~ /^\{.+\}$/) {
                   9001:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9002:         } else {
1.1140    raeburn  9003:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9004:         }
1.1140    raeburn  9005:     }
                   9006:     my $nicescroll_js = '
1.1137    raeburn  9007: $(document).ready(
1.1140    raeburn  9008:       function() {
                   9009:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9010:       }
1.1137    raeburn  9011: );
                   9012: ';
1.1140    raeburn  9013:     if ($framecheck) {
                   9014:         $nicescroll_js .= '
                   9015: function expand_div(caller) {
                   9016:     if (top === self) {
                   9017:         document.getElementById("'.$id.'").style.width = "auto";
                   9018:         document.getElementById("'.$id.'").style.height = "auto";
                   9019:     } else {
                   9020:         try {
                   9021:             if (parent.frames) {
                   9022:                 if (parent.frames.length > 1) {
                   9023:                     var framesrc = parent.frames[1].location.href;
                   9024:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9025:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9026:                         document.getElementById("'.$id.'").style.width = "auto";
                   9027:                         document.getElementById("'.$id.'").style.height = "auto";
                   9028:                     }
                   9029:                 }
                   9030:             }
                   9031:         } catch (e) {
                   9032:             return;
                   9033:         }
1.1137    raeburn  9034:     }
1.1140    raeburn  9035:     return;
1.996     www      9036: }
1.1140    raeburn  9037: ';
                   9038:     }
                   9039:     if ($needjsready) {
                   9040:         $nicescroll_js = '
                   9041: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9042:     } else {
                   9043:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9044:     }
                   9045:     return $nicescroll_js;
1.996     www      9046: }
                   9047: 
1.318     albertel 9048: sub simple_error_page {
1.1150    bisitz   9049:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  9050:     if (ref($args) eq 'HASH') {
                   9051:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   9052:     } else {
                   9053:         $msg = &mt($msg);
                   9054:     }
1.1150    bisitz   9055: 
1.318     albertel 9056:     my $page =
                   9057: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   9058: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9059: 	&Apache::loncommon::end_page();
                   9060:     if (ref($r)) {
                   9061: 	$r->print($page);
1.327     albertel 9062: 	return;
1.318     albertel 9063:     }
                   9064:     return $page;
                   9065: }
1.347     albertel 9066: 
                   9067: {
1.610     albertel 9068:     my @row_count;
1.961     onken    9069: 
                   9070:     sub start_data_table_count {
                   9071:         unshift(@row_count, 0);
                   9072:         return;
                   9073:     }
                   9074: 
                   9075:     sub end_data_table_count {
                   9076:         shift(@row_count);
                   9077:         return;
                   9078:     }
                   9079: 
1.347     albertel 9080:     sub start_data_table {
1.1018    raeburn  9081: 	my ($add_class,$id) = @_;
1.422     albertel 9082: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9083:         my $table_id;
                   9084:         if (defined($id)) {
                   9085:             $table_id = ' id="'.$id.'"';
                   9086:         }
1.961     onken    9087: 	&start_data_table_count();
1.1018    raeburn  9088: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9089:     }
                   9090: 
                   9091:     sub end_data_table {
1.961     onken    9092: 	&end_data_table_count();
1.389     albertel 9093: 	return '</table>'."\n";;
1.347     albertel 9094:     }
                   9095: 
                   9096:     sub start_data_table_row {
1.974     wenzelju 9097: 	my ($add_class, $id) = @_;
1.610     albertel 9098: 	$row_count[0]++;
                   9099: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9100: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9101:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9102:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9103:     }
1.471     banghart 9104:     
                   9105:     sub continue_data_table_row {
1.974     wenzelju 9106: 	my ($add_class, $id) = @_;
1.610     albertel 9107: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9108: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9109:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9110:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9111:     }
1.347     albertel 9112: 
                   9113:     sub end_data_table_row {
1.389     albertel 9114: 	return '</tr>'."\n";;
1.347     albertel 9115:     }
1.367     www      9116: 
1.421     albertel 9117:     sub start_data_table_empty_row {
1.707     bisitz   9118: #	$row_count[0]++;
1.421     albertel 9119: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9120:     }
                   9121: 
                   9122:     sub end_data_table_empty_row {
                   9123: 	return '</tr>'."\n";;
                   9124:     }
                   9125: 
1.367     www      9126:     sub start_data_table_header_row {
1.389     albertel 9127: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9128:     }
                   9129: 
                   9130:     sub end_data_table_header_row {
1.389     albertel 9131: 	return '</tr>'."\n";;
1.367     www      9132:     }
1.890     droeschl 9133: 
                   9134:     sub data_table_caption {
                   9135:         my $caption = shift;
                   9136:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9137:     }
1.347     albertel 9138: }
                   9139: 
1.548     albertel 9140: =pod
                   9141: 
                   9142: =item * &inhibit_menu_check($arg)
                   9143: 
                   9144: Checks for a inhibitmenu state and generates output to preserve it
                   9145: 
                   9146: Inputs:         $arg - can be any of
                   9147:                      - undef - in which case the return value is a string 
                   9148:                                to add  into arguments list of a uri
                   9149:                      - 'input' - in which case the return value is a HTML
                   9150:                                  <form> <input> field of type hidden to
                   9151:                                  preserve the value
                   9152:                      - a url - in which case the return value is the url with
                   9153:                                the neccesary cgi args added to preserve the
                   9154:                                inhibitmenu state
                   9155:                      - a ref to a url - no return value, but the string is
                   9156:                                         updated to include the neccessary cgi
                   9157:                                         args to preserve the inhibitmenu state
                   9158: 
                   9159: =cut
                   9160: 
                   9161: sub inhibit_menu_check {
                   9162:     my ($arg) = @_;
                   9163:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9164:     if ($arg eq 'input') {
                   9165: 	if ($env{'form.inhibitmenu'}) {
                   9166: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9167: 	} else {
                   9168: 	    return
                   9169: 	}
                   9170:     }
                   9171:     if ($env{'form.inhibitmenu'}) {
                   9172: 	if (ref($arg)) {
                   9173: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9174: 	} elsif ($arg eq '') {
                   9175: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9176: 	} else {
                   9177: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9178: 	}
                   9179:     }
                   9180:     if (!ref($arg)) {
                   9181: 	return $arg;
                   9182:     }
                   9183: }
                   9184: 
1.251     albertel 9185: ###############################################
1.182     matthew  9186: 
                   9187: =pod
                   9188: 
1.549     albertel 9189: =back
                   9190: 
                   9191: =head1 User Information Routines
                   9192: 
                   9193: =over 4
                   9194: 
1.405     albertel 9195: =item * &get_users_function()
1.182     matthew  9196: 
                   9197: Used by &bodytag to determine the current users primary role.
                   9198: Returns either 'student','coordinator','admin', or 'author'.
                   9199: 
                   9200: =cut
                   9201: 
                   9202: ###############################################
                   9203: sub get_users_function {
1.815     tempelho 9204:     my $function = 'norole';
1.818     tempelho 9205:     if ($env{'request.role'}=~/^(st)/) {
                   9206:         $function='student';
                   9207:     }
1.907     raeburn  9208:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9209:         $function='coordinator';
                   9210:     }
1.258     albertel 9211:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9212:         $function='admin';
                   9213:     }
1.826     bisitz   9214:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9215:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9216:         $function='author';
                   9217:     }
                   9218:     return $function;
1.54      www      9219: }
1.99      www      9220: 
                   9221: ###############################################
                   9222: 
1.233     raeburn  9223: =pod
                   9224: 
1.821     raeburn  9225: =item * &show_course()
                   9226: 
                   9227: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9228: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9229: 
                   9230: Inputs:
                   9231: None
                   9232: 
                   9233: Outputs:
                   9234: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9235: 
                   9236: =cut
                   9237: 
                   9238: ###############################################
                   9239: sub show_course {
                   9240:     my $course = !$env{'user.adv'};
                   9241:     if (!$env{'user.adv'}) {
                   9242:         foreach my $env (keys(%env)) {
                   9243:             next if ($env !~ m/^user\.priv\./);
                   9244:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9245:                 $course = 0;
                   9246:                 last;
                   9247:             }
                   9248:         }
                   9249:     }
                   9250:     return $course;
                   9251: }
                   9252: 
                   9253: ###############################################
                   9254: 
                   9255: =pod
                   9256: 
1.542     raeburn  9257: =item * &check_user_status()
1.274     raeburn  9258: 
                   9259: Determines current status of supplied role for a
                   9260: specific user. Roles can be active, previous or future.
                   9261: 
                   9262: Inputs: 
                   9263: user's domain, user's username, course's domain,
1.375     raeburn  9264: course's number, optional section ID.
1.274     raeburn  9265: 
                   9266: Outputs:
                   9267: role status: active, previous or future. 
                   9268: 
                   9269: =cut
                   9270: 
                   9271: sub check_user_status {
1.412     raeburn  9272:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9273:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9274:     my @uroles = keys(%userinfo);
1.274     raeburn  9275:     my $srchstr;
                   9276:     my $active_chk = 'none';
1.412     raeburn  9277:     my $now = time;
1.274     raeburn  9278:     if (@uroles > 0) {
1.908     raeburn  9279:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9280:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9281:         } else {
1.412     raeburn  9282:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9283:         }
                   9284:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9285:             my $role_end = 0;
                   9286:             my $role_start = 0;
                   9287:             $active_chk = 'active';
1.412     raeburn  9288:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9289:                 $role_end = $1;
                   9290:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9291:                     $role_start = $1;
1.274     raeburn  9292:                 }
                   9293:             }
                   9294:             if ($role_start > 0) {
1.412     raeburn  9295:                 if ($now < $role_start) {
1.274     raeburn  9296:                     $active_chk = 'future';
                   9297:                 }
                   9298:             }
                   9299:             if ($role_end > 0) {
1.412     raeburn  9300:                 if ($now > $role_end) {
1.274     raeburn  9301:                     $active_chk = 'previous';
                   9302:                 }
                   9303:             }
                   9304:         }
                   9305:     }
                   9306:     return $active_chk;
                   9307: }
                   9308: 
                   9309: ###############################################
                   9310: 
                   9311: =pod
                   9312: 
1.405     albertel 9313: =item * &get_sections()
1.233     raeburn  9314: 
                   9315: Determines all the sections for a course including
                   9316: sections with students and sections containing other roles.
1.419     raeburn  9317: Incoming parameters: 
                   9318: 
                   9319: 1. domain
                   9320: 2. course number 
                   9321: 3. reference to array containing roles for which sections should 
                   9322: be gathered (optional).
                   9323: 4. reference to array containing status types for which sections 
                   9324: should be gathered (optional).
                   9325: 
                   9326: If the third argument is undefined, sections are gathered for any role. 
                   9327: If the fourth argument is undefined, sections are gathered for any status.
                   9328: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9329:  
1.374     raeburn  9330: Returns section hash (keys are section IDs, values are
                   9331: number of users in each section), subject to the
1.419     raeburn  9332: optional roles filter, optional status filter 
1.233     raeburn  9333: 
                   9334: =cut
                   9335: 
                   9336: ###############################################
                   9337: sub get_sections {
1.419     raeburn  9338:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9339:     if (!defined($cdom) || !defined($cnum)) {
                   9340:         my $cid =  $env{'request.course.id'};
                   9341: 
                   9342: 	return if (!defined($cid));
                   9343: 
                   9344:         $cdom = $env{'course.'.$cid.'.domain'};
                   9345:         $cnum = $env{'course.'.$cid.'.num'};
                   9346:     }
                   9347: 
                   9348:     my %sectioncount;
1.419     raeburn  9349:     my $now = time;
1.240     albertel 9350: 
1.1118    raeburn  9351:     my $check_students = 1;
                   9352:     my $only_students = 0;
                   9353:     if (ref($possible_roles) eq 'ARRAY') {
                   9354:         if (grep(/^st$/,@{$possible_roles})) {
                   9355:             if (@{$possible_roles} == 1) {
                   9356:                 $only_students = 1;
                   9357:             }
                   9358:         } else {
                   9359:             $check_students = 0;
                   9360:         }
                   9361:     }
                   9362: 
                   9363:     if ($check_students) { 
1.276     albertel 9364: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9365: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9366: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9367:         my $start_index = &Apache::loncoursedata::CL_START();
                   9368:         my $end_index = &Apache::loncoursedata::CL_END();
                   9369:         my $status;
1.366     albertel 9370: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9371: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9372: 				                     $data->[$status_index],
                   9373:                                                      $data->[$start_index],
                   9374:                                                      $data->[$end_index]);
                   9375:             if ($stu_status eq 'Active') {
                   9376:                 $status = 'active';
                   9377:             } elsif ($end < $now) {
                   9378:                 $status = 'previous';
                   9379:             } elsif ($start > $now) {
                   9380:                 $status = 'future';
                   9381:             } 
                   9382: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9383:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9384:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9385: 		    $sectioncount{$section}++;
                   9386:                 }
1.240     albertel 9387: 	    }
                   9388: 	}
                   9389:     }
1.1118    raeburn  9390:     if ($only_students) {
                   9391:         return %sectioncount;
                   9392:     }
1.240     albertel 9393:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9394:     foreach my $user (sort(keys(%courseroles))) {
                   9395: 	if ($user !~ /^(\w{2})/) { next; }
                   9396: 	my ($role) = ($user =~ /^(\w{2})/);
                   9397: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9398: 	my ($section,$status);
1.240     albertel 9399: 	if ($role eq 'cr' &&
                   9400: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9401: 	    $section=$1;
                   9402: 	}
                   9403: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9404: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9405:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9406:         if ($end == -1 && $start == -1) {
                   9407:             next; #deleted role
                   9408:         }
                   9409:         if (!defined($possible_status)) { 
                   9410:             $sectioncount{$section}++;
                   9411:         } else {
                   9412:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9413:                 $status = 'active';
                   9414:             } elsif ($end < $now) {
                   9415:                 $status = 'future';
                   9416:             } elsif ($start > $now) {
                   9417:                 $status = 'previous';
                   9418:             }
                   9419:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9420:                 $sectioncount{$section}++;
                   9421:             }
                   9422:         }
1.233     raeburn  9423:     }
1.366     albertel 9424:     return %sectioncount;
1.233     raeburn  9425: }
                   9426: 
1.274     raeburn  9427: ###############################################
1.294     raeburn  9428: 
                   9429: =pod
1.405     albertel 9430: 
                   9431: =item * &get_course_users()
                   9432: 
1.275     raeburn  9433: Retrieves usernames:domains for users in the specified course
                   9434: with specific role(s), and access status. 
                   9435: 
                   9436: Incoming parameters:
1.277     albertel 9437: 1. course domain
                   9438: 2. course number
                   9439: 3. access status: users must have - either active, 
1.275     raeburn  9440: previous, future, or all.
1.277     albertel 9441: 4. reference to array of permissible roles
1.288     raeburn  9442: 5. reference to array of section restrictions (optional)
                   9443: 6. reference to results object (hash of hashes).
                   9444: 7. reference to optional userdata hash
1.609     raeburn  9445: 8. reference to optional statushash
1.630     raeburn  9446: 9. flag if privileged users (except those set to unhide in
                   9447:    course settings) should be excluded    
1.609     raeburn  9448: Keys of top level results hash are roles.
1.275     raeburn  9449: Keys of inner hashes are username:domain, with 
                   9450: values set to access type.
1.288     raeburn  9451: Optional userdata hash returns an array with arguments in the 
                   9452: same order as loncoursedata::get_classlist() for student data.
                   9453: 
1.609     raeburn  9454: Optional statushash returns
                   9455: 
1.288     raeburn  9456: Entries for end, start, section and status are blank because
                   9457: of the possibility of multiple values for non-student roles.
                   9458: 
1.275     raeburn  9459: =cut
1.405     albertel 9460: 
1.275     raeburn  9461: ###############################################
1.405     albertel 9462: 
1.275     raeburn  9463: sub get_course_users {
1.630     raeburn  9464:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9465:     my %idx = ();
1.419     raeburn  9466:     my %seclists;
1.288     raeburn  9467: 
                   9468:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9469:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9470:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9471:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9472:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9473:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9474:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9475:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9476: 
1.290     albertel 9477:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9478:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9479:         my $now = time;
1.277     albertel 9480:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9481:             my $match = 0;
1.412     raeburn  9482:             my $secmatch = 0;
1.419     raeburn  9483:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9484:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9485:             if ($section eq '') {
                   9486:                 $section = 'none';
                   9487:             }
1.291     albertel 9488:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9489:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9490:                     $secmatch = 1;
                   9491:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9492:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9493:                         $secmatch = 1;
                   9494:                     }
                   9495:                 } else {  
1.419     raeburn  9496: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9497: 		        $secmatch = 1;
                   9498:                     }
1.290     albertel 9499: 		}
1.412     raeburn  9500:                 if (!$secmatch) {
                   9501:                     next;
                   9502:                 }
1.419     raeburn  9503:             }
1.275     raeburn  9504:             if (defined($$types{'active'})) {
1.288     raeburn  9505:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9506:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9507:                     $match = 1;
1.275     raeburn  9508:                 }
                   9509:             }
                   9510:             if (defined($$types{'previous'})) {
1.609     raeburn  9511:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9512:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9513:                     $match = 1;
1.275     raeburn  9514:                 }
                   9515:             }
                   9516:             if (defined($$types{'future'})) {
1.609     raeburn  9517:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9518:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9519:                     $match = 1;
1.275     raeburn  9520:                 }
                   9521:             }
1.609     raeburn  9522:             if ($match) {
                   9523:                 push(@{$seclists{$student}},$section);
                   9524:                 if (ref($userdata) eq 'HASH') {
                   9525:                     $$userdata{$student} = $$classlist{$student};
                   9526:                 }
                   9527:                 if (ref($statushash) eq 'HASH') {
                   9528:                     $statushash->{$student}{'st'}{$section} = $status;
                   9529:                 }
1.288     raeburn  9530:             }
1.275     raeburn  9531:         }
                   9532:     }
1.412     raeburn  9533:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9534:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9535:         my $now = time;
1.609     raeburn  9536:         my %displaystatus = ( previous => 'Expired',
                   9537:                               active   => 'Active',
                   9538:                               future   => 'Future',
                   9539:                             );
1.1121    raeburn  9540:         my (%nothide,@possdoms);
1.630     raeburn  9541:         if ($hidepriv) {
                   9542:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9543:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9544:                 if ($user !~ /:/) {
                   9545:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9546:                 } else {
                   9547:                     $nothide{$user} = 1;
                   9548:                 }
                   9549:             }
1.1121    raeburn  9550:             my @possdoms = ($cdom);
                   9551:             if ($coursehash{'checkforpriv'}) {
                   9552:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9553:             }
1.630     raeburn  9554:         }
1.439     raeburn  9555:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9556:             my $match = 0;
1.412     raeburn  9557:             my $secmatch = 0;
1.439     raeburn  9558:             my $status;
1.412     raeburn  9559:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9560:             $user =~ s/:$//;
1.439     raeburn  9561:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9562:             if ($end == -1 || $start == -1) {
                   9563:                 next;
                   9564:             }
                   9565:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9566:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9567:                 my ($uname,$udom) = split(/:/,$user);
                   9568:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9569:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9570:                         $secmatch = 1;
                   9571:                     } elsif ($usec eq '') {
1.420     albertel 9572:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9573:                             $secmatch = 1;
                   9574:                         }
                   9575:                     } else {
                   9576:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9577:                             $secmatch = 1;
                   9578:                         }
                   9579:                     }
                   9580:                     if (!$secmatch) {
                   9581:                         next;
                   9582:                     }
1.288     raeburn  9583:                 }
1.419     raeburn  9584:                 if ($usec eq '') {
                   9585:                     $usec = 'none';
                   9586:                 }
1.275     raeburn  9587:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9588:                     if ($hidepriv) {
1.1121    raeburn  9589:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9590:                             (!$nothide{$uname.':'.$udom})) {
                   9591:                             next;
                   9592:                         }
                   9593:                     }
1.503     raeburn  9594:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9595:                         $status = 'previous';
                   9596:                     } elsif ($start > $now) {
                   9597:                         $status = 'future';
                   9598:                     } else {
                   9599:                         $status = 'active';
                   9600:                     }
1.277     albertel 9601:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9602:                         if ($status eq $type) {
1.420     albertel 9603:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9604:                                 push(@{$$users{$role}{$user}},$type);
                   9605:                             }
1.288     raeburn  9606:                             $match = 1;
                   9607:                         }
                   9608:                     }
1.419     raeburn  9609:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9610:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9611: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9612:                         }
1.420     albertel 9613:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9614:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9615:                         }
1.609     raeburn  9616:                         if (ref($statushash) eq 'HASH') {
                   9617:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9618:                         }
1.275     raeburn  9619:                     }
                   9620:                 }
                   9621:             }
                   9622:         }
1.290     albertel 9623:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9624:             if ((defined($cdom)) && (defined($cnum))) {
                   9625:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9626:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9627:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9628:                     next if ($owner eq '');
                   9629:                     my ($ownername,$ownerdom);
                   9630:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9631:                         $ownername = $1;
                   9632:                         $ownerdom = $2;
                   9633:                     } else {
                   9634:                         $ownername = $owner;
                   9635:                         $ownerdom = $cdom;
                   9636:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9637:                     }
                   9638:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9639:                     if (defined($userdata) && 
1.609     raeburn  9640: 			!exists($$userdata{$owner})) {
                   9641: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9642:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9643:                             push(@{$seclists{$owner}},'none');
                   9644:                         }
                   9645:                         if (ref($statushash) eq 'HASH') {
                   9646:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9647:                         }
1.290     albertel 9648: 		    }
1.279     raeburn  9649:                 }
                   9650:             }
                   9651:         }
1.419     raeburn  9652:         foreach my $user (keys(%seclists)) {
                   9653:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9654:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9655:         }
1.275     raeburn  9656:     }
                   9657:     return;
                   9658: }
                   9659: 
1.288     raeburn  9660: sub get_user_info {
                   9661:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9662:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9663: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9664:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9665:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9666:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9667:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9668:     return;
                   9669: }
1.275     raeburn  9670: 
1.472     raeburn  9671: ###############################################
                   9672: 
                   9673: =pod
                   9674: 
                   9675: =item * &get_user_quota()
                   9676: 
1.1134    raeburn  9677: Retrieves quota assigned for storage of user files.
                   9678: Default is to report quota for portfolio files.
1.472     raeburn  9679: 
                   9680: Incoming parameters:
                   9681: 1. user's username
                   9682: 2. user's domain
1.1134    raeburn  9683: 3. quota name - portfolio, author, or course
1.1136    raeburn  9684:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  9685: 4. crstype - official, unofficial, textbook, placement or community, 
                   9686:    if quota name is course
1.472     raeburn  9687: 
                   9688: Returns:
1.1163    raeburn  9689: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9690: 2. (Optional) Type of setting: custom or default
                   9691:    (individually assigned or default for user's 
                   9692:    institutional status).
                   9693: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9694:    or student - types as defined in localenroll::inst_usertypes 
                   9695:    for user's domain, which determines default quota for user.
                   9696: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9697: 
                   9698: If a value has been stored in the user's environment, 
1.536     raeburn  9699: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9700: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9701: 
                   9702: =cut
                   9703: 
                   9704: ###############################################
                   9705: 
                   9706: 
                   9707: sub get_user_quota {
1.1136    raeburn  9708:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9709:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9710:     if (!defined($udom)) {
                   9711:         $udom = $env{'user.domain'};
                   9712:     }
                   9713:     if (!defined($uname)) {
                   9714:         $uname = $env{'user.name'};
                   9715:     }
                   9716:     if (($udom eq '' || $uname eq '') ||
                   9717:         ($udom eq 'public') && ($uname eq 'public')) {
                   9718:         $quota = 0;
1.536     raeburn  9719:         $quotatype = 'default';
                   9720:         $defquota = 0; 
1.472     raeburn  9721:     } else {
1.536     raeburn  9722:         my $inststatus;
1.1134    raeburn  9723:         if ($quotaname eq 'course') {
                   9724:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9725:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9726:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9727:             } else {
                   9728:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9729:                 $quota = $cenv{'internal.uploadquota'};
                   9730:             }
1.536     raeburn  9731:         } else {
1.1134    raeburn  9732:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9733:                 if ($quotaname eq 'author') {
                   9734:                     $quota = $env{'environment.authorquota'};
                   9735:                 } else {
                   9736:                     $quota = $env{'environment.portfolioquota'};
                   9737:                 }
                   9738:                 $inststatus = $env{'environment.inststatus'};
                   9739:             } else {
                   9740:                 my %userenv = 
                   9741:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9742:                                          'authorquota','inststatus'],$udom,$uname);
                   9743:                 my ($tmp) = keys(%userenv);
                   9744:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9745:                     if ($quotaname eq 'author') {
                   9746:                         $quota = $userenv{'authorquota'};
                   9747:                     } else {
                   9748:                         $quota = $userenv{'portfolioquota'};
                   9749:                     }
                   9750:                     $inststatus = $userenv{'inststatus'};
                   9751:                 } else {
                   9752:                     undef(%userenv);
                   9753:                 }
                   9754:             }
                   9755:         }
                   9756:         if ($quota eq '' || wantarray) {
                   9757:             if ($quotaname eq 'course') {
                   9758:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9759:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  9760:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   9761:                     ($crstype eq 'placement')) { 
1.1136    raeburn  9762:                     $defquota = $domdefs{$crstype.'quota'};
                   9763:                 }
                   9764:                 if ($defquota eq '') {
                   9765:                     $defquota = 500;
                   9766:                 }
1.1134    raeburn  9767:             } else {
                   9768:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9769:             }
                   9770:             if ($quota eq '') {
                   9771:                 $quota = $defquota;
                   9772:                 $quotatype = 'default';
                   9773:             } else {
                   9774:                 $quotatype = 'custom';
                   9775:             }
1.472     raeburn  9776:         }
                   9777:     }
1.536     raeburn  9778:     if (wantarray) {
                   9779:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9780:     } else {
                   9781:         return $quota;
                   9782:     }
1.472     raeburn  9783: }
                   9784: 
                   9785: ###############################################
                   9786: 
                   9787: =pod
                   9788: 
                   9789: =item * &default_quota()
                   9790: 
1.536     raeburn  9791: Retrieves default quota assigned for storage of user portfolio files,
                   9792: given an (optional) user's institutional status.
1.472     raeburn  9793: 
                   9794: Incoming parameters:
1.1142    raeburn  9795: 
1.472     raeburn  9796: 1. domain
1.536     raeburn  9797: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9798:    status types (e.g., faculty, staff, student etc.)
                   9799:    which apply to the user for whom the default is being retrieved.
                   9800:    If the institutional status string in undefined, the domain
1.1134    raeburn  9801:    default quota will be returned.
                   9802: 3.  quota name - portfolio, author, or course
                   9803:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9804: 
                   9805: Returns:
1.1142    raeburn  9806: 
1.1163    raeburn  9807: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9808: 2. (Optional) institutional type which determined the value of the
                   9809:    default quota.
1.472     raeburn  9810: 
                   9811: If a value has been stored in the domain's configuration db,
                   9812: it will return that, otherwise it returns 20 (for backwards 
                   9813: compatibility with domains which have not set up a configuration
1.1163    raeburn  9814: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9815: 
1.536     raeburn  9816: If the user's status includes multiple types (e.g., staff and student),
                   9817: the largest default quota which applies to the user determines the
                   9818: default quota returned.
                   9819: 
1.472     raeburn  9820: =cut
                   9821: 
                   9822: ###############################################
                   9823: 
                   9824: 
                   9825: sub default_quota {
1.1134    raeburn  9826:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9827:     my ($defquota,$settingstatus);
                   9828:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9829:                                             ['quotas'],$udom);
1.1134    raeburn  9830:     my $key = 'defaultquota';
                   9831:     if ($quotaname eq 'author') {
                   9832:         $key = 'authorquota';
                   9833:     }
1.622     raeburn  9834:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9835:         if ($inststatus ne '') {
1.765     raeburn  9836:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9837:             foreach my $item (@statuses) {
1.1134    raeburn  9838:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9839:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9840:                         if ($defquota eq '') {
1.1134    raeburn  9841:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9842:                             $settingstatus = $item;
1.1134    raeburn  9843:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9844:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9845:                             $settingstatus = $item;
                   9846:                         }
                   9847:                     }
1.1134    raeburn  9848:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9849:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9850:                         if ($defquota eq '') {
                   9851:                             $defquota = $quotahash{'quotas'}{$item};
                   9852:                             $settingstatus = $item;
                   9853:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9854:                             $defquota = $quotahash{'quotas'}{$item};
                   9855:                             $settingstatus = $item;
                   9856:                         }
1.536     raeburn  9857:                     }
                   9858:                 }
                   9859:             }
                   9860:         }
                   9861:         if ($defquota eq '') {
1.1134    raeburn  9862:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9863:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9864:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9865:                 $defquota = $quotahash{'quotas'}{'default'};
                   9866:             }
1.536     raeburn  9867:             $settingstatus = 'default';
1.1139    raeburn  9868:             if ($defquota eq '') {
                   9869:                 if ($quotaname eq 'author') {
                   9870:                     $defquota = 500;
                   9871:                 }
                   9872:             }
1.536     raeburn  9873:         }
                   9874:     } else {
                   9875:         $settingstatus = 'default';
1.1134    raeburn  9876:         if ($quotaname eq 'author') {
                   9877:             $defquota = 500;
                   9878:         } else {
                   9879:             $defquota = 20;
                   9880:         }
1.536     raeburn  9881:     }
                   9882:     if (wantarray) {
                   9883:         return ($defquota,$settingstatus);
1.472     raeburn  9884:     } else {
1.536     raeburn  9885:         return $defquota;
1.472     raeburn  9886:     }
                   9887: }
                   9888: 
1.1135    raeburn  9889: ###############################################
                   9890: 
                   9891: =pod
                   9892: 
1.1136    raeburn  9893: =item * &excess_filesize_warning()
1.1135    raeburn  9894: 
                   9895: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  9896: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  9897: space to be exceeded.
1.1136    raeburn  9898: 
                   9899: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  9900: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  9901: 
1.1165    raeburn  9902: Inputs: 7 
1.1136    raeburn  9903: 1. username or coursenum
1.1135    raeburn  9904: 2. domain
1.1136    raeburn  9905: 3. context ('author' or 'course')
1.1135    raeburn  9906: 4. filename of file for which action is being requested
                   9907: 5. filesize (kB) of file
                   9908: 6. action being taken: copy or upload.
1.1237    raeburn  9909: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  9910: 
                   9911: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  9912:          otherwise return null.
                   9913: 
                   9914: =back
1.1135    raeburn  9915: 
                   9916: =cut
                   9917: 
1.1136    raeburn  9918: sub excess_filesize_warning {
1.1165    raeburn  9919:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  9920:     my $current_disk_usage = 0;
1.1165    raeburn  9921:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  9922:     if ($context eq 'author') {
                   9923:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9924:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9925:     } else {
                   9926:         foreach my $subdir ('docs','supplemental') {
                   9927:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9928:         }
                   9929:     }
1.1135    raeburn  9930:     $disk_quota = int($disk_quota * 1000);
                   9931:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   9932:         return '<p class="LC_warning">'.
1.1135    raeburn  9933:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   9934:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9935:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  9936:                             $disk_quota,$current_disk_usage).
                   9937:                '</p>';
                   9938:     }
                   9939:     return;
                   9940: }
                   9941: 
                   9942: ###############################################
                   9943: 
                   9944: 
1.1136    raeburn  9945: 
                   9946: 
1.384     raeburn  9947: sub get_secgrprole_info {
                   9948:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9949:     my %sections_count = &get_sections($cdom,$cnum);
                   9950:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9951:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9952:     my @groups = sort(keys(%curr_groups));
                   9953:     my $allroles = [];
                   9954:     my $rolehash;
                   9955:     my $accesshash = {
                   9956:                      active => 'Currently has access',
                   9957:                      future => 'Will have future access',
                   9958:                      previous => 'Previously had access',
                   9959:                   };
                   9960:     if ($needroles) {
                   9961:         $rolehash = {'all' => 'all'};
1.385     albertel 9962:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9963: 	if (&Apache::lonnet::error(%user_roles)) {
                   9964: 	    undef(%user_roles);
                   9965: 	}
                   9966:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9967:             my ($role)=split(/\:/,$item,2);
                   9968:             if ($role eq 'cr') { next; }
                   9969:             if ($role =~ /^cr/) {
                   9970:                 $$rolehash{$role} = (split('/',$role))[3];
                   9971:             } else {
                   9972:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9973:             }
                   9974:         }
                   9975:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9976:             push(@{$allroles},$key);
                   9977:         }
                   9978:         push (@{$allroles},'st');
                   9979:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9980:     }
                   9981:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9982: }
                   9983: 
1.555     raeburn  9984: sub user_picker {
1.1255    raeburn  9985:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom) = @_;
1.555     raeburn  9986:     my $currdom = $dom;
1.1253    raeburn  9987:     my @alldoms = &Apache::lonnet::all_domains();
                   9988:     if (@alldoms == 1) {
                   9989:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   9990:                                                ['directorysrch'],$alldoms[0]);
                   9991:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   9992:         my $showdom = $domdesc;
                   9993:         if ($showdom eq '') {
                   9994:             $showdom = $dom;
                   9995:         }
                   9996:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   9997:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   9998:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   9999:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10000:             }
                   10001:         }
                   10002:     }
1.555     raeburn  10003:     my %curr_selected = (
                   10004:                         srchin => 'dom',
1.580     raeburn  10005:                         srchby => 'lastname',
1.555     raeburn  10006:                       );
                   10007:     my $srchterm;
1.625     raeburn  10008:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10009:         if ($srch->{'srchby'} ne '') {
                   10010:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10011:         }
                   10012:         if ($srch->{'srchin'} ne '') {
                   10013:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10014:         }
                   10015:         if ($srch->{'srchtype'} ne '') {
                   10016:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10017:         }
                   10018:         if ($srch->{'srchdomain'} ne '') {
                   10019:             $currdom = $srch->{'srchdomain'};
                   10020:         }
                   10021:         $srchterm = $srch->{'srchterm'};
                   10022:     }
1.1222    damieng  10023:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10024:                     'usr'       => 'Search criteria',
1.563     raeburn  10025:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10026:                     'uname'     => 'username',
                   10027:                     'lastname'  => 'last name',
1.555     raeburn  10028:                     'lastfirst' => 'last name, first name',
1.558     albertel 10029:                     'crs'       => 'in this course',
1.576     raeburn  10030:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10031:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10032:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10033:                     'exact'     => 'is',
                   10034:                     'contains'  => 'contains',
1.569     raeburn  10035:                     'begins'    => 'begins with',
1.1222    damieng  10036:                                        );
                   10037:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10038:                     'youm'      => "You must include some text to search for.",
                   10039:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10040:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10041:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10042:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10043:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10044:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10045:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10046:                                        );
1.1222    damieng  10047:     &html_escape(\%html_lt);
                   10048:     &js_escape(\%js_lt);
1.1255    raeburn  10049:     my $domform;
                   10050:     if ($fixeddom) {
                   10051:         $domform = &select_dom_form($currdom,'srchdomain',1,1,undef,[$currdom]);
                   10052:     } else {
                   10053:         $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   10054:     }
1.563     raeburn  10055:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10056: 
                   10057:     my @srchins = ('crs','dom','alc','instd');
                   10058: 
                   10059:     foreach my $option (@srchins) {
                   10060:         # FIXME 'alc' option unavailable until 
                   10061:         #       loncreateuser::print_user_query_page()
                   10062:         #       has been completed.
                   10063:         next if ($option eq 'alc');
1.880     raeburn  10064:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10065:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  10066:         if ($curr_selected{'srchin'} eq $option) {
                   10067:             $srchinsel .= ' 
1.1222    damieng  10068:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10069:         } else {
                   10070:             $srchinsel .= '
1.1222    damieng  10071:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10072:         }
1.555     raeburn  10073:     }
1.563     raeburn  10074:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10075: 
                   10076:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10077:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10078:         if ($curr_selected{'srchby'} eq $option) {
                   10079:             $srchbysel .= '
1.1222    damieng  10080:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10081:         } else {
                   10082:             $srchbysel .= '
1.1222    damieng  10083:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10084:          }
                   10085:     }
                   10086:     $srchbysel .= "\n  </select>\n";
                   10087: 
                   10088:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10089:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10090:         if ($curr_selected{'srchtype'} eq $option) {
                   10091:             $srchtypesel .= '
1.1222    damieng  10092:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10093:         } else {
                   10094:             $srchtypesel .= '
1.1222    damieng  10095:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10096:         }
                   10097:     }
                   10098:     $srchtypesel .= "\n  </select>\n";
                   10099: 
1.558     albertel 10100:     my ($newuserscript,$new_user_create);
1.994     raeburn  10101:     my $context_dom = $env{'request.role.domain'};
                   10102:     if ($context eq 'requestcrs') {
                   10103:         if ($env{'form.coursedom'} ne '') { 
                   10104:             $context_dom = $env{'form.coursedom'};
                   10105:         }
                   10106:     }
1.556     raeburn  10107:     if ($forcenewuser) {
1.576     raeburn  10108:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10109:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10110:                 if ($cancreate) {
                   10111:                     $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>';
                   10112:                 } else {
1.799     bisitz   10113:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10114:                     my %usertypetext = (
                   10115:                         official   => 'institutional',
                   10116:                         unofficial => 'non-institutional',
                   10117:                     );
1.799     bisitz   10118:                     $new_user_create = '<p class="LC_warning">'
                   10119:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10120:                                       .' '
                   10121:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10122:                                           ,'<a href="'.$helplink.'">','</a>')
                   10123:                                       .'</p><br />';
1.627     raeburn  10124:                 }
1.576     raeburn  10125:             }
                   10126:         }
                   10127: 
1.556     raeburn  10128:         $newuserscript = <<"ENDSCRIPT";
                   10129: 
1.570     raeburn  10130: function setSearch(createnew,callingForm) {
1.556     raeburn  10131:     if (createnew == 1) {
1.570     raeburn  10132:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10133:             if (callingForm.srchby.options[i].value == 'uname') {
                   10134:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10135:             }
                   10136:         }
1.570     raeburn  10137:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10138:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10139: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10140:             }
                   10141:         }
1.570     raeburn  10142:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10143:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10144:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10145:             }
                   10146:         }
1.570     raeburn  10147:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10148:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10149:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10150:             }
                   10151:         }
                   10152:     }
                   10153: }
                   10154: ENDSCRIPT
1.558     albertel 10155: 
1.556     raeburn  10156:     }
                   10157: 
1.555     raeburn  10158:     my $output = <<"END_BLOCK";
1.556     raeburn  10159: <script type="text/javascript">
1.824     bisitz   10160: // <![CDATA[
1.570     raeburn  10161: function validateEntry(callingForm) {
1.558     albertel 10162: 
1.556     raeburn  10163:     var checkok = 1;
1.558     albertel 10164:     var srchin;
1.570     raeburn  10165:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10166: 	if ( callingForm.srchin[i].checked ) {
                   10167: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10168: 	}
                   10169:     }
                   10170: 
1.570     raeburn  10171:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10172:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10173:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10174:     var srchterm =  callingForm.srchterm.value;
                   10175:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10176:     var msg = "";
                   10177: 
                   10178:     if (srchterm == "") {
                   10179:         checkok = 0;
1.1222    damieng  10180:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10181:     }
                   10182: 
1.569     raeburn  10183:     if (srchtype== 'begins') {
                   10184:         if (srchterm.length < 2) {
                   10185:             checkok = 0;
1.1222    damieng  10186:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10187:         }
                   10188:     }
                   10189: 
1.556     raeburn  10190:     if (srchtype== 'contains') {
                   10191:         if (srchterm.length < 3) {
                   10192:             checkok = 0;
1.1222    damieng  10193:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10194:         }
                   10195:     }
                   10196:     if (srchin == 'instd') {
                   10197:         if (srchdomain == '') {
                   10198:             checkok = 0;
1.1222    damieng  10199:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10200:         }
                   10201:     }
                   10202:     if (srchin == 'dom') {
                   10203:         if (srchdomain == '') {
                   10204:             checkok = 0;
1.1222    damieng  10205:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10206:         }
                   10207:     }
                   10208:     if (srchby == 'lastfirst') {
                   10209:         if (srchterm.indexOf(",") == -1) {
                   10210:             checkok = 0;
1.1222    damieng  10211:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10212:         }
                   10213:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10214:             checkok = 0;
1.1222    damieng  10215:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10216:         }
                   10217:     }
                   10218:     if (checkok == 0) {
1.1222    damieng  10219:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10220:         return;
                   10221:     }
                   10222:     if (checkok == 1) {
1.570     raeburn  10223:         callingForm.submit();
1.556     raeburn  10224:     }
                   10225: }
                   10226: 
                   10227: $newuserscript
                   10228: 
1.824     bisitz   10229: // ]]>
1.556     raeburn  10230: </script>
1.558     albertel 10231: 
                   10232: $new_user_create
                   10233: 
1.555     raeburn  10234: END_BLOCK
1.558     albertel 10235: 
1.876     raeburn  10236:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10237:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10238:                $domform.
                   10239:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10240:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10241:                $srchbysel.
                   10242:                $srchtypesel. 
                   10243:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10244:                $srchinsel.
                   10245:                &Apache::lonhtmlcommon::row_closure(1). 
                   10246:                &Apache::lonhtmlcommon::end_pick_box().
                   10247:                '<br />';
1.1253    raeburn  10248:     return ($output,1);
1.555     raeburn  10249: }
                   10250: 
1.612     raeburn  10251: sub user_rule_check {
1.615     raeburn  10252:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10253:     my ($response,%inst_response);
1.612     raeburn  10254:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10255:         if (keys(%{$usershash}) > 1) {
                   10256:             my (%by_username,%by_id,%userdoms);
                   10257:             my $checkid; 
                   10258:             if (ref($checks) eq 'HASH') {
                   10259:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10260:                     $checkid = 1;
                   10261:                 }
                   10262:             }
                   10263:             foreach my $user (keys(%{$usershash})) {
                   10264:                 my ($uname,$udom) = split(/:/,$user);
                   10265:                 if ($checkid) {
                   10266:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10267:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10268:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10269:                             $userdoms{$udom} = 1;
1.1227    raeburn  10270:                             if (ref($inst_results) eq 'HASH') {
                   10271:                                 $inst_results->{$uname.':'.$udom} = {};
                   10272:                             }
1.1226    raeburn  10273:                         }
                   10274:                     }
                   10275:                 } else {
                   10276:                     $by_username{$udom}{$uname} = 1;
                   10277:                     $userdoms{$udom} = 1;
1.1227    raeburn  10278:                     if (ref($inst_results) eq 'HASH') {
                   10279:                         $inst_results->{$uname.':'.$udom} = {};
                   10280:                     }
1.1226    raeburn  10281:                 }
                   10282:             }
                   10283:             foreach my $udom (keys(%userdoms)) {
                   10284:                 if (!$got_rules->{$udom}) {
                   10285:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10286:                                                              ['usercreation'],$udom);
                   10287:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10288:                         foreach my $item ('username','id') {
                   10289:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10290:                                 $$curr_rules{$udom}{$item} =
                   10291:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10292:                             }
                   10293:                         }
                   10294:                     }
                   10295:                     $got_rules->{$udom} = 1;
                   10296:                 }
1.612     raeburn  10297:             }
1.1226    raeburn  10298:             if ($checkid) {
                   10299:                 foreach my $udom (keys(%by_id)) {
                   10300:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10301:                     if ($outcome eq 'ok') {
1.1227    raeburn  10302:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10303:                             my $uname = $by_id{$udom}{$id};
                   10304:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10305:                         }
1.1226    raeburn  10306:                         if (ref($results) eq 'HASH') {
                   10307:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  10308:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10309:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10310:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10311:                                 }
1.1226    raeburn  10312:                             }
                   10313:                         }
                   10314:                     }
1.612     raeburn  10315:                 }
1.615     raeburn  10316:             } else {
1.1226    raeburn  10317:                 foreach my $udom (keys(%by_username)) {
                   10318:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10319:                     if ($outcome eq 'ok') {
1.1227    raeburn  10320:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10321:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10322:                         }
1.1226    raeburn  10323:                         if (ref($results) eq 'HASH') {
                   10324:                             foreach my $uname (keys(%{$results})) {
                   10325:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10326:                             }
                   10327:                         }
                   10328:                     }
                   10329:                 }
1.612     raeburn  10330:             }
1.1226    raeburn  10331:         } elsif (keys(%{$usershash}) == 1) {
                   10332:             my $user = (keys(%{$usershash}))[0];
                   10333:             my ($uname,$udom) = split(/:/,$user);
                   10334:             if (($udom ne '') && ($uname ne '')) {
                   10335:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10336:                     if (ref($checks) eq 'HASH') {
                   10337:                         if (defined($checks->{'username'})) {
                   10338:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   10339:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10340:                         } elsif (defined($checks->{'id'})) {
                   10341:                             if ($usershash->{$user}->{'id'} ne '') {
                   10342:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10343:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10344:                                                                   $usershash->{$user}->{'id'});
                   10345:                             } else {
                   10346:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10347:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10348:                             }
1.585     raeburn  10349:                         }
1.1226    raeburn  10350:                     } else {
                   10351:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10352:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10353:                        return;
                   10354:                     }
                   10355:                     if (!$got_rules->{$udom}) {
                   10356:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10357:                                                                  ['usercreation'],$udom);
                   10358:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10359:                             foreach my $item ('username','id') {
                   10360:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10361:                                    $$curr_rules{$udom}{$item} = 
                   10362:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10363:                                 }
                   10364:                             }
                   10365:                         }
                   10366:                         $got_rules->{$udom} = 1;
1.585     raeburn  10367:                     }
                   10368:                 }
1.1226    raeburn  10369:             } else {
                   10370:                 return;
                   10371:             }
                   10372:         } else {
                   10373:             return;
                   10374:         }
                   10375:         foreach my $user (keys(%{$usershash})) {
                   10376:             my ($uname,$udom) = split(/:/,$user);
                   10377:             next if (($udom eq '') || ($uname eq ''));
                   10378:             my $id;
1.1227    raeburn  10379:             if (ref($inst_results) eq 'HASH') {
                   10380:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10381:                     $id = $inst_results->{$user}->{'id'};
                   10382:                 }
                   10383:             }
                   10384:             if ($id eq '') { 
                   10385:                 if (ref($usershash->{$user})) {
                   10386:                     $id = $usershash->{$user}->{'id'};
                   10387:                 }
1.585     raeburn  10388:             }
1.612     raeburn  10389:             foreach my $item (keys(%{$checks})) {
                   10390:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10391:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10392:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10393:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10394:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10395:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10396:                                 if ($rule_check{$rule}) {
                   10397:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10398:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10399:                                         if (ref($inst_results) eq 'HASH') {
                   10400:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10401:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10402:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10403:                                                 } elsif ($item eq 'id') {
                   10404:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10405:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10406:                                                     }
1.615     raeburn  10407:                                                 }
1.612     raeburn  10408:                                             }
                   10409:                                         }
1.615     raeburn  10410:                                     }
                   10411:                                     last;
1.585     raeburn  10412:                                 }
                   10413:                             }
                   10414:                         }
                   10415:                     }
                   10416:                 }
                   10417:             }
                   10418:         }
                   10419:     }
1.612     raeburn  10420:     return;
                   10421: }
                   10422: 
                   10423: sub user_rule_formats {
                   10424:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10425:     my %text = ( 
                   10426:                  'username' => 'Usernames',
                   10427:                  'id'       => 'IDs',
                   10428:                );
                   10429:     my $output;
                   10430:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10431:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10432:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10433:             $output = '<br />'.
                   10434:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10435:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10436:                       ' <ul>';
1.612     raeburn  10437:             foreach my $rule (@{$ruleorder}) {
                   10438:                 if (ref($curr_rules) eq 'ARRAY') {
                   10439:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10440:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10441:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10442:                                         $rules->{$rule}{'desc'}.'</li>';
                   10443:                         }
                   10444:                     }
                   10445:                 }
                   10446:             }
                   10447:             $output .= '</ul>';
                   10448:         }
                   10449:     }
                   10450:     return $output;
                   10451: }
                   10452: 
                   10453: sub instrule_disallow_msg {
1.615     raeburn  10454:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10455:     my $response;
                   10456:     my %text = (
                   10457:                   item   => 'username',
                   10458:                   items  => 'usernames',
                   10459:                   match  => 'matches',
                   10460:                   do     => 'does',
                   10461:                   action => 'a username',
                   10462:                   one    => 'one',
                   10463:                );
                   10464:     if ($count > 1) {
                   10465:         $text{'item'} = 'usernames';
                   10466:         $text{'match'} ='match';
                   10467:         $text{'do'} = 'do';
                   10468:         $text{'action'} = 'usernames',
                   10469:         $text{'one'} = 'ones';
                   10470:     }
                   10471:     if ($checkitem eq 'id') {
                   10472:         $text{'items'} = 'IDs';
                   10473:         $text{'item'} = 'ID';
                   10474:         $text{'action'} = 'an ID';
1.615     raeburn  10475:         if ($count > 1) {
                   10476:             $text{'item'} = 'IDs';
                   10477:             $text{'action'} = 'IDs';
                   10478:         }
1.612     raeburn  10479:     }
1.674     bisitz   10480:     $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  10481:     if ($mode eq 'upload') {
                   10482:         if ($checkitem eq 'username') {
                   10483:             $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'}.");
                   10484:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10485:             $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  10486:         }
1.669     raeburn  10487:     } elsif ($mode eq 'selfcreate') {
                   10488:         if ($checkitem eq 'id') {
                   10489:             $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.");
                   10490:         }
1.615     raeburn  10491:     } else {
                   10492:         if ($checkitem eq 'username') {
                   10493:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10494:         } elsif ($checkitem eq 'id') {
                   10495:             $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.");
                   10496:         }
1.612     raeburn  10497:     }
                   10498:     return $response;
1.585     raeburn  10499: }
                   10500: 
1.624     raeburn  10501: sub personal_data_fieldtitles {
                   10502:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10503:                         id => 'Student/Employee ID',
                   10504:                         permanentemail => 'E-mail address',
                   10505:                         lastname => 'Last Name',
                   10506:                         firstname => 'First Name',
                   10507:                         middlename => 'Middle Name',
                   10508:                         generation => 'Generation',
                   10509:                         gen => 'Generation',
1.765     raeburn  10510:                         inststatus => 'Affiliation',
1.624     raeburn  10511:                    );
                   10512:     return %fieldtitles;
                   10513: }
                   10514: 
1.642     raeburn  10515: sub sorted_inst_types {
                   10516:     my ($dom) = @_;
1.1185    raeburn  10517:     my ($usertypes,$order);
                   10518:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10519:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10520:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10521:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10522:     } else {
                   10523:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10524:     }
1.642     raeburn  10525:     my $othertitle = &mt('All users');
                   10526:     if ($env{'request.course.id'}) {
1.668     raeburn  10527:         $othertitle  = &mt('Any users');
1.642     raeburn  10528:     }
                   10529:     my @types;
                   10530:     if (ref($order) eq 'ARRAY') {
                   10531:         @types = @{$order};
                   10532:     }
                   10533:     if (@types == 0) {
                   10534:         if (ref($usertypes) eq 'HASH') {
                   10535:             @types = sort(keys(%{$usertypes}));
                   10536:         }
                   10537:     }
                   10538:     if (keys(%{$usertypes}) > 0) {
                   10539:         $othertitle = &mt('Other users');
                   10540:     }
                   10541:     return ($othertitle,$usertypes,\@types);
                   10542: }
                   10543: 
1.645     raeburn  10544: sub get_institutional_codes {
                   10545:     my ($settings,$allcourses,$LC_code) = @_;
                   10546: # Get complete list of course sections to update
                   10547:     my @currsections = ();
                   10548:     my @currxlists = ();
                   10549:     my $coursecode = $$settings{'internal.coursecode'};
                   10550: 
                   10551:     if ($$settings{'internal.sectionnums'} ne '') {
                   10552:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10553:     }
                   10554: 
                   10555:     if ($$settings{'internal.crosslistings'} ne '') {
                   10556:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10557:     }
                   10558: 
                   10559:     if (@currxlists > 0) {
                   10560:         foreach (@currxlists) {
                   10561:             if (m/^([^:]+):(\w*)$/) {
                   10562:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  10563:                     push(@{$allcourses},$1);
1.645     raeburn  10564:                     $$LC_code{$1} = $2;
                   10565:                 }
                   10566:             }
                   10567:         }
                   10568:     }
                   10569:  
                   10570:     if (@currsections > 0) {
                   10571:         foreach (@currsections) {
                   10572:             if (m/^(\w+):(\w*)$/) {
                   10573:                 my $sec = $coursecode.$1;
                   10574:                 my $lc_sec = $2;
                   10575:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1263    raeburn  10576:                     push(@{$allcourses},$sec);
1.645     raeburn  10577:                     $$LC_code{$sec} = $lc_sec;
                   10578:                 }
                   10579:             }
                   10580:         }
                   10581:     }
                   10582:     return;
                   10583: }
                   10584: 
1.971     raeburn  10585: sub get_standard_codeitems {
                   10586:     return ('Year','Semester','Department','Number','Section');
                   10587: }
                   10588: 
1.112     bowersj2 10589: =pod
                   10590: 
1.780     raeburn  10591: =head1 Slot Helpers
                   10592: 
                   10593: =over 4
                   10594: 
                   10595: =item * sorted_slots()
                   10596: 
1.1040    raeburn  10597: Sorts an array of slot names in order of an optional sort key,
                   10598: default sort is by slot start time (earliest first). 
1.780     raeburn  10599: 
                   10600: Inputs:
                   10601: 
                   10602: =over 4
                   10603: 
                   10604: slotsarr  - Reference to array of unsorted slot names.
                   10605: 
                   10606: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10607: 
1.1040    raeburn  10608: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10609: 
1.549     albertel 10610: =back
                   10611: 
1.780     raeburn  10612: Returns:
                   10613: 
                   10614: =over 4
                   10615: 
1.1040    raeburn  10616: sorted   - An array of slot names sorted by a specified sort key 
                   10617:            (default sort key is start time of the slot).
1.780     raeburn  10618: 
                   10619: =back
                   10620: 
                   10621: =cut
                   10622: 
                   10623: 
                   10624: sub sorted_slots {
1.1040    raeburn  10625:     my ($slotsarr,$slots,$sortkey) = @_;
                   10626:     if ($sortkey eq '') {
                   10627:         $sortkey = 'starttime';
                   10628:     }
1.780     raeburn  10629:     my @sorted;
                   10630:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10631:         @sorted =
                   10632:             sort {
                   10633:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10634:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10635:                      }
                   10636:                      if (ref($slots->{$a})) { return -1;}
                   10637:                      if (ref($slots->{$b})) { return 1;}
                   10638:                      return 0;
                   10639:                  } @{$slotsarr};
                   10640:     }
                   10641:     return @sorted;
                   10642: }
                   10643: 
1.1040    raeburn  10644: =pod
                   10645: 
                   10646: =item * get_future_slots()
                   10647: 
                   10648: Inputs:
                   10649: 
                   10650: =over 4
                   10651: 
                   10652: cnum - course number
                   10653: 
                   10654: cdom - course domain
                   10655: 
                   10656: now - current UNIX time
                   10657: 
                   10658: symb - optional symb
                   10659: 
                   10660: =back
                   10661: 
                   10662: Returns:
                   10663: 
                   10664: =over 4
                   10665: 
                   10666: sorted_reservable - ref to array of student_schedulable slots currently 
                   10667:                     reservable, ordered by end date of reservation period.
                   10668: 
                   10669: reservable_now - ref to hash of student_schedulable slots currently
                   10670:                  reservable.
                   10671: 
                   10672:     Keys in inner hash are:
                   10673:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10674:     (b) endreserve: end date of reservation period.
                   10675:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10676:         selected.
1.1040    raeburn  10677: 
                   10678: sorted_future - ref to array of student_schedulable slots reservable in
                   10679:                 the future, ordered by start date of reservation period.
                   10680: 
                   10681: future_reservable - ref to hash of student_schedulable slots reservable
                   10682:                     in the future.
                   10683: 
                   10684:     Keys in inner hash are:
                   10685:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10686:     (b) startreserve: start date of reservation period.
                   10687:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10688:         selected.
1.1040    raeburn  10689: 
                   10690: =back
                   10691: 
                   10692: =cut
                   10693: 
                   10694: sub get_future_slots {
                   10695:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  10696:     my $map;
                   10697:     if ($symb) {
                   10698:         ($map) = &Apache::lonnet::decode_symb($symb);
                   10699:     }
1.1040    raeburn  10700:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10701:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10702:     foreach my $slot (keys(%slots)) {
                   10703:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10704:         if ($symb) {
1.1229    raeburn  10705:             if ($slots{$slot}->{'symb'} ne '') {
                   10706:                 my $canuse;
                   10707:                 my %oksymbs;
                   10708:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   10709:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   10710:                 if ($oksymbs{$symb}) {
                   10711:                     $canuse = 1;
                   10712:                 } else {
                   10713:                     foreach my $item (@slotsymbs) {
                   10714:                         if ($item =~ /\.(page|sequence)$/) {
                   10715:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   10716:                             if (($map ne '') && ($map eq $sloturl)) {
                   10717:                                 $canuse = 1;
                   10718:                                 last;
                   10719:                             }
                   10720:                         }
                   10721:                     }
                   10722:                 }
                   10723:                 next unless ($canuse);
                   10724:             }
1.1040    raeburn  10725:         }
                   10726:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10727:             ($slots{$slot}->{'endtime'} > $now)) {
                   10728:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10729:                 my $userallowed = 0;
                   10730:                 if ($slots{$slot}->{'allowedsections'}) {
                   10731:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10732:                     if (!defined($env{'request.role.sec'})
                   10733:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10734:                         $userallowed=1;
                   10735:                     } else {
                   10736:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10737:                             $userallowed=1;
                   10738:                         }
                   10739:                     }
                   10740:                     unless ($userallowed) {
                   10741:                         if (defined($env{'request.course.groups'})) {
                   10742:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10743:                             foreach my $group (@groups) {
                   10744:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10745:                                     $userallowed=1;
                   10746:                                     last;
                   10747:                                 }
                   10748:                             }
                   10749:                         }
                   10750:                     }
                   10751:                 }
                   10752:                 if ($slots{$slot}->{'allowedusers'}) {
                   10753:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10754:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10755:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10756:                         $userallowed = 1;
                   10757:                     }
                   10758:                 }
                   10759:                 next unless($userallowed);
                   10760:             }
                   10761:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10762:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10763:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  10764:             my $uniqueperiod;
                   10765:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10766:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10767:             }
1.1040    raeburn  10768:             if (($startreserve < $now) &&
                   10769:                 (!$endreserve || $endreserve > $now)) {
                   10770:                 my $lastres = $endreserve;
                   10771:                 if (!$lastres) {
                   10772:                     $lastres = $slots{$slot}->{'starttime'};
                   10773:                 }
                   10774:                 $reservable_now{$slot} = {
                   10775:                                            symb       => $symb,
1.1250    raeburn  10776:                                            endreserve => $lastres,
                   10777:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  10778:                                          };
                   10779:             } elsif (($startreserve > $now) &&
                   10780:                      (!$endreserve || $endreserve > $startreserve)) {
                   10781:                 $future_reservable{$slot} = {
                   10782:                                               symb         => $symb,
1.1250    raeburn  10783:                                               startreserve => $startreserve,
                   10784:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10785:                                             };
                   10786:             }
                   10787:         }
                   10788:     }
                   10789:     my @unsorted_reservable = keys(%reservable_now);
                   10790:     if (@unsorted_reservable > 0) {
                   10791:         @sorted_reservable = 
                   10792:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10793:     }
                   10794:     my @unsorted_future = keys(%future_reservable);
                   10795:     if (@unsorted_future > 0) {
                   10796:         @sorted_future =
                   10797:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10798:     }
                   10799:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10800: }
1.780     raeburn  10801: 
                   10802: =pod
                   10803: 
1.1057    foxr     10804: =back
                   10805: 
1.549     albertel 10806: =head1 HTTP Helpers
                   10807: 
                   10808: =over 4
                   10809: 
1.648     raeburn  10810: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10811: 
1.258     albertel 10812: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10813: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10814: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10815: 
                   10816: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10817: $possible_names is an ref to an array of form element names.  As an example:
                   10818: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10819: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10820: 
                   10821: =cut
1.1       albertel 10822: 
1.6       albertel 10823: sub get_unprocessed_cgi {
1.25      albertel 10824:   my ($query,$possible_names)= @_;
1.26      matthew  10825:   # $Apache::lonxml::debug=1;
1.356     albertel 10826:   foreach my $pair (split(/&/,$query)) {
                   10827:     my ($name, $value) = split(/=/,$pair);
1.369     www      10828:     $name = &unescape($name);
1.25      albertel 10829:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10830:       $value =~ tr/+/ /;
                   10831:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10832:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10833:     }
1.16      harris41 10834:   }
1.6       albertel 10835: }
                   10836: 
1.112     bowersj2 10837: =pod
                   10838: 
1.648     raeburn  10839: =item * &cacheheader() 
1.112     bowersj2 10840: 
                   10841: returns cache-controlling header code
                   10842: 
                   10843: =cut
                   10844: 
1.7       albertel 10845: sub cacheheader {
1.258     albertel 10846:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10847:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10848:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10849:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10850:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10851:     return $output;
1.7       albertel 10852: }
                   10853: 
1.112     bowersj2 10854: =pod
                   10855: 
1.648     raeburn  10856: =item * &no_cache($r) 
1.112     bowersj2 10857: 
                   10858: specifies header code to not have cache
                   10859: 
                   10860: =cut
                   10861: 
1.9       albertel 10862: sub no_cache {
1.216     albertel 10863:     my ($r) = @_;
                   10864:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10865: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10866:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10867:     $r->no_cache(1);
                   10868:     $r->header_out("Expires" => $date);
                   10869:     $r->header_out("Pragma" => "no-cache");
1.123     www      10870: }
                   10871: 
                   10872: sub content_type {
1.181     albertel 10873:     my ($r,$type,$charset) = @_;
1.299     foxr     10874:     if ($r) {
                   10875: 	#  Note that printout.pl calls this with undef for $r.
                   10876: 	&no_cache($r);
                   10877:     }
1.258     albertel 10878:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10879:     unless ($charset) {
                   10880: 	$charset=&Apache::lonlocal::current_encoding;
                   10881:     }
                   10882:     if ($charset) { $type.='; charset='.$charset; }
                   10883:     if ($r) {
                   10884: 	$r->content_type($type);
                   10885:     } else {
                   10886: 	print("Content-type: $type\n\n");
                   10887:     }
1.9       albertel 10888: }
1.25      albertel 10889: 
1.112     bowersj2 10890: =pod
                   10891: 
1.648     raeburn  10892: =item * &add_to_env($name,$value) 
1.112     bowersj2 10893: 
1.258     albertel 10894: adds $name to the %env hash with value
1.112     bowersj2 10895: $value, if $name already exists, the entry is converted to an array
                   10896: reference and $value is added to the array.
                   10897: 
                   10898: =cut
                   10899: 
1.25      albertel 10900: sub add_to_env {
                   10901:   my ($name,$value)=@_;
1.258     albertel 10902:   if (defined($env{$name})) {
                   10903:     if (ref($env{$name})) {
1.25      albertel 10904:       #already have multiple values
1.258     albertel 10905:       push(@{ $env{$name} },$value);
1.25      albertel 10906:     } else {
                   10907:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10908:       my $first=$env{$name};
                   10909:       undef($env{$name});
                   10910:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10911:     }
                   10912:   } else {
1.258     albertel 10913:     $env{$name}=$value;
1.25      albertel 10914:   }
1.31      albertel 10915: }
1.149     albertel 10916: 
                   10917: =pod
                   10918: 
1.648     raeburn  10919: =item * &get_env_multiple($name) 
1.149     albertel 10920: 
1.258     albertel 10921: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10922: values may be defined and end up as an array ref.
                   10923: 
                   10924: returns an array of values
                   10925: 
                   10926: =cut
                   10927: 
                   10928: sub get_env_multiple {
                   10929:     my ($name) = @_;
                   10930:     my @values;
1.258     albertel 10931:     if (defined($env{$name})) {
1.149     albertel 10932:         # exists is it an array
1.258     albertel 10933:         if (ref($env{$name})) {
                   10934:             @values=@{ $env{$name} };
1.149     albertel 10935:         } else {
1.258     albertel 10936:             $values[0]=$env{$name};
1.149     albertel 10937:         }
                   10938:     }
                   10939:     return(@values);
                   10940: }
                   10941: 
1.1249    damieng  10942: # Looks at given dependencies, and returns something depending on the context.
                   10943: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   10944: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   10945: # For all other contexts, returns ($output, $counter, $numpathchg).
                   10946: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   10947: # $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.
                   10948: # $numpathchg: integer with the number of cleaned up dependency paths.
                   10949: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   10950: # \%mapping: hash reference clean path -> original path for all dependencies.
                   10951: # @param {string} actionurl - The path to the handler, indicative of the context.
                   10952: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   10953: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   10954: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   10955: # @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)
                   10956: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  10957: sub ask_for_embedded_content {
1.1249    damieng  10958:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  10959:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10960:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  10961:         %currsubfile,%unused,$rem);
1.1071    raeburn  10962:     my $counter = 0;
                   10963:     my $numnew = 0;
1.987     raeburn  10964:     my $numremref = 0;
                   10965:     my $numinvalid = 0;
                   10966:     my $numpathchg = 0;
                   10967:     my $numexisting = 0;
1.1071    raeburn  10968:     my $numunused = 0;
                   10969:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  10970:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10971:     my $heading = &mt('Upload embedded files');
                   10972:     my $buttontext = &mt('Upload');
                   10973: 
1.1249    damieng  10974:     # fills these variables based on the context:
                   10975:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   10976:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  10977:     if ($env{'request.course.id'}) {
1.1123    raeburn  10978:         if ($actionurl eq '/adm/dependencies') {
                   10979:             $navmap = Apache::lonnavmaps::navmap->new();
                   10980:         }
                   10981:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10982:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  10983:     }
1.1123    raeburn  10984:     if (($actionurl eq '/adm/portfolio') || 
                   10985:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10986:         my $current_path='/';
                   10987:         if ($env{'form.currentpath'}) {
                   10988:             $current_path = $env{'form.currentpath'};
                   10989:         }
                   10990:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  10991:             $udom = $cdom;
                   10992:             $uname = $cnum;
1.984     raeburn  10993:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10994:         } else {
                   10995:             $udom = $env{'user.domain'};
                   10996:             $uname = $env{'user.name'};
                   10997:             $url = '/userfiles/portfolio';
                   10998:         }
1.987     raeburn  10999:         $toplevel = $url.'/';
1.984     raeburn  11000:         $url .= $current_path;
                   11001:         $getpropath = 1;
1.987     raeburn  11002:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11003:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11004:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11005:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11006:         $toplevel = $url;
1.984     raeburn  11007:         if ($rest ne '') {
1.987     raeburn  11008:             $url .= $rest;
                   11009:         }
                   11010:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11011:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11012:             $url = $args->{'docs_url'};
                   11013:             $toplevel = $url;
1.1084    raeburn  11014:             if ($args->{'context'} eq 'paste') {
                   11015:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11016:                 ($path) = 
                   11017:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11018:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11019:                 $fileloc =~ s{^/}{};
                   11020:             }
1.1071    raeburn  11021:         }
1.1084    raeburn  11022:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11023:         if ($env{'request.course.id'} ne '') {
                   11024:             if (ref($args) eq 'HASH') {
                   11025:                 $url = $args->{'docs_url'};
                   11026:                 $title = $args->{'docs_title'};
1.1126    raeburn  11027:                 $toplevel = $url; 
                   11028:                 unless ($toplevel =~ m{^/}) {
                   11029:                     $toplevel = "/$url";
                   11030:                 }
1.1085    raeburn  11031:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11032:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11033:                     $path = $1;
                   11034:                 } else {
                   11035:                     ($path) =
                   11036:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11037:                 }
1.1195    raeburn  11038:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11039:                     $fileloc = $toplevel;
                   11040:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11041:                     my ($udom,$uname,$fname) =
                   11042:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11043:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11044:                 } else {
                   11045:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11046:                 }
1.1071    raeburn  11047:                 $fileloc =~ s{^/}{};
                   11048:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11049:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11050:             }
1.987     raeburn  11051:         }
1.1123    raeburn  11052:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11053:         $udom = $cdom;
                   11054:         $uname = $cnum;
                   11055:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11056:         $toplevel = $url;
                   11057:         $path = $url;
                   11058:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11059:         $fileloc =~ s{^/}{};
1.987     raeburn  11060:     }
1.1249    damieng  11061:     
                   11062:     # parses the dependency paths to get some info
                   11063:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11064:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11065:     # (will be completed later)
                   11066:     # $mapping:
                   11067:     #   for external URLs: external URL -> external URL
                   11068:     #   for relative paths: clean path -> original path
                   11069:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11070:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11071:     foreach my $file (keys(%{$allfiles})) {
                   11072:         my $embed_file;
                   11073:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11074:             $embed_file = $1;
                   11075:         } else {
                   11076:             $embed_file = $file;
                   11077:         }
1.1158    raeburn  11078:         my ($absolutepath,$cleaned_file);
                   11079:         if ($embed_file =~ m{^\w+://}) {
                   11080:             $cleaned_file = $embed_file;
1.1147    raeburn  11081:             $newfiles{$cleaned_file} = 1;
                   11082:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11083:         } else {
1.1158    raeburn  11084:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11085:             if ($embed_file =~ m{^/}) {
                   11086:                 $absolutepath = $embed_file;
                   11087:             }
1.1147    raeburn  11088:             if ($cleaned_file =~ m{/}) {
                   11089:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11090:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11091:                 my $item = $fname;
                   11092:                 if ($path ne '') {
                   11093:                     $item = $path.'/'.$fname;
                   11094:                     $subdependencies{$path}{$fname} = 1;
                   11095:                 } else {
                   11096:                     $dependencies{$item} = 1;
                   11097:                 }
                   11098:                 if ($absolutepath) {
                   11099:                     $mapping{$item} = $absolutepath;
                   11100:                 } else {
                   11101:                     $mapping{$item} = $embed_file;
                   11102:                 }
                   11103:             } else {
                   11104:                 $dependencies{$embed_file} = 1;
                   11105:                 if ($absolutepath) {
1.1147    raeburn  11106:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11107:                 } else {
1.1147    raeburn  11108:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11109:                 }
                   11110:             }
1.984     raeburn  11111:         }
                   11112:     }
1.1249    damieng  11113:     
                   11114:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11115:     # and lists
                   11116:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11117:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11118:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11119:     #                                    the path had to be cleaned up
                   11120:     # $existing: hash clean path -> 1 if the file exists
                   11121:     # $numexisting: number of keys in $existing
                   11122:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11123:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11124:     #                                      dependency subdirectories that are
                   11125:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11126:     my $dirptr = 16384;
1.984     raeburn  11127:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11128:         $currsubfile{$path} = {};
1.1123    raeburn  11129:         if (($actionurl eq '/adm/portfolio') || 
                   11130:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11131:             my ($sublistref,$listerror) =
                   11132:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11133:             if (ref($sublistref) eq 'ARRAY') {
                   11134:                 foreach my $line (@{$sublistref}) {
                   11135:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11136:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11137:                 }
1.984     raeburn  11138:             }
1.987     raeburn  11139:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11140:             if (opendir(my $dir,$url.'/'.$path)) {
                   11141:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11142:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11143:             }
1.1084    raeburn  11144:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11145:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11146:                   ($args->{'context'} eq 'paste')) ||
                   11147:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11148:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11149:                 my $dir;
                   11150:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11151:                     $dir = $fileloc;
                   11152:                 } else {
                   11153:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11154:                 }
1.1071    raeburn  11155:                 if ($dir ne '') {
                   11156:                     my ($sublistref,$listerror) =
                   11157:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11158:                     if (ref($sublistref) eq 'ARRAY') {
                   11159:                         foreach my $line (@{$sublistref}) {
                   11160:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11161:                                 undef,$mtime)=split(/\&/,$line,12);
                   11162:                             unless (($testdir&$dirptr) ||
                   11163:                                     ($file_name =~ /^\.\.?$/)) {
                   11164:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11165:                             }
                   11166:                         }
                   11167:                     }
                   11168:                 }
1.984     raeburn  11169:             }
                   11170:         }
                   11171:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11172:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11173:                 my $item = $path.'/'.$file;
                   11174:                 unless ($mapping{$item} eq $item) {
                   11175:                     $pathchanges{$item} = 1;
                   11176:                 }
                   11177:                 $existing{$item} = 1;
                   11178:                 $numexisting ++;
                   11179:             } else {
                   11180:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11181:             }
                   11182:         }
1.1071    raeburn  11183:         if ($actionurl eq '/adm/dependencies') {
                   11184:             foreach my $path (keys(%currsubfile)) {
                   11185:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11186:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11187:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11188:                              next if (($rem ne '') &&
                   11189:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11190:                                        (ref($navmap) &&
                   11191:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11192:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11193:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11194:                              $unused{$path.'/'.$file} = 1; 
                   11195:                          }
                   11196:                     }
                   11197:                 }
                   11198:             }
                   11199:         }
1.984     raeburn  11200:     }
1.1249    damieng  11201:     
                   11202:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11203:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11204:     my %currfile;
1.1123    raeburn  11205:     if (($actionurl eq '/adm/portfolio') ||
                   11206:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11207:         my ($dirlistref,$listerror) =
                   11208:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11209:         if (ref($dirlistref) eq 'ARRAY') {
                   11210:             foreach my $line (@{$dirlistref}) {
                   11211:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11212:                 $currfile{$file_name} = 1;
                   11213:             }
1.984     raeburn  11214:         }
1.987     raeburn  11215:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11216:         if (opendir(my $dir,$url)) {
1.987     raeburn  11217:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11218:             map {$currfile{$_} = 1;} @dir_list;
                   11219:         }
1.1084    raeburn  11220:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11221:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11222:               ($args->{'context'} eq 'paste')) ||
                   11223:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11224:         if ($env{'request.course.id'} ne '') {
                   11225:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11226:             if ($dir ne '') {
                   11227:                 my ($dirlistref,$listerror) =
                   11228:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11229:                 if (ref($dirlistref) eq 'ARRAY') {
                   11230:                     foreach my $line (@{$dirlistref}) {
                   11231:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11232:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11233:                         unless (($testdir&$dirptr) ||
                   11234:                                 ($file_name =~ /^\.\.?$/)) {
                   11235:                             $currfile{$file_name} = [$size,$mtime];
                   11236:                         }
                   11237:                     }
                   11238:                 }
                   11239:             }
                   11240:         }
1.984     raeburn  11241:     }
1.1249    damieng  11242:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11243:     # are not in subdirectories, using $currfile
1.984     raeburn  11244:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11245:         if (exists($currfile{$file})) {
1.987     raeburn  11246:             unless ($mapping{$file} eq $file) {
                   11247:                 $pathchanges{$file} = 1;
                   11248:             }
                   11249:             $existing{$file} = 1;
                   11250:             $numexisting ++;
                   11251:         } else {
1.984     raeburn  11252:             $newfiles{$file} = 1;
                   11253:         }
                   11254:     }
1.1071    raeburn  11255:     foreach my $file (keys(%currfile)) {
                   11256:         unless (($file eq $filename) ||
                   11257:                 ($file eq $filename.'.bak') ||
                   11258:                 ($dependencies{$file})) {
1.1085    raeburn  11259:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11260:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11261:                     next if (($rem ne '') &&
                   11262:                              (($env{"httpref.$rem".$file} ne '') ||
                   11263:                               (ref($navmap) &&
                   11264:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11265:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11266:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11267:                 }
1.1085    raeburn  11268:             }
1.1071    raeburn  11269:             $unused{$file} = 1;
                   11270:         }
                   11271:     }
1.1249    damieng  11272:     
                   11273:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11274:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11275:         ($args->{'context'} eq 'paste')) {
                   11276:         $counter = scalar(keys(%existing));
                   11277:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11278:         return ($output,$counter,$numpathchg,\%existing);
                   11279:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11280:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11281:         $counter = scalar(keys(%existing));
                   11282:         $numpathchg = scalar(keys(%pathchanges));
                   11283:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  11284:     }
1.1249    damieng  11285:     
                   11286:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   11287:     
                   11288:     # $upload_output: missing dependencies (with upload form)
                   11289:     # $modify_output: uploaded dependencies (in use)
                   11290:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  11291:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11292:         if ($actionurl eq '/adm/dependencies') {
                   11293:             next if ($embed_file =~ m{^\w+://});
                   11294:         }
1.660     raeburn  11295:         $upload_output .= &start_data_table_row().
1.1123    raeburn  11296:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11297:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11298:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  11299:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11300:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11301:         }
1.1123    raeburn  11302:         $upload_output .= '</td>';
1.1071    raeburn  11303:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  11304:             $upload_output.='<td align="right">'.
                   11305:                             '<span class="LC_info LC_fontsize_medium">'.
                   11306:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11307:             $numremref++;
1.660     raeburn  11308:         } elsif ($args->{'error_on_invalid_names'}
                   11309:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  11310:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11311:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11312:             $numinvalid++;
1.660     raeburn  11313:         } else {
1.1123    raeburn  11314:             $upload_output .= '<td>'.
                   11315:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11316:                                                      $embed_file,\%mapping,
1.1071    raeburn  11317:                                                      $allfiles,$codebase,'upload');
                   11318:             $counter ++;
                   11319:             $numnew ++;
1.987     raeburn  11320:         }
                   11321:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11322:     }
                   11323:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11324:         if ($actionurl eq '/adm/dependencies') {
                   11325:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11326:             $modify_output .= &start_data_table_row().
                   11327:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11328:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11329:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11330:                               '<td>'.$size.'</td>'.
                   11331:                               '<td>'.$mtime.'</td>'.
                   11332:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11333:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11334:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11335:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11336:                               &embedded_file_element('upload_embedded',$counter,
                   11337:                                                      $embed_file,\%mapping,
                   11338:                                                      $allfiles,$codebase,'modify').
                   11339:                               '</div></td>'.
                   11340:                               &end_data_table_row()."\n";
                   11341:             $counter ++;
                   11342:         } else {
                   11343:             $upload_output .= &start_data_table_row().
1.1123    raeburn  11344:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11345:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11346:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11347:                               &Apache::loncommon::end_data_table_row()."\n";
                   11348:         }
                   11349:     }
                   11350:     my $delidx = $counter;
                   11351:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11352:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11353:         $delete_output .= &start_data_table_row().
                   11354:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11355:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11356:                           '<td>'.$size.'</td>'.
                   11357:                           '<td>'.$mtime.'</td>'.
                   11358:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11359:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11360:                           &embedded_file_element('upload_embedded',$delidx,
                   11361:                                                  $oldfile,\%mapping,$allfiles,
                   11362:                                                  $codebase,'delete').'</td>'.
                   11363:                           &end_data_table_row()."\n"; 
                   11364:         $numunused ++;
                   11365:         $delidx ++;
1.987     raeburn  11366:     }
                   11367:     if ($upload_output) {
                   11368:         $upload_output = &start_data_table().
                   11369:                          $upload_output.
                   11370:                          &end_data_table()."\n";
                   11371:     }
1.1071    raeburn  11372:     if ($modify_output) {
                   11373:         $modify_output = &start_data_table().
                   11374:                          &start_data_table_header_row().
                   11375:                          '<th>'.&mt('File').'</th>'.
                   11376:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11377:                          '<th>'.&mt('Modified').'</th>'.
                   11378:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11379:                          &end_data_table_header_row().
                   11380:                          $modify_output.
                   11381:                          &end_data_table()."\n";
                   11382:     }
                   11383:     if ($delete_output) {
                   11384:         $delete_output = &start_data_table().
                   11385:                          &start_data_table_header_row().
                   11386:                          '<th>'.&mt('File').'</th>'.
                   11387:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11388:                          '<th>'.&mt('Modified').'</th>'.
                   11389:                          '<th>'.&mt('Delete?').'</th>'.
                   11390:                          &end_data_table_header_row().
                   11391:                          $delete_output.
                   11392:                          &end_data_table()."\n";
                   11393:     }
1.987     raeburn  11394:     my $applies = 0;
                   11395:     if ($numremref) {
                   11396:         $applies ++;
                   11397:     }
                   11398:     if ($numinvalid) {
                   11399:         $applies ++;
                   11400:     }
                   11401:     if ($numexisting) {
                   11402:         $applies ++;
                   11403:     }
1.1071    raeburn  11404:     if ($counter || $numunused) {
1.987     raeburn  11405:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11406:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11407:                   $state.'<h3>'.$heading.'</h3>'; 
                   11408:         if ($actionurl eq '/adm/dependencies') {
                   11409:             if ($numnew) {
                   11410:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11411:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11412:                            $upload_output.'<br />'."\n";
                   11413:             }
                   11414:             if ($numexisting) {
                   11415:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11416:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11417:                            $modify_output.'<br />'."\n";
                   11418:                            $buttontext = &mt('Save changes');
                   11419:             }
                   11420:             if ($numunused) {
                   11421:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11422:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11423:                            $delete_output.'<br />'."\n";
                   11424:                            $buttontext = &mt('Save changes');
                   11425:             }
                   11426:         } else {
                   11427:             $output .= $upload_output.'<br />'."\n";
                   11428:         }
                   11429:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11430:                    $counter.'" />'."\n";
                   11431:         if ($actionurl eq '/adm/dependencies') { 
                   11432:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11433:                        $numnew.'" />'."\n";
                   11434:         } elsif ($actionurl eq '') {
1.987     raeburn  11435:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11436:         }
                   11437:     } elsif ($applies) {
                   11438:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11439:         if ($applies > 1) {
                   11440:             $output .=  
1.1123    raeburn  11441:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11442:             if ($numremref) {
                   11443:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11444:             }
                   11445:             if ($numinvalid) {
                   11446:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11447:             }
                   11448:             if ($numexisting) {
                   11449:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11450:             }
                   11451:             $output .= '</ul><br />';
                   11452:         } elsif ($numremref) {
                   11453:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11454:         } elsif ($numinvalid) {
                   11455:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11456:         } elsif ($numexisting) {
                   11457:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11458:         }
                   11459:         $output .= $upload_output.'<br />';
                   11460:     }
                   11461:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11462:     $chgcount = $counter;
1.987     raeburn  11463:     if (keys(%pathchanges) > 0) {
                   11464:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11465:             if ($counter) {
1.987     raeburn  11466:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11467:                                                   $embed_file,\%mapping,
1.1071    raeburn  11468:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11469:             } else {
                   11470:                 $pathchange_output .= 
                   11471:                     &start_data_table_row().
                   11472:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11473:                     $chgcount.'" checked="checked" /></td>'.
                   11474:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11475:                     '<td>'.$embed_file.
                   11476:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11477:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11478:                     '</td>'.&end_data_table_row();
1.660     raeburn  11479:             }
1.987     raeburn  11480:             $numpathchg ++;
                   11481:             $chgcount ++;
1.660     raeburn  11482:         }
                   11483:     }
1.1127    raeburn  11484:     if (($counter) || ($numunused)) {
1.987     raeburn  11485:         if ($numpathchg) {
                   11486:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11487:                        $numpathchg.'" />'."\n";
                   11488:         }
                   11489:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11490:             ($actionurl eq '/adm/imsimport')) {
                   11491:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11492:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11493:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11494:         } elsif ($actionurl eq '/adm/dependencies') {
                   11495:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11496:         }
1.1123    raeburn  11497:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11498:     } elsif ($numpathchg) {
                   11499:         my %pathchange = ();
                   11500:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11501:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11502:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11503:         }
1.987     raeburn  11504:     }
1.1071    raeburn  11505:     return ($output,$counter,$numpathchg);
1.987     raeburn  11506: }
                   11507: 
1.1147    raeburn  11508: =pod
                   11509: 
                   11510: =item * clean_path($name)
                   11511: 
                   11512: Performs clean-up of directories, subdirectories and filename in an
                   11513: embedded object, referenced in an HTML file which is being uploaded
                   11514: to a course or portfolio, where 
                   11515: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11516: checked.
                   11517: 
                   11518: Clean-up is similar to replacements in lonnet::clean_filename()
                   11519: except each / between sub-directory and next level is preserved.
                   11520: 
                   11521: =cut
                   11522: 
                   11523: sub clean_path {
                   11524:     my ($embed_file) = @_;
                   11525:     $embed_file =~s{^/+}{};
                   11526:     my @contents;
                   11527:     if ($embed_file =~ m{/}) {
                   11528:         @contents = split(/\//,$embed_file);
                   11529:     } else {
                   11530:         @contents = ($embed_file);
                   11531:     }
                   11532:     my $lastidx = scalar(@contents)-1;
                   11533:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11534:         $contents[$i]=~s{\\}{/}g;
                   11535:         $contents[$i]=~s/\s+/\_/g;
                   11536:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11537:         if ($i == $lastidx) {
                   11538:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11539:         }
                   11540:     }
                   11541:     if ($lastidx > 0) {
                   11542:         return join('/',@contents);
                   11543:     } else {
                   11544:         return $contents[0];
                   11545:     }
                   11546: }
                   11547: 
1.987     raeburn  11548: sub embedded_file_element {
1.1071    raeburn  11549:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11550:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11551:                    (ref($codebase) eq 'HASH'));
                   11552:     my $output;
1.1071    raeburn  11553:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11554:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11555:     }
                   11556:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11557:                &escape($embed_file).'" />';
                   11558:     unless (($context eq 'upload_embedded') && 
                   11559:             ($mapping->{$embed_file} eq $embed_file)) {
                   11560:         $output .='
                   11561:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11562:     }
                   11563:     my $attrib;
                   11564:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11565:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11566:     }
                   11567:     $output .=
                   11568:         "\n\t\t".
                   11569:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11570:         $attrib.'" />';
                   11571:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11572:         $output .=
                   11573:             "\n\t\t".
                   11574:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11575:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11576:     }
1.987     raeburn  11577:     return $output;
1.660     raeburn  11578: }
                   11579: 
1.1071    raeburn  11580: sub get_dependency_details {
                   11581:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11582:     my ($size,$mtime,$showsize,$showmtime);
                   11583:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11584:         if ($embed_file =~ m{/}) {
                   11585:             my ($path,$fname) = split(/\//,$embed_file);
                   11586:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11587:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11588:             }
                   11589:         } else {
                   11590:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11591:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11592:             }
                   11593:         }
                   11594:         $showsize = $size/1024.0;
                   11595:         $showsize = sprintf("%.1f",$showsize);
                   11596:         if ($mtime > 0) {
                   11597:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11598:         }
                   11599:     }
                   11600:     return ($showsize,$showmtime);
                   11601: }
                   11602: 
                   11603: sub ask_embedded_js {
                   11604:     return <<"END";
                   11605: <script type="text/javascript"">
                   11606: // <![CDATA[
                   11607: function toggleBrowse(counter) {
                   11608:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11609:     var fileid = document.getElementById('embedded_item_'+counter);
                   11610:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11611:     if (chkboxid.checked == true) {
                   11612:         uploaddivid.style.display='block';
                   11613:     } else {
                   11614:         uploaddivid.style.display='none';
                   11615:         fileid.value = '';
                   11616:     }
                   11617: }
                   11618: // ]]>
                   11619: </script>
                   11620: 
                   11621: END
                   11622: }
                   11623: 
1.661     raeburn  11624: sub upload_embedded {
                   11625:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11626:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11627:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11628:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11629:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11630:         my $orig_uploaded_filename =
                   11631:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11632:         foreach my $type ('orig','ref','attrib','codebase') {
                   11633:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11634:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11635:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11636:             }
                   11637:         }
1.661     raeburn  11638:         my ($path,$fname) =
                   11639:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11640:         # no path, whole string is fname
                   11641:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11642:         $fname = &Apache::lonnet::clean_filename($fname);
                   11643:         # See if there is anything left
                   11644:         next if ($fname eq '');
                   11645: 
                   11646:         # Check if file already exists as a file or directory.
                   11647:         my ($state,$msg);
                   11648:         if ($context eq 'portfolio') {
                   11649:             my $port_path = $dirpath;
                   11650:             if ($group ne '') {
                   11651:                 $port_path = "groups/$group/$port_path";
                   11652:             }
1.987     raeburn  11653:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11654:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11655:                                               $dir_root,$port_path,$disk_quota,
                   11656:                                               $current_disk_usage,$uname,$udom);
                   11657:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11658:                 || $state eq 'file_locked') {
1.661     raeburn  11659:                 $output .= $msg;
                   11660:                 next;
                   11661:             }
                   11662:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11663:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11664:             if ($state eq 'exists') {
                   11665:                 $output .= $msg;
                   11666:                 next;
                   11667:             }
                   11668:         }
                   11669:         # Check if extension is valid
                   11670:         if (($fname =~ /\.(\w+)$/) &&
                   11671:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   11672:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11673:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11674:             next;
                   11675:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11676:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11677:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11678:             next;
                   11679:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   11680:             $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  11681:             next;
                   11682:         }
                   11683:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  11684:         my $subdir = $path;
                   11685:         $subdir =~ s{/+$}{};
1.661     raeburn  11686:         if ($context eq 'portfolio') {
1.984     raeburn  11687:             my $result;
                   11688:             if ($state eq 'existingfile') {
                   11689:                 $result=
                   11690:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  11691:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11692:             } else {
1.984     raeburn  11693:                 $result=
                   11694:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11695:                                                     $dirpath.
1.1123    raeburn  11696:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11697:                 if ($result !~ m|^/uploaded/|) {
                   11698:                     $output .= '<span class="LC_error">'
                   11699:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11700:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11701:                                .'</span><br />';
                   11702:                     next;
                   11703:                 } else {
1.987     raeburn  11704:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11705:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11706:                 }
1.661     raeburn  11707:             }
1.1123    raeburn  11708:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  11709:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11710:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11711:             my $result =
1.1126    raeburn  11712:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11713:             if ($result !~ m|^/uploaded/|) {
                   11714:                 $output .= '<span class="LC_error">'
                   11715:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11716:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11717:                            .'</span><br />';
                   11718:                     next;
                   11719:             } else {
                   11720:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11721:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11722:                 if ($context eq 'syllabus') {
                   11723:                     &Apache::lonnet::make_public_indefinitely($result);
                   11724:                 }
1.987     raeburn  11725:             }
1.661     raeburn  11726:         } else {
                   11727: # Save the file
                   11728:             my $target = $env{'form.embedded_item_'.$i};
                   11729:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11730:             my $dest = $fullpath.$fname;
                   11731:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11732:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11733:             my $count;
                   11734:             my $filepath = $dir_root;
1.1027    raeburn  11735:             foreach my $subdir (@parts) {
                   11736:                 $filepath .= "/$subdir";
                   11737:                 if (!-e $filepath) {
1.661     raeburn  11738:                     mkdir($filepath,0770);
                   11739:                 }
                   11740:             }
                   11741:             my $fh;
                   11742:             if (!open($fh,'>'.$dest)) {
                   11743:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11744:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11745:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11746:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11747:                            '</span><br />';
                   11748:             } else {
                   11749:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11750:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11751:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11752:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11753:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11754:                               '</span><br />';
                   11755:                 } else {
1.987     raeburn  11756:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11757:                                $url.'</span>').'<br />';
                   11758:                     unless ($context eq 'testbank') {
                   11759:                         $footer .= &mt('View embedded file: [_1]',
                   11760:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11761:                     }
                   11762:                 }
                   11763:                 close($fh);
                   11764:             }
                   11765:         }
                   11766:         if ($env{'form.embedded_ref_'.$i}) {
                   11767:             $pathchange{$i} = 1;
                   11768:         }
                   11769:     }
                   11770:     if ($output) {
                   11771:         $output = '<p>'.$output.'</p>';
                   11772:     }
                   11773:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11774:     $returnflag = 'ok';
1.1071    raeburn  11775:     my $numpathchgs = scalar(keys(%pathchange));
                   11776:     if ($numpathchgs > 0) {
1.987     raeburn  11777:         if ($context eq 'portfolio') {
                   11778:             $output .= '<p>'.&mt('or').'</p>';
                   11779:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11780:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11781:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11782:             $returnflag = 'modify_orightml';
                   11783:         }
                   11784:     }
1.1071    raeburn  11785:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11786: }
                   11787: 
                   11788: sub modify_html_form {
                   11789:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11790:     my $end = 0;
                   11791:     my $modifyform;
                   11792:     if ($context eq 'upload_embedded') {
                   11793:         return unless (ref($pathchange) eq 'HASH');
                   11794:         if ($env{'form.number_embedded_items'}) {
                   11795:             $end += $env{'form.number_embedded_items'};
                   11796:         }
                   11797:         if ($env{'form.number_pathchange_items'}) {
                   11798:             $end += $env{'form.number_pathchange_items'};
                   11799:         }
                   11800:         if ($end) {
                   11801:             for (my $i=0; $i<$end; $i++) {
                   11802:                 if ($i < $env{'form.number_embedded_items'}) {
                   11803:                     next unless($pathchange->{$i});
                   11804:                 }
                   11805:                 $modifyform .=
                   11806:                     &start_data_table_row().
                   11807:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11808:                     'checked="checked" /></td>'.
                   11809:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11810:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11811:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11812:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11813:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11814:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11815:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11816:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11817:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11818:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11819:                     &end_data_table_row();
1.1071    raeburn  11820:             }
1.987     raeburn  11821:         }
                   11822:     } else {
                   11823:         $modifyform = $pathchgtable;
                   11824:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11825:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11826:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11827:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11828:         }
                   11829:     }
                   11830:     if ($modifyform) {
1.1071    raeburn  11831:         if ($actionurl eq '/adm/dependencies') {
                   11832:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11833:         }
1.987     raeburn  11834:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11835:                '<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".
                   11836:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11837:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11838:                '</ol></p>'."\n".'<p>'.
                   11839:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11840:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11841:                &start_data_table()."\n".
                   11842:                &start_data_table_header_row().
                   11843:                '<th>'.&mt('Change?').'</th>'.
                   11844:                '<th>'.&mt('Current reference').'</th>'.
                   11845:                '<th>'.&mt('Required reference').'</th>'.
                   11846:                &end_data_table_header_row()."\n".
                   11847:                $modifyform.
                   11848:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11849:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11850:                '</form>'."\n";
                   11851:     }
                   11852:     return;
                   11853: }
                   11854: 
                   11855: sub modify_html_refs {
1.1123    raeburn  11856:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11857:     my $container;
                   11858:     if ($context eq 'portfolio') {
                   11859:         $container = $env{'form.container'};
                   11860:     } elsif ($context eq 'coursedoc') {
                   11861:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11862:     } elsif ($context eq 'manage_dependencies') {
                   11863:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11864:         $container = "/$container";
1.1123    raeburn  11865:     } elsif ($context eq 'syllabus') {
                   11866:         $container = $url;
1.987     raeburn  11867:     } else {
1.1027    raeburn  11868:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11869:     }
                   11870:     my (%allfiles,%codebase,$output,$content);
                   11871:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  11872:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  11873:         if (wantarray) {
                   11874:             return ('',0,0); 
                   11875:         } else {
                   11876:             return;
                   11877:         }
                   11878:     }
                   11879:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11880:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11881:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11882:             if (wantarray) {
                   11883:                 return ('',0,0);
                   11884:             } else {
                   11885:                 return;
                   11886:             }
                   11887:         } 
1.987     raeburn  11888:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11889:         if ($content eq '-1') {
                   11890:             if (wantarray) {
                   11891:                 return ('',0,0);
                   11892:             } else {
                   11893:                 return;
                   11894:             }
                   11895:         }
1.987     raeburn  11896:     } else {
1.1071    raeburn  11897:         unless ($container =~ /^\Q$dir_root\E/) {
                   11898:             if (wantarray) {
                   11899:                 return ('',0,0);
                   11900:             } else {
                   11901:                 return;
                   11902:             }
                   11903:         } 
1.987     raeburn  11904:         if (open(my $fh,"<$container")) {
                   11905:             $content = join('', <$fh>);
                   11906:             close($fh);
                   11907:         } else {
1.1071    raeburn  11908:             if (wantarray) {
                   11909:                 return ('',0,0);
                   11910:             } else {
                   11911:                 return;
                   11912:             }
1.987     raeburn  11913:         }
                   11914:     }
                   11915:     my ($count,$codebasecount) = (0,0);
                   11916:     my $mm = new File::MMagic;
                   11917:     my $mime_type = $mm->checktype_contents($content);
                   11918:     if ($mime_type eq 'text/html') {
                   11919:         my $parse_result = 
                   11920:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11921:                                                     \%codebase,\$content);
                   11922:         if ($parse_result eq 'ok') {
                   11923:             foreach my $i (@changes) {
                   11924:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11925:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11926:                 if ($allfiles{$ref}) {
                   11927:                     my $newname =  $orig;
                   11928:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11929:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11930:                     if ($attrib_regexp =~ /:/) {
                   11931:                         $attrib_regexp =~ s/\:/|/g;
                   11932:                     }
                   11933:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11934:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11935:                         $count += $numchg;
1.1123    raeburn  11936:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  11937:                         delete($allfiles{$ref});
1.987     raeburn  11938:                     }
                   11939:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11940:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11941:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11942:                         $codebasecount ++;
                   11943:                     }
                   11944:                 }
                   11945:             }
1.1123    raeburn  11946:             my $skiprewrites;
1.987     raeburn  11947:             if ($count || $codebasecount) {
                   11948:                 my $saveresult;
1.1071    raeburn  11949:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11950:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11951:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11952:                     if ($url eq $container) {
                   11953:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11954:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11955:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11956:                                             $fname.'</span>').'</p>';
1.987     raeburn  11957:                     } else {
                   11958:                          $output = '<p class="LC_error">'.
                   11959:                                    &mt('Error: update failed for: [_1].',
                   11960:                                    '<span class="LC_filename">'.
                   11961:                                    $container.'</span>').'</p>';
                   11962:                     }
1.1123    raeburn  11963:                     if ($context eq 'syllabus') {
                   11964:                         unless ($saveresult eq 'ok') {
                   11965:                             $skiprewrites = 1;
                   11966:                         }
                   11967:                     }
1.987     raeburn  11968:                 } else {
                   11969:                     if (open(my $fh,">$container")) {
                   11970:                         print $fh $content;
                   11971:                         close($fh);
                   11972:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11973:                                   $count,'<span class="LC_filename">'.
                   11974:                                   $container.'</span>').'</p>';
1.661     raeburn  11975:                     } else {
1.987     raeburn  11976:                          $output = '<p class="LC_error">'.
                   11977:                                    &mt('Error: could not update [_1].',
                   11978:                                    '<span class="LC_filename">'.
                   11979:                                    $container.'</span>').'</p>';
1.661     raeburn  11980:                     }
                   11981:                 }
                   11982:             }
1.1123    raeburn  11983:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11984:                 my ($actionurl,$state);
                   11985:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11986:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11987:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11988:                                               \%codebase,
                   11989:                                               {'context' => 'rewrites',
                   11990:                                                'ignore_remote_references' => 1,});
                   11991:                 if (ref($mapping) eq 'HASH') {
                   11992:                     my $rewrites = 0;
                   11993:                     foreach my $key (keys(%{$mapping})) {
                   11994:                         next if ($key =~ m{^https?://});
                   11995:                         my $ref = $mapping->{$key};
                   11996:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11997:                         my $attrib;
                   11998:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11999:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12000:                         }
                   12001:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12002:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12003:                             $rewrites += $numchg;
                   12004:                         }
                   12005:                     }
                   12006:                     if ($rewrites) {
                   12007:                         my $saveresult; 
                   12008:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12009:                         if ($url eq $container) {
                   12010:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12011:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12012:                                             $count,'<span class="LC_filename">'.
                   12013:                                             $fname.'</span>').'</p>';
                   12014:                         } else {
                   12015:                             $output .= '<p class="LC_error">'.
                   12016:                                        &mt('Error: could not update links in [_1].',
                   12017:                                        '<span class="LC_filename">'.
                   12018:                                        $container.'</span>').'</p>';
                   12019: 
                   12020:                         }
                   12021:                     }
                   12022:                 }
                   12023:             }
1.987     raeburn  12024:         } else {
                   12025:             &logthis('Failed to parse '.$container.
                   12026:                      ' to modify references: '.$parse_result);
1.661     raeburn  12027:         }
                   12028:     }
1.1071    raeburn  12029:     if (wantarray) {
                   12030:         return ($output,$count,$codebasecount);
                   12031:     } else {
                   12032:         return $output;
                   12033:     }
1.661     raeburn  12034: }
                   12035: 
                   12036: sub check_for_existing {
                   12037:     my ($path,$fname,$element) = @_;
                   12038:     my ($state,$msg);
                   12039:     if (-d $path.'/'.$fname) {
                   12040:         $state = 'exists';
                   12041:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12042:     } elsif (-e $path.'/'.$fname) {
                   12043:         $state = 'exists';
                   12044:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12045:     }
                   12046:     if ($state eq 'exists') {
                   12047:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12048:     }
                   12049:     return ($state,$msg);
                   12050: }
                   12051: 
                   12052: sub check_for_upload {
                   12053:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12054:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12055:     my $filesize = length($env{'form.'.$element});
                   12056:     if (!$filesize) {
                   12057:         my $msg = '<span class="LC_error">'.
                   12058:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12059:                       '<span class="LC_filename">'.$fname.'</span>',
                   12060:                       $filesize).'<br />'.
1.1007    raeburn  12061:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12062:                   '</span>';
                   12063:         return ('zero_bytes',$msg);
                   12064:     }
                   12065:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12066:     my $getpropath = 1;
1.1021    raeburn  12067:     my ($dirlistref,$listerror) =
                   12068:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12069:     my $found_file = 0;
                   12070:     my $locked_file = 0;
1.991     raeburn  12071:     my @lockers;
                   12072:     my $navmap;
                   12073:     if ($env{'request.course.id'}) {
                   12074:         $navmap = Apache::lonnavmaps::navmap->new();
                   12075:     }
1.1021    raeburn  12076:     if (ref($dirlistref) eq 'ARRAY') {
                   12077:         foreach my $line (@{$dirlistref}) {
                   12078:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12079:             if ($file_name eq $fname){
                   12080:                 $file_name = $path.$file_name;
                   12081:                 if ($group ne '') {
                   12082:                     $file_name = $group.$file_name;
                   12083:                 }
                   12084:                 $found_file = 1;
                   12085:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12086:                     foreach my $lock (@lockers) {
                   12087:                         if (ref($lock) eq 'ARRAY') {
                   12088:                             my ($symb,$crsid) = @{$lock};
                   12089:                             if ($crsid eq $env{'request.course.id'}) {
                   12090:                                 if (ref($navmap)) {
                   12091:                                     my $res = $navmap->getBySymb($symb);
                   12092:                                     foreach my $part (@{$res->parts()}) { 
                   12093:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12094:                                         unless (($slot_status == $res->RESERVED) ||
                   12095:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12096:                                             $locked_file = 1;
                   12097:                                         }
1.991     raeburn  12098:                                     }
1.1021    raeburn  12099:                                 } else {
                   12100:                                     $locked_file = 1;
1.991     raeburn  12101:                                 }
                   12102:                             } else {
                   12103:                                 $locked_file = 1;
                   12104:                             }
                   12105:                         }
1.1021    raeburn  12106:                    }
                   12107:                 } else {
                   12108:                     my @info = split(/\&/,$rest);
                   12109:                     my $currsize = $info[6]/1000;
                   12110:                     if ($currsize < $filesize) {
                   12111:                         my $extra = $filesize - $currsize;
                   12112:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12113:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12114:                                       &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   12115:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12116:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12117:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12118:                             return ('will_exceed_quota',$msg);
                   12119:                         }
1.984     raeburn  12120:                     }
                   12121:                 }
1.661     raeburn  12122:             }
                   12123:         }
                   12124:     }
                   12125:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12126:         my $msg = '<p class="LC_warning">'.
                   12127:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12128:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12129:         return ('will_exceed_quota',$msg);
                   12130:     } elsif ($found_file) {
                   12131:         if ($locked_file) {
1.1179    bisitz   12132:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12133:             $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   12134:             $msg .= '</p>';
1.661     raeburn  12135:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12136:             return ('file_locked',$msg);
                   12137:         } else {
1.1179    bisitz   12138:             my $msg = '<p class="LC_error">';
1.984     raeburn  12139:             $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   12140:             $msg .= '</p>';
1.984     raeburn  12141:             return ('existingfile',$msg);
1.661     raeburn  12142:         }
                   12143:     }
                   12144: }
                   12145: 
1.987     raeburn  12146: sub check_for_traversal {
                   12147:     my ($path,$url,$toplevel) = @_;
                   12148:     my @parts=split(/\//,$path);
                   12149:     my $cleanpath;
                   12150:     my $fullpath = $url;
                   12151:     for (my $i=0;$i<@parts;$i++) {
                   12152:         next if ($parts[$i] eq '.');
                   12153:         if ($parts[$i] eq '..') {
                   12154:             $fullpath =~ s{([^/]+/)$}{};
                   12155:         } else {
                   12156:             $fullpath .= $parts[$i].'/';
                   12157:         }
                   12158:     }
                   12159:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12160:         $cleanpath = $1;
                   12161:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12162:         my $curr_toprel = $1;
                   12163:         my @parts = split(/\//,$curr_toprel);
                   12164:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12165:         my @urlparts = split(/\//,$url_toprel);
                   12166:         my $doubledots;
                   12167:         my $startdiff = -1;
                   12168:         for (my $i=0; $i<@urlparts; $i++) {
                   12169:             if ($startdiff == -1) {
                   12170:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12171:                     $startdiff = $i;
                   12172:                     $doubledots .= '../';
                   12173:                 }
                   12174:             } else {
                   12175:                 $doubledots .= '../';
                   12176:             }
                   12177:         }
                   12178:         if ($startdiff > -1) {
                   12179:             $cleanpath = $doubledots;
                   12180:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12181:                 $cleanpath .= $parts[$i].'/';
                   12182:             }
                   12183:         }
                   12184:     }
                   12185:     $cleanpath =~ s{(/)$}{};
                   12186:     return $cleanpath;
                   12187: }
1.31      albertel 12188: 
1.1053    raeburn  12189: sub is_archive_file {
                   12190:     my ($mimetype) = @_;
                   12191:     if (($mimetype eq 'application/octet-stream') ||
                   12192:         ($mimetype eq 'application/x-stuffit') ||
                   12193:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12194:         return 1;
                   12195:     }
                   12196:     return;
                   12197: }
                   12198: 
                   12199: sub decompress_form {
1.1065    raeburn  12200:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12201:     my %lt = &Apache::lonlocal::texthash (
                   12202:         this => 'This file is an archive file.',
1.1067    raeburn  12203:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12204:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12205:         youm => 'You may wish to extract its contents.',
                   12206:         extr => 'Extract contents',
1.1067    raeburn  12207:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12208:         proa => 'Process automatically?',
1.1053    raeburn  12209:         yes  => 'Yes',
                   12210:         no   => 'No',
1.1067    raeburn  12211:         fold => 'Title for folder containing movie',
                   12212:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12213:     );
1.1065    raeburn  12214:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12215:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12216:     my $info = &list_archive_contents($fileloc,\@paths);
                   12217:     if (@paths) {
                   12218:         foreach my $path (@paths) {
                   12219:             $path =~ s{^/}{};
1.1067    raeburn  12220:             if ($path =~ m{^([^/]+)/$}) {
                   12221:                 $topdir = $1;
                   12222:             }
1.1065    raeburn  12223:             if ($path =~ m{^([^/]+)/}) {
                   12224:                 $toplevel{$1} = $path;
                   12225:             } else {
                   12226:                 $toplevel{$path} = $path;
                   12227:             }
                   12228:         }
                   12229:     }
1.1067    raeburn  12230:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12231:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12232:                         "$topdir/media/",
                   12233:                         "$topdir/media/$topdir.mp4",
                   12234:                         "$topdir/media/FirstFrame.png",
                   12235:                         "$topdir/media/player.swf",
                   12236:                         "$topdir/media/swfobject.js",
                   12237:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12238:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12239:                          "$topdir/$topdir.mp4",
                   12240:                          "$topdir/$topdir\_config.xml",
                   12241:                          "$topdir/$topdir\_controller.swf",
                   12242:                          "$topdir/$topdir\_embed.css",
                   12243:                          "$topdir/$topdir\_First_Frame.png",
                   12244:                          "$topdir/$topdir\_player.html",
                   12245:                          "$topdir/$topdir\_Thumbnails.png",
                   12246:                          "$topdir/playerProductInstall.swf",
                   12247:                          "$topdir/scripts/",
                   12248:                          "$topdir/scripts/config_xml.js",
                   12249:                          "$topdir/scripts/handlebars.js",
                   12250:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12251:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12252:                          "$topdir/scripts/modernizr.js",
                   12253:                          "$topdir/scripts/player-min.js",
                   12254:                          "$topdir/scripts/swfobject.js",
                   12255:                          "$topdir/skins/",
                   12256:                          "$topdir/skins/configuration_express.xml",
                   12257:                          "$topdir/skins/express_show/",
                   12258:                          "$topdir/skins/express_show/player-min.css",
                   12259:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12260:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12261:                          "$topdir/$topdir.mp4",
                   12262:                          "$topdir/$topdir\_config.xml",
                   12263:                          "$topdir/$topdir\_controller.swf",
                   12264:                          "$topdir/$topdir\_embed.css",
                   12265:                          "$topdir/$topdir\_First_Frame.png",
                   12266:                          "$topdir/$topdir\_player.html",
                   12267:                          "$topdir/$topdir\_Thumbnails.png",
                   12268:                          "$topdir/playerProductInstall.swf",
                   12269:                          "$topdir/scripts/",
                   12270:                          "$topdir/scripts/config_xml.js",
                   12271:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12272:                          "$topdir/skins/",
                   12273:                          "$topdir/skins/configuration_express.xml",
                   12274:                          "$topdir/skins/express_show/",
                   12275:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12276:                          "$topdir/skins/express_show/spritesheet.png",
                   12277:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12278:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12279:         if (@diffs == 0) {
1.1164    raeburn  12280:             $is_camtasia = 6;
                   12281:         } else {
1.1197    raeburn  12282:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12283:             if (@diffs == 0) {
                   12284:                 $is_camtasia = 8;
1.1197    raeburn  12285:             } else {
                   12286:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12287:                 if (@diffs == 0) {
                   12288:                     $is_camtasia = 8;
                   12289:                 }
1.1164    raeburn  12290:             }
1.1067    raeburn  12291:         }
                   12292:     }
                   12293:     my $output;
                   12294:     if ($is_camtasia) {
                   12295:         $output = <<"ENDCAM";
                   12296: <script type="text/javascript" language="Javascript">
                   12297: // <![CDATA[
                   12298: 
                   12299: function camtasiaToggle() {
                   12300:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12301:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  12302:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12303:                 document.getElementById('camtasia_titles').style.display='block';
                   12304:             } else {
                   12305:                 document.getElementById('camtasia_titles').style.display='none';
                   12306:             }
                   12307:         }
                   12308:     }
                   12309:     return;
                   12310: }
                   12311: 
                   12312: // ]]>
                   12313: </script>
                   12314: <p>$lt{'camt'}</p>
                   12315: ENDCAM
1.1065    raeburn  12316:     } else {
1.1067    raeburn  12317:         $output = '<p>'.$lt{'this'};
                   12318:         if ($info eq '') {
                   12319:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12320:         } else {
                   12321:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12322:                        '<div><pre>'.$info.'</pre></div>';
                   12323:         }
1.1065    raeburn  12324:     }
1.1067    raeburn  12325:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12326:     my $duplicates;
                   12327:     my $num = 0;
                   12328:     if (ref($dirlist) eq 'ARRAY') {
                   12329:         foreach my $item (@{$dirlist}) {
                   12330:             if (ref($item) eq 'ARRAY') {
                   12331:                 if (exists($toplevel{$item->[0]})) {
                   12332:                     $duplicates .= 
                   12333:                         &start_data_table_row().
                   12334:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12335:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12336:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12337:                         'value="1" />'.&mt('Yes').'</label>'.
                   12338:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12339:                         '<td>'.$item->[0].'</td>';
                   12340:                     if ($item->[2]) {
                   12341:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12342:                     } else {
                   12343:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12344:                     }
                   12345:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12346:                                    '<td>'.
                   12347:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12348:                                    '</td>'.
                   12349:                                    &end_data_table_row();
                   12350:                     $num ++;
                   12351:                 }
                   12352:             }
                   12353:         }
                   12354:     }
                   12355:     my $itemcount;
                   12356:     if (@paths > 0) {
                   12357:         $itemcount = scalar(@paths);
                   12358:     } else {
                   12359:         $itemcount = 1;
                   12360:     }
1.1067    raeburn  12361:     if ($is_camtasia) {
                   12362:         $output .= $lt{'auto'}.'<br />'.
                   12363:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  12364:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12365:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12366:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12367:                    $lt{'no'}.'</label></span><br />'.
                   12368:                    '<div id="camtasia_titles" style="display:block">'.
                   12369:                    &Apache::lonhtmlcommon::start_pick_box().
                   12370:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12371:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12372:                    &Apache::lonhtmlcommon::row_closure().
                   12373:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12374:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12375:                    &Apache::lonhtmlcommon::row_closure(1).
                   12376:                    &Apache::lonhtmlcommon::end_pick_box().
                   12377:                    '</div>';
                   12378:     }
1.1065    raeburn  12379:     $output .= 
                   12380:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12381:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12382:         "\n";
1.1065    raeburn  12383:     if ($duplicates ne '') {
                   12384:         $output .= '<p><span class="LC_warning">'.
                   12385:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12386:                    &start_data_table().
                   12387:                    &start_data_table_header_row().
                   12388:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12389:                    '<th>'.&mt('Name').'</th>'.
                   12390:                    '<th>'.&mt('Type').'</th>'.
                   12391:                    '<th>'.&mt('Size').'</th>'.
                   12392:                    '<th>'.&mt('Last modified').'</th>'.
                   12393:                    &end_data_table_header_row().
                   12394:                    $duplicates.
                   12395:                    &end_data_table().
                   12396:                    '</p>';
                   12397:     }
1.1067    raeburn  12398:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12399:     if (ref($hiddenelements) eq 'HASH') {
                   12400:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12401:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12402:         }
                   12403:     }
                   12404:     $output .= <<"END";
1.1067    raeburn  12405: <br />
1.1053    raeburn  12406: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12407: </form>
                   12408: $noextract
                   12409: END
                   12410:     return $output;
                   12411: }
                   12412: 
1.1065    raeburn  12413: sub decompression_utility {
                   12414:     my ($program) = @_;
                   12415:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12416:     my $location;
                   12417:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12418:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12419:                          '/usr/sbin/') {
                   12420:             if (-x $dir.$program) {
                   12421:                 $location = $dir.$program;
                   12422:                 last;
                   12423:             }
                   12424:         }
                   12425:     }
                   12426:     return $location;
                   12427: }
                   12428: 
                   12429: sub list_archive_contents {
                   12430:     my ($file,$pathsref) = @_;
                   12431:     my (@cmd,$output);
                   12432:     my $needsregexp;
                   12433:     if ($file =~ /\.zip$/) {
                   12434:         @cmd = (&decompression_utility('unzip'),"-l");
                   12435:         $needsregexp = 1;
                   12436:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12437:              ($file =~ /\.tgz$/)) {
                   12438:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12439:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12440:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12441:     } elsif ($file =~ m|\.tar$|) {
                   12442:         @cmd = (&decompression_utility('tar'),"-tf");
                   12443:     }
                   12444:     if (@cmd) {
                   12445:         undef($!);
                   12446:         undef($@);
                   12447:         if (open(my $fh,"-|", @cmd, $file)) {
                   12448:             while (my $line = <$fh>) {
                   12449:                 $output .= $line;
                   12450:                 chomp($line);
                   12451:                 my $item;
                   12452:                 if ($needsregexp) {
                   12453:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12454:                 } else {
                   12455:                     $item = $line;
                   12456:                 }
                   12457:                 if ($item ne '') {
                   12458:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12459:                         push(@{$pathsref},$item);
                   12460:                     } 
                   12461:                 }
                   12462:             }
                   12463:             close($fh);
                   12464:         }
                   12465:     }
                   12466:     return $output;
                   12467: }
                   12468: 
1.1053    raeburn  12469: sub decompress_uploaded_file {
                   12470:     my ($file,$dir) = @_;
                   12471:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12472:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12473:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12474:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12475:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12476:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12477:     my $decompressed = $env{'cgi.decompressed'};
                   12478:     &Apache::lonnet::delenv('cgi.file');
                   12479:     &Apache::lonnet::delenv('cgi.dir');
                   12480:     &Apache::lonnet::delenv('cgi.decompressed');
                   12481:     return ($decompressed,$result);
                   12482: }
                   12483: 
1.1055    raeburn  12484: sub process_decompression {
                   12485:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   12486:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12487:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12488:         $error = &mt('Filename not a supported archive file type.').
                   12489:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12490:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12491:     } else {
                   12492:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12493:         if ($docuhome eq 'no_host') {
                   12494:             $error = &mt('Could not determine home server for course.');
                   12495:         } else {
                   12496:             my @ids=&Apache::lonnet::current_machine_ids();
                   12497:             my $currdir = "$dir_root/$destination";
                   12498:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12499:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12500:                        "$dir_root/$destination";
                   12501:             } else {
                   12502:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12503:                        "$dir_root/$docudom/$docuname/$destination";
                   12504:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12505:                     $error = &mt('Archive file not found.');
                   12506:                 }
                   12507:             }
1.1065    raeburn  12508:             my (@to_overwrite,@to_skip);
                   12509:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12510:                 my $total = $env{'form.archive_overwrite_total'};
                   12511:                 for (my $i=0; $i<$total; $i++) {
                   12512:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12513:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12514:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12515:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12516:                     }
                   12517:                 }
                   12518:             }
                   12519:             my $numskip = scalar(@to_skip);
                   12520:             if (($numskip > 0) && 
                   12521:                 ($numskip == $env{'form.archive_itemcount'})) {
                   12522:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12523:             } elsif ($dir eq '') {
1.1055    raeburn  12524:                 $error = &mt('Directory containing archive file unavailable.');
                   12525:             } elsif (!$error) {
1.1065    raeburn  12526:                 my ($decompressed,$display);
                   12527:                 if ($numskip > 0) {
                   12528:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12529:                     mkdir("$dir/$tempdir",0755);
                   12530:                     system("mv $dir/$file $dir/$tempdir/$file");
                   12531:                     ($decompressed,$display) = 
                   12532:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   12533:                     foreach my $item (@to_skip) {
                   12534:                         if (($item ne '') && ($item !~ /\.\./)) {
                   12535:                             if (-f "$dir/$tempdir/$item") { 
                   12536:                                 unlink("$dir/$tempdir/$item");
                   12537:                             } elsif (-d "$dir/$tempdir/$item") {
                   12538:                                 system("rm -rf $dir/$tempdir/$item");
                   12539:                             }
                   12540:                         }
                   12541:                     }
                   12542:                     system("mv $dir/$tempdir/* $dir");
                   12543:                     rmdir("$dir/$tempdir");   
                   12544:                 } else {
                   12545:                     ($decompressed,$display) = 
                   12546:                         &decompress_uploaded_file($file,$dir);
                   12547:                 }
1.1055    raeburn  12548:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12549:                     $output = '<p class="LC_info">'.
                   12550:                               &mt('Files extracted successfully from archive.').
                   12551:                               '</p>'."\n";
1.1055    raeburn  12552:                     my ($warning,$result,@contents);
                   12553:                     my ($newdirlistref,$newlisterror) =
                   12554:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12555:                                                  $docuname,1);
                   12556:                     my (%is_dir,%changes,@newitems);
                   12557:                     my $dirptr = 16384;
1.1065    raeburn  12558:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12559:                         foreach my $dir_line (@{$newdirlistref}) {
                   12560:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  12561:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   12562:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  12563:                                 push(@newitems,$item);
                   12564:                                 if ($dirptr&$testdir) {
                   12565:                                     $is_dir{$item} = 1;
                   12566:                                 }
                   12567:                                 $changes{$item} = 1;
                   12568:                             }
                   12569:                         }
                   12570:                     }
                   12571:                     if (keys(%changes) > 0) {
                   12572:                         foreach my $item (sort(@newitems)) {
                   12573:                             if ($changes{$item}) {
                   12574:                                 push(@contents,$item);
                   12575:                             }
                   12576:                         }
                   12577:                     }
                   12578:                     if (@contents > 0) {
1.1067    raeburn  12579:                         my $wantform;
                   12580:                         unless ($env{'form.autoextract_camtasia'}) {
                   12581:                             $wantform = 1;
                   12582:                         }
1.1056    raeburn  12583:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12584:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12585:                                                                 $currdir,\%is_dir,
                   12586:                                                                 \%children,\%parent,
1.1056    raeburn  12587:                                                                 \@contents,\%dirorder,
                   12588:                                                                 \%titles,$wantform);
1.1055    raeburn  12589:                         if ($datatable ne '') {
                   12590:                             $output .= &archive_options_form('decompressed',$datatable,
                   12591:                                                              $count,$hiddenelem);
1.1065    raeburn  12592:                             my $startcount = 6;
1.1055    raeburn  12593:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12594:                                                            \%titles,\%children);
1.1055    raeburn  12595:                         }
1.1067    raeburn  12596:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  12597:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12598:                             my %displayed;
                   12599:                             my $total = 1;
                   12600:                             $env{'form.archive_directory'} = [];
                   12601:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12602:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12603:                                 $path =~ s{/$}{};
                   12604:                                 my $item;
                   12605:                                 if ($path ne '') {
                   12606:                                     $item = "$path/$titles{$i}";
                   12607:                                 } else {
                   12608:                                     $item = $titles{$i};
                   12609:                                 }
                   12610:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12611:                                 if ($item eq $contents[0]) {
                   12612:                                     push(@{$env{'form.archive_directory'}},$i);
                   12613:                                     $env{'form.archive_'.$i} = 'display';
                   12614:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12615:                                     $displayed{'folder'} = $i;
1.1164    raeburn  12616:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12617:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  12618:                                     $env{'form.archive_'.$i} = 'display';
                   12619:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12620:                                     $displayed{'web'} = $i;
                   12621:                                 } else {
1.1164    raeburn  12622:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12623:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12624:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12625:                                         push(@{$env{'form.archive_directory'}},$i);
                   12626:                                     }
                   12627:                                     $env{'form.archive_'.$i} = 'dependency';
                   12628:                                 }
                   12629:                                 $total ++;
                   12630:                             }
                   12631:                             for (my $i=1; $i<$total; $i++) {
                   12632:                                 next if ($i == $displayed{'web'});
                   12633:                                 next if ($i == $displayed{'folder'});
                   12634:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12635:                             }
                   12636:                             $env{'form.phase'} = 'decompress_cleanup';
                   12637:                             $env{'form.archivedelete'} = 1;
                   12638:                             $env{'form.archive_count'} = $total-1;
                   12639:                             $output .=
                   12640:                                 &process_extracted_files('coursedocs',$docudom,
                   12641:                                                          $docuname,$destination,
                   12642:                                                          $dir_root,$hiddenelem);
                   12643:                         }
1.1055    raeburn  12644:                     } else {
                   12645:                         $warning = &mt('No new items extracted from archive file.');
                   12646:                     }
                   12647:                 } else {
                   12648:                     $output = $display;
                   12649:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12650:                 }
                   12651:             }
                   12652:         }
                   12653:     }
                   12654:     if ($error) {
                   12655:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12656:                    $error.'</p>'."\n";
                   12657:     }
                   12658:     if ($warning) {
                   12659:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12660:     }
                   12661:     return $output;
                   12662: }
                   12663: 
                   12664: sub get_extracted {
1.1056    raeburn  12665:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12666:         $titles,$wantform) = @_;
1.1055    raeburn  12667:     my $count = 0;
                   12668:     my $depth = 0;
                   12669:     my $datatable;
1.1056    raeburn  12670:     my @hierarchy;
1.1055    raeburn  12671:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12672:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12673:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12674:     foreach my $item (@{$contents}) {
                   12675:         $count ++;
1.1056    raeburn  12676:         @{$dirorder->{$count}} = @hierarchy;
                   12677:         $titles->{$count} = $item;
1.1055    raeburn  12678:         &archive_hierarchy($depth,$count,$parent,$children);
                   12679:         if ($wantform) {
                   12680:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12681:                                        $currdir,$depth,$count);
                   12682:         }
                   12683:         if ($is_dir->{$item}) {
                   12684:             $depth ++;
1.1056    raeburn  12685:             push(@hierarchy,$count);
                   12686:             $parent->{$depth} = $count;
1.1055    raeburn  12687:             $datatable .=
                   12688:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12689:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12690:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12691:             $depth --;
1.1056    raeburn  12692:             pop(@hierarchy);
1.1055    raeburn  12693:         }
                   12694:     }
                   12695:     return ($count,$datatable);
                   12696: }
                   12697: 
                   12698: sub recurse_extracted_archive {
1.1056    raeburn  12699:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12700:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12701:     my $result='';
1.1056    raeburn  12702:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12703:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12704:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12705:         return $result;
                   12706:     }
                   12707:     my $dirptr = 16384;
                   12708:     my ($newdirlistref,$newlisterror) =
                   12709:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12710:     if (ref($newdirlistref) eq 'ARRAY') {
                   12711:         foreach my $dir_line (@{$newdirlistref}) {
                   12712:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12713:             unless ($item =~ /^\.+$/) {
                   12714:                 $$count ++;
1.1056    raeburn  12715:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12716:                 $titles->{$$count} = $item;
1.1055    raeburn  12717:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12718: 
1.1055    raeburn  12719:                 my $is_dir;
                   12720:                 if ($dirptr&$testdir) {
                   12721:                     $is_dir = 1;
                   12722:                 }
                   12723:                 if ($wantform) {
                   12724:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12725:                 }
                   12726:                 if ($is_dir) {
                   12727:                     $$depth ++;
1.1056    raeburn  12728:                     push(@{$hierarchy},$$count);
                   12729:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12730:                     $result .=
                   12731:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12732:                                                    $docuname,$depth,$count,
1.1056    raeburn  12733:                                                    $hierarchy,$dirorder,$children,
                   12734:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12735:                     $$depth --;
1.1056    raeburn  12736:                     pop(@{$hierarchy});
1.1055    raeburn  12737:                 }
                   12738:             }
                   12739:         }
                   12740:     }
                   12741:     return $result;
                   12742: }
                   12743: 
                   12744: sub archive_hierarchy {
                   12745:     my ($depth,$count,$parent,$children) =@_;
                   12746:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12747:         if (exists($parent->{$depth})) {
                   12748:              $children->{$parent->{$depth}} .= $count.':';
                   12749:         }
                   12750:     }
                   12751:     return;
                   12752: }
                   12753: 
                   12754: sub archive_row {
                   12755:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12756:     my ($name) = ($item =~ m{([^/]+)$});
                   12757:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12758:                                        'display'    => 'Add as file',
1.1055    raeburn  12759:                                        'dependency' => 'Include as dependency',
                   12760:                                        'discard'    => 'Discard',
                   12761:                                       );
                   12762:     if ($is_dir) {
1.1059    raeburn  12763:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12764:     }
1.1056    raeburn  12765:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12766:     my $offset = 0;
1.1055    raeburn  12767:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12768:         $offset ++;
1.1065    raeburn  12769:         if ($action ne 'display') {
                   12770:             $offset ++;
                   12771:         }  
1.1055    raeburn  12772:         $output .= '<td><span class="LC_nobreak">'.
                   12773:                    '<label><input type="radio" name="archive_'.$count.
                   12774:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12775:         my $text = $choices{$action};
                   12776:         if ($is_dir) {
                   12777:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12778:             if ($action eq 'display') {
1.1059    raeburn  12779:                 $text = &mt('Add as folder');
1.1055    raeburn  12780:             }
1.1056    raeburn  12781:         } else {
                   12782:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12783: 
                   12784:         }
                   12785:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12786:         if ($action eq 'dependency') {
                   12787:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12788:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12789:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12790:                        '<option value=""></option>'."\n".
                   12791:                        '</select>'."\n".
                   12792:                        '</div>';
1.1059    raeburn  12793:         } elsif ($action eq 'display') {
                   12794:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12795:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12796:                        '</div>';
1.1055    raeburn  12797:         }
1.1056    raeburn  12798:         $output .= '</td>';
1.1055    raeburn  12799:     }
                   12800:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12801:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12802:     for (my $i=0; $i<$depth; $i++) {
                   12803:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12804:     }
                   12805:     if ($is_dir) {
                   12806:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12807:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12808:     } else {
                   12809:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12810:     }
                   12811:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12812:                &end_data_table_row();
                   12813:     return $output;
                   12814: }
                   12815: 
                   12816: sub archive_options_form {
1.1065    raeburn  12817:     my ($form,$display,$count,$hiddenelem) = @_;
                   12818:     my %lt = &Apache::lonlocal::texthash(
                   12819:                perm => 'Permanently remove archive file?',
                   12820:                hows => 'How should each extracted item be incorporated in the course?',
                   12821:                cont => 'Content actions for all',
                   12822:                addf => 'Add as folder/file',
                   12823:                incd => 'Include as dependency for a displayed file',
                   12824:                disc => 'Discard',
                   12825:                no   => 'No',
                   12826:                yes  => 'Yes',
                   12827:                save => 'Save',
                   12828:     );
                   12829:     my $output = <<"END";
                   12830: <form name="$form" method="post" action="">
                   12831: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12832: <label>
                   12833:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12834: </label>
                   12835: &nbsp;
                   12836: <label>
                   12837:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12838: </span>
                   12839: </p>
                   12840: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12841: <br />$lt{'hows'}
                   12842: <div class="LC_columnSection">
                   12843:   <fieldset>
                   12844:     <legend>$lt{'cont'}</legend>
                   12845:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12846:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12847:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12848:   </fieldset>
                   12849: </div>
                   12850: END
                   12851:     return $output.
1.1055    raeburn  12852:            &start_data_table()."\n".
1.1065    raeburn  12853:            $display."\n".
1.1055    raeburn  12854:            &end_data_table()."\n".
                   12855:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12856:            $hiddenelem.
1.1065    raeburn  12857:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12858:            '</form>';
                   12859: }
                   12860: 
                   12861: sub archive_javascript {
1.1056    raeburn  12862:     my ($startcount,$numitems,$titles,$children) = @_;
                   12863:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12864:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12865:     my $scripttag = <<START;
                   12866: <script type="text/javascript">
                   12867: // <![CDATA[
                   12868: 
                   12869: function checkAll(form,prefix) {
                   12870:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12871:     for (var i=0; i < form.elements.length; i++) {
                   12872:         var id = form.elements[i].id;
                   12873:         if ((id != '') && (id != undefined)) {
                   12874:             if (idstr.test(id)) {
                   12875:                 if (form.elements[i].type == 'radio') {
                   12876:                     form.elements[i].checked = true;
1.1056    raeburn  12877:                     var nostart = i-$startcount;
1.1059    raeburn  12878:                     var offset = nostart%7;
                   12879:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12880:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12881:                 }
                   12882:             }
                   12883:         }
                   12884:     }
                   12885: }
                   12886: 
                   12887: function propagateCheck(form,count) {
                   12888:     if (count > 0) {
1.1059    raeburn  12889:         var startelement = $startcount + ((count-1) * 7);
                   12890:         for (var j=1; j<6; j++) {
                   12891:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12892:                 var item = startelement + j; 
                   12893:                 if (form.elements[item].type == 'radio') {
                   12894:                     if (form.elements[item].checked) {
                   12895:                         containerCheck(form,count,j);
                   12896:                         break;
                   12897:                     }
1.1055    raeburn  12898:                 }
                   12899:             }
                   12900:         }
                   12901:     }
                   12902: }
                   12903: 
                   12904: numitems = $numitems
1.1056    raeburn  12905: var titles = new Array(numitems);
                   12906: var parents = new Array(numitems);
1.1055    raeburn  12907: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12908:     parents[i] = new Array;
1.1055    raeburn  12909: }
1.1059    raeburn  12910: var maintitle = '$maintitle';
1.1055    raeburn  12911: 
                   12912: START
                   12913: 
1.1056    raeburn  12914:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12915:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12916:         for (my $i=0; $i<@contents; $i ++) {
                   12917:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12918:         }
                   12919:     }
                   12920: 
1.1056    raeburn  12921:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12922:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12923:     }
                   12924: 
1.1055    raeburn  12925:     $scripttag .= <<END;
                   12926: 
                   12927: function containerCheck(form,count,offset) {
                   12928:     if (count > 0) {
1.1056    raeburn  12929:         dependencyCheck(form,count,offset);
1.1059    raeburn  12930:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12931:         form.elements[item].checked = true;
                   12932:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12933:             if (parents[count].length > 0) {
                   12934:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12935:                     containerCheck(form,parents[count][j],offset);
                   12936:                 }
                   12937:             }
                   12938:         }
                   12939:     }
                   12940: }
                   12941: 
                   12942: function dependencyCheck(form,count,offset) {
                   12943:     if (count > 0) {
1.1059    raeburn  12944:         var chosen = (offset+$startcount)+7*(count-1);
                   12945:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12946:         var currtype = form.elements[depitem].type;
                   12947:         if (form.elements[chosen].value == 'dependency') {
                   12948:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12949:             form.elements[depitem].options.length = 0;
                   12950:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  12951:             for (var i=1; i<=numitems; i++) {
                   12952:                 if (i == count) {
                   12953:                     continue;
                   12954:                 }
1.1059    raeburn  12955:                 var startelement = $startcount + (i-1) * 7;
                   12956:                 for (var j=1; j<6; j++) {
                   12957:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12958:                         var item = startelement + j;
                   12959:                         if (form.elements[item].type == 'radio') {
                   12960:                             if (form.elements[item].checked) {
                   12961:                                 if (form.elements[item].value == 'display') {
                   12962:                                     var n = form.elements[depitem].options.length;
                   12963:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12964:                                 }
                   12965:                             }
                   12966:                         }
                   12967:                     }
                   12968:                 }
                   12969:             }
                   12970:         } else {
                   12971:             document.getElementById('arc_depon_'+count).style.display='none';
                   12972:             form.elements[depitem].options.length = 0;
                   12973:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12974:         }
1.1059    raeburn  12975:         titleCheck(form,count,offset);
1.1056    raeburn  12976:     }
                   12977: }
                   12978: 
                   12979: function propagateSelect(form,count,offset) {
                   12980:     if (count > 0) {
1.1065    raeburn  12981:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12982:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12983:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12984:             if (parents[count].length > 0) {
                   12985:                 for (var j=0; j<parents[count].length; j++) {
                   12986:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12987:                 }
                   12988:             }
                   12989:         }
                   12990:     }
                   12991: }
1.1056    raeburn  12992: 
                   12993: function containerSelect(form,count,offset,picked) {
                   12994:     if (count > 0) {
1.1065    raeburn  12995:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12996:         if (form.elements[item].type == 'radio') {
                   12997:             if (form.elements[item].value == 'dependency') {
                   12998:                 if (form.elements[item+1].type == 'select-one') {
                   12999:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13000:                         if (form.elements[item+1].options[i].value == picked) {
                   13001:                             form.elements[item+1].selectedIndex = i;
                   13002:                             break;
                   13003:                         }
                   13004:                     }
                   13005:                 }
                   13006:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13007:                     if (parents[count].length > 0) {
                   13008:                         for (var j=0; j<parents[count].length; j++) {
                   13009:                             containerSelect(form,parents[count][j],offset,picked);
                   13010:                         }
                   13011:                     }
                   13012:                 }
                   13013:             }
                   13014:         }
                   13015:     }
                   13016: }
                   13017: 
1.1059    raeburn  13018: function titleCheck(form,count,offset) {
                   13019:     if (count > 0) {
                   13020:         var chosen = (offset+$startcount)+7*(count-1);
                   13021:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13022:         var currtype = form.elements[depitem].type;
                   13023:         if (form.elements[chosen].value == 'display') {
                   13024:             document.getElementById('arc_title_'+count).style.display='block';
                   13025:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13026:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13027:             }
                   13028:         } else {
                   13029:             document.getElementById('arc_title_'+count).style.display='none';
                   13030:             if (currtype == 'text') { 
                   13031:                 document.getElementById('archive_title_'+count).value='';
                   13032:             }
                   13033:         }
                   13034:     }
                   13035:     return;
                   13036: }
                   13037: 
1.1055    raeburn  13038: // ]]>
                   13039: </script>
                   13040: END
                   13041:     return $scripttag;
                   13042: }
                   13043: 
                   13044: sub process_extracted_files {
1.1067    raeburn  13045:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13046:     my $numitems = $env{'form.archive_count'};
                   13047:     return unless ($numitems);
                   13048:     my @ids=&Apache::lonnet::current_machine_ids();
                   13049:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13050:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13051:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13052:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13053:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13054:         $pathtocheck = "$dir_root/$destination";
                   13055:         $dir = $dir_root;
                   13056:         $ishome = 1;
                   13057:     } else {
                   13058:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13059:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   13060:         $dir = "$dir_root/$docudom/$docuname";    
                   13061:     }
                   13062:     my $currdir = "$dir_root/$destination";
                   13063:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13064:     if ($env{'form.folderpath'}) {
                   13065:         my @items = split('&',$env{'form.folderpath'});
                   13066:         $folders{'0'} = $items[-2];
1.1099    raeburn  13067:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13068:             $containers{'0'}='page';
                   13069:         } else {  
                   13070:             $containers{'0'}='sequence';
                   13071:         }
1.1055    raeburn  13072:     }
                   13073:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13074:     if ($numitems) {
                   13075:         for (my $i=1; $i<=$numitems; $i++) {
                   13076:             my $path = $env{'form.archive_content_'.$i};
                   13077:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13078:                 my $item = $1;
                   13079:                 $toplevelitems{$item} = $i;
                   13080:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13081:                     $is_dir{$item} = 1;
                   13082:                 }
                   13083:             }
                   13084:         }
                   13085:     }
1.1067    raeburn  13086:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13087:     if (keys(%toplevelitems) > 0) {
                   13088:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13089:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13090:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13091:     }
1.1066    raeburn  13092:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13093:     if ($numitems) {
                   13094:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13095:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13096:             my $path = $env{'form.archive_content_'.$i};
                   13097:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13098:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13099:                     if ($prefix ne '' && $path ne '') {
                   13100:                         if (-e $prefix.$path) {
1.1066    raeburn  13101:                             if ((@archdirs > 0) && 
                   13102:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13103:                                 $todeletedir{$prefix.$path} = 1;
                   13104:                             } else {
                   13105:                                 $todelete{$prefix.$path} = 1;
                   13106:                             }
1.1055    raeburn  13107:                         }
                   13108:                     }
                   13109:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13110:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13111:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13112:                     $docstitle = $env{'form.archive_title_'.$i};
                   13113:                     if ($docstitle eq '') {
                   13114:                         $docstitle = $title;
                   13115:                     }
1.1055    raeburn  13116:                     $outer = 0;
1.1056    raeburn  13117:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13118:                         if (@{$dirorder{$i}} > 0) {
                   13119:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13120:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13121:                                     $outer = $item;
                   13122:                                     last;
                   13123:                                 }
                   13124:                             }
                   13125:                         }
                   13126:                     }
                   13127:                     my ($errtext,$fatal) = 
                   13128:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13129:                                                '/'.$folders{$outer}.'.'.
                   13130:                                                $containers{$outer});
                   13131:                     next if ($fatal);
                   13132:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13133:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13134:                             $mapinner{$i} = time;
1.1055    raeburn  13135:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13136:                             $containers{$i} = 'sequence';
                   13137:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13138:                                       $folders{$i}.'.'.$containers{$i};
                   13139:                             my $newidx = &LONCAPA::map::getresidx();
                   13140:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13141:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13142:                             push(@LONCAPA::map::order,$newidx);
                   13143:                             my ($outtext,$errtext) =
                   13144:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13145:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13146:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13147:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13148:                             unless ($errtext) {
                   13149:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   13150:                             }
1.1055    raeburn  13151:                         }
                   13152:                     } else {
                   13153:                         if ($context eq 'coursedocs') {
                   13154:                             my $newidx=&LONCAPA::map::getresidx();
                   13155:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13156:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13157:                                       $title;
                   13158:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13159:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13160:                             }
                   13161:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13162:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13163:                             }
                   13164:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13165:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  13166:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  13167:                                 unless ($ishome) {
                   13168:                                     my $fetch = "$newdest{$i}/$title";
                   13169:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13170:                                     $prompttofetch{$fetch} = 1;
                   13171:                                 }
1.1055    raeburn  13172:                             }
                   13173:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13174:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13175:                             push(@LONCAPA::map::order, $newidx);
                   13176:                             my ($outtext,$errtext)=
                   13177:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13178:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13179:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  13180:                             unless ($errtext) {
                   13181:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13182:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   13183:                                 }
                   13184:                             }
1.1055    raeburn  13185:                         }
                   13186:                     }
1.1086    raeburn  13187:                 }
                   13188:             } else {
                   13189:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   13190:             }
                   13191:         }
                   13192:         for (my $i=1; $i<=$numitems; $i++) {
                   13193:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13194:             my $path = $env{'form.archive_content_'.$i};
                   13195:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13196:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13197:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13198:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13199:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13200:                         my ($itemidx,$fullpath,$relpath);
                   13201:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13202:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13203:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13204:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13205:                                     $itemidx = $j;
1.1056    raeburn  13206:                                 }
                   13207:                             }
1.1086    raeburn  13208:                         }
                   13209:                         if ($itemidx eq '') {
                   13210:                             $itemidx =  0;
                   13211:                         } 
                   13212:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13213:                             if ($mapinner{$referrer{$i}}) {
                   13214:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13215:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13216:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13217:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13218:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13219:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13220:                                             if (!-e $fullpath) {
                   13221:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13222:                                             }
                   13223:                                         }
1.1086    raeburn  13224:                                     } else {
                   13225:                                         last;
1.1056    raeburn  13226:                                     }
1.1086    raeburn  13227:                                 }
                   13228:                             }
                   13229:                         } elsif ($newdest{$referrer{$i}}) {
                   13230:                             $fullpath = $newdest{$referrer{$i}};
                   13231:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13232:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13233:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13234:                                     last;
                   13235:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13236:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13237:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13238:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13239:                                         if (!-e $fullpath) {
                   13240:                                             mkdir($fullpath,0755);
1.1056    raeburn  13241:                                         }
                   13242:                                     }
1.1086    raeburn  13243:                                 } else {
                   13244:                                     last;
1.1056    raeburn  13245:                                 }
1.1055    raeburn  13246:                             }
                   13247:                         }
1.1086    raeburn  13248:                         if ($fullpath ne '') {
                   13249:                             if (-e "$prefix$path") {
                   13250:                                 system("mv $prefix$path $fullpath/$title");
                   13251:                             }
                   13252:                             if (-e "$fullpath/$title") {
                   13253:                                 my $showpath;
                   13254:                                 if ($relpath ne '') {
                   13255:                                     $showpath = "$relpath/$title";
                   13256:                                 } else {
                   13257:                                     $showpath = "/$title";
                   13258:                                 } 
                   13259:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   13260:                             } 
                   13261:                             unless ($ishome) {
                   13262:                                 my $fetch = "$fullpath/$title";
                   13263:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   13264:                                 $prompttofetch{$fetch} = 1;
                   13265:                             }
                   13266:                         }
1.1055    raeburn  13267:                     }
1.1086    raeburn  13268:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13269:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   13270:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  13271:                 }
                   13272:             } else {
                   13273:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   13274:             }
                   13275:         }
                   13276:         if (keys(%todelete)) {
                   13277:             foreach my $key (keys(%todelete)) {
                   13278:                 unlink($key);
1.1066    raeburn  13279:             }
                   13280:         }
                   13281:         if (keys(%todeletedir)) {
                   13282:             foreach my $key (keys(%todeletedir)) {
                   13283:                 rmdir($key);
                   13284:             }
                   13285:         }
                   13286:         foreach my $dir (sort(keys(%is_dir))) {
                   13287:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13288:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13289:             }
                   13290:         }
1.1067    raeburn  13291:         if ($result ne '') {
                   13292:             $output .= '<ul>'."\n".
                   13293:                        $result."\n".
                   13294:                        '</ul>';
                   13295:         }
                   13296:         unless ($ishome) {
                   13297:             my $replicationfail;
                   13298:             foreach my $item (keys(%prompttofetch)) {
                   13299:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13300:                 unless ($fetchresult eq 'ok') {
                   13301:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13302:                 }
                   13303:             }
                   13304:             if ($replicationfail) {
                   13305:                 $output .= '<p class="LC_error">'.
                   13306:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13307:                            $replicationfail.
                   13308:                            '</ul></p>';
                   13309:             }
                   13310:         }
1.1055    raeburn  13311:     } else {
                   13312:         $warning = &mt('No items found in archive.');
                   13313:     }
                   13314:     if ($error) {
                   13315:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13316:                    $error.'</p>'."\n";
                   13317:     }
                   13318:     if ($warning) {
                   13319:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13320:     }
                   13321:     return $output;
                   13322: }
                   13323: 
1.1066    raeburn  13324: sub cleanup_empty_dirs {
                   13325:     my ($path) = @_;
                   13326:     if (($path ne '') && (-d $path)) {
                   13327:         if (opendir(my $dirh,$path)) {
                   13328:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13329:             my $numitems = 0;
                   13330:             foreach my $item (@dircontents) {
                   13331:                 if (-d "$path/$item") {
1.1111    raeburn  13332:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13333:                     if (-e "$path/$item") {
                   13334:                         $numitems ++;
                   13335:                     }
                   13336:                 } else {
                   13337:                     $numitems ++;
                   13338:                 }
                   13339:             }
                   13340:             if ($numitems == 0) {
                   13341:                 rmdir($path);
                   13342:             }
                   13343:             closedir($dirh);
                   13344:         }
                   13345:     }
                   13346:     return;
                   13347: }
                   13348: 
1.41      ng       13349: =pod
1.45      matthew  13350: 
1.1162    raeburn  13351: =item * &get_folder_hierarchy()
1.1068    raeburn  13352: 
                   13353: Provides hierarchy of names of folders/sub-folders containing the current
                   13354: item,
                   13355: 
                   13356: Inputs: 3
                   13357:      - $navmap - navmaps object
                   13358: 
                   13359:      - $map - url for map (either the trigger itself, or map containing
                   13360:                            the resource, which is the trigger).
                   13361: 
                   13362:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13363: 
                   13364: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13365: 
                   13366: =cut
                   13367: 
                   13368: sub get_folder_hierarchy {
                   13369:     my ($navmap,$map,$showitem) = @_;
                   13370:     my @pathitems;
                   13371:     if (ref($navmap)) {
                   13372:         my $mapres = $navmap->getResourceByUrl($map);
                   13373:         if (ref($mapres)) {
                   13374:             my $pcslist = $mapres->map_hierarchy();
                   13375:             if ($pcslist ne '') {
                   13376:                 my @pcs = split(/,/,$pcslist);
                   13377:                 foreach my $pc (@pcs) {
                   13378:                     if ($pc == 1) {
1.1129    raeburn  13379:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13380:                     } else {
                   13381:                         my $res = $navmap->getByMapPc($pc);
                   13382:                         if (ref($res)) {
                   13383:                             my $title = $res->compTitle();
                   13384:                             $title =~ s/\W+/_/g;
                   13385:                             if ($title ne '') {
                   13386:                                 push(@pathitems,$title);
                   13387:                             }
                   13388:                         }
                   13389:                     }
                   13390:                 }
                   13391:             }
1.1071    raeburn  13392:             if ($showitem) {
                   13393:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  13394:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13395:                 } else {
                   13396:                     my $maptitle = $mapres->compTitle();
                   13397:                     $maptitle =~ s/\W+/_/g;
                   13398:                     if ($maptitle ne '') {
                   13399:                         push(@pathitems,$maptitle);
                   13400:                     }
1.1068    raeburn  13401:                 }
                   13402:             }
                   13403:         }
                   13404:     }
                   13405:     return @pathitems;
                   13406: }
                   13407: 
                   13408: =pod
                   13409: 
1.1015    raeburn  13410: =item * &get_turnedin_filepath()
                   13411: 
                   13412: Determines path in a user's portfolio file for storage of files uploaded
                   13413: to a specific essayresponse or dropbox item.
                   13414: 
                   13415: Inputs: 3 required + 1 optional.
                   13416: $symb is symb for resource, $uname and $udom are for current user (required).
                   13417: $caller is optional (can be "submission", if routine is called when storing
                   13418: an upoaded file when "Submit Answer" button was pressed).
                   13419: 
                   13420: Returns array containing $path and $multiresp. 
                   13421: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13422: than one file upload item.  Callers of routine should append partid as a 
                   13423: subdirectory to $path in cases where $multiresp is 1.
                   13424: 
                   13425: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13426: 
                   13427: =cut
                   13428: 
                   13429: sub get_turnedin_filepath {
                   13430:     my ($symb,$uname,$udom,$caller) = @_;
                   13431:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13432:     my $turnindir;
                   13433:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13434:     $turnindir = $userhash{'turnindir'};
                   13435:     my ($path,$multiresp);
                   13436:     if ($turnindir eq '') {
                   13437:         if ($caller eq 'submission') {
                   13438:             $turnindir = &mt('turned in');
                   13439:             $turnindir =~ s/\W+/_/g;
                   13440:             my %newhash = (
                   13441:                             'turnindir' => $turnindir,
                   13442:                           );
                   13443:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13444:         }
                   13445:     }
                   13446:     if ($turnindir ne '') {
                   13447:         $path = '/'.$turnindir.'/';
                   13448:         my ($multipart,$turnin,@pathitems);
                   13449:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13450:         if (defined($navmap)) {
                   13451:             my $mapres = $navmap->getResourceByUrl($map);
                   13452:             if (ref($mapres)) {
                   13453:                 my $pcslist = $mapres->map_hierarchy();
                   13454:                 if ($pcslist ne '') {
                   13455:                     foreach my $pc (split(/,/,$pcslist)) {
                   13456:                         my $res = $navmap->getByMapPc($pc);
                   13457:                         if (ref($res)) {
                   13458:                             my $title = $res->compTitle();
                   13459:                             $title =~ s/\W+/_/g;
                   13460:                             if ($title ne '') {
1.1149    raeburn  13461:                                 if (($pc > 1) && (length($title) > 12)) {
                   13462:                                     $title = substr($title,0,12);
                   13463:                                 }
1.1015    raeburn  13464:                                 push(@pathitems,$title);
                   13465:                             }
                   13466:                         }
                   13467:                     }
                   13468:                 }
                   13469:                 my $maptitle = $mapres->compTitle();
                   13470:                 $maptitle =~ s/\W+/_/g;
                   13471:                 if ($maptitle ne '') {
1.1149    raeburn  13472:                     if (length($maptitle) > 12) {
                   13473:                         $maptitle = substr($maptitle,0,12);
                   13474:                     }
1.1015    raeburn  13475:                     push(@pathitems,$maptitle);
                   13476:                 }
                   13477:                 unless ($env{'request.state'} eq 'construct') {
                   13478:                     my $res = $navmap->getBySymb($symb);
                   13479:                     if (ref($res)) {
                   13480:                         my $partlist = $res->parts();
                   13481:                         my $totaluploads = 0;
                   13482:                         if (ref($partlist) eq 'ARRAY') {
                   13483:                             foreach my $part (@{$partlist}) {
                   13484:                                 my @types = $res->responseType($part);
                   13485:                                 my @ids = $res->responseIds($part);
                   13486:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13487:                                     if ($types[$i] eq 'essay') {
                   13488:                                         my $partid = $part.'_'.$ids[$i];
                   13489:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13490:                                             $totaluploads ++;
                   13491:                                         }
                   13492:                                     }
                   13493:                                 }
                   13494:                             }
                   13495:                             if ($totaluploads > 1) {
                   13496:                                 $multiresp = 1;
                   13497:                             }
                   13498:                         }
                   13499:                     }
                   13500:                 }
                   13501:             } else {
                   13502:                 return;
                   13503:             }
                   13504:         } else {
                   13505:             return;
                   13506:         }
                   13507:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13508:         $restitle =~ s/\W+/_/g;
                   13509:         if ($restitle eq '') {
                   13510:             $restitle = ($resurl =~ m{/[^/]+$});
                   13511:             if ($restitle eq '') {
                   13512:                 $restitle = time;
                   13513:             }
                   13514:         }
1.1149    raeburn  13515:         if (length($restitle) > 12) {
                   13516:             $restitle = substr($restitle,0,12);
                   13517:         }
1.1015    raeburn  13518:         push(@pathitems,$restitle);
                   13519:         $path .= join('/',@pathitems);
                   13520:     }
                   13521:     return ($path,$multiresp);
                   13522: }
                   13523: 
                   13524: =pod
                   13525: 
1.464     albertel 13526: =back
1.41      ng       13527: 
1.112     bowersj2 13528: =head1 CSV Upload/Handling functions
1.38      albertel 13529: 
1.41      ng       13530: =over 4
                   13531: 
1.648     raeburn  13532: =item * &upfile_store($r)
1.41      ng       13533: 
                   13534: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13535: needs $env{'form.upfile'}
1.41      ng       13536: returns $datatoken to be put into hidden field
                   13537: 
                   13538: =cut
1.31      albertel 13539: 
                   13540: sub upfile_store {
                   13541:     my $r=shift;
1.258     albertel 13542:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13543:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13544:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13545:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13546: 
1.258     albertel 13547:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   13548: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 13549:     {
1.158     raeburn  13550:         my $datafile = $r->dir_config('lonDaemons').
                   13551:                            '/tmp/'.$datatoken.'.tmp';
                   13552:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13553:             print $fh $env{'form.upfile'};
1.158     raeburn  13554:             close($fh);
                   13555:         }
1.31      albertel 13556:     }
                   13557:     return $datatoken;
                   13558: }
                   13559: 
1.56      matthew  13560: =pod
                   13561: 
1.648     raeburn  13562: =item * &load_tmp_file($r)
1.41      ng       13563: 
                   13564: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 13565: needs $env{'form.datatoken'},
                   13566: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13567: 
                   13568: =cut
1.31      albertel 13569: 
                   13570: sub load_tmp_file {
                   13571:     my $r=shift;
                   13572:     my @studentdata=();
                   13573:     {
1.158     raeburn  13574:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13575:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13576:         if ( open(my $fh,"<$studentfile") ) {
                   13577:             @studentdata=<$fh>;
                   13578:             close($fh);
                   13579:         }
1.31      albertel 13580:     }
1.258     albertel 13581:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13582: }
                   13583: 
1.56      matthew  13584: =pod
                   13585: 
1.648     raeburn  13586: =item * &upfile_record_sep()
1.41      ng       13587: 
                   13588: Separate uploaded file into records
                   13589: returns array of records,
1.258     albertel 13590: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13591: 
                   13592: =cut
1.31      albertel 13593: 
                   13594: sub upfile_record_sep {
1.258     albertel 13595:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13596:     } else {
1.248     albertel 13597: 	my @records;
1.258     albertel 13598: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13599: 	    if ($line=~/^\s*$/) { next; }
                   13600: 	    push(@records,$line);
                   13601: 	}
                   13602: 	return @records;
1.31      albertel 13603:     }
                   13604: }
                   13605: 
1.56      matthew  13606: =pod
                   13607: 
1.648     raeburn  13608: =item * &record_sep($record)
1.41      ng       13609: 
1.258     albertel 13610: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13611: 
                   13612: =cut
                   13613: 
1.263     www      13614: sub takeleft {
                   13615:     my $index=shift;
                   13616:     return substr('0000'.$index,-4,4);
                   13617: }
                   13618: 
1.31      albertel 13619: sub record_sep {
                   13620:     my $record=shift;
                   13621:     my %components=();
1.258     albertel 13622:     if ($env{'form.upfiletype'} eq 'xml') {
                   13623:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13624:         my $i=0;
1.356     albertel 13625:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13626:             $field=~s/^(\"|\')//;
                   13627:             $field=~s/(\"|\')$//;
1.263     www      13628:             $components{&takeleft($i)}=$field;
1.31      albertel 13629:             $i++;
                   13630:         }
1.258     albertel 13631:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13632:         my $i=0;
1.356     albertel 13633:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13634:             $field=~s/^(\"|\')//;
                   13635:             $field=~s/(\"|\')$//;
1.263     www      13636:             $components{&takeleft($i)}=$field;
1.31      albertel 13637:             $i++;
                   13638:         }
                   13639:     } else {
1.561     www      13640:         my $separator=',';
1.480     banghart 13641:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13642:             $separator=';';
1.480     banghart 13643:         }
1.31      albertel 13644:         my $i=0;
1.561     www      13645: # the character we are looking for to indicate the end of a quote or a record 
                   13646:         my $looking_for=$separator;
                   13647: # do not add the characters to the fields
                   13648:         my $ignore=0;
                   13649: # we just encountered a separator (or the beginning of the record)
                   13650:         my $just_found_separator=1;
                   13651: # store the field we are working on here
                   13652:         my $field='';
                   13653: # work our way through all characters in record
                   13654:         foreach my $character ($record=~/(.)/g) {
                   13655:             if ($character eq $looking_for) {
                   13656:                if ($character ne $separator) {
                   13657: # Found the end of a quote, again looking for separator
                   13658:                   $looking_for=$separator;
                   13659:                   $ignore=1;
                   13660:                } else {
                   13661: # Found a separator, store away what we got
                   13662:                   $components{&takeleft($i)}=$field;
                   13663: 	          $i++;
                   13664:                   $just_found_separator=1;
                   13665:                   $ignore=0;
                   13666:                   $field='';
                   13667:                }
                   13668:                next;
                   13669:             }
                   13670: # single or double quotation marks after a separator indicate beginning of a quote
                   13671: # we are now looking for the end of the quote and need to ignore separators
                   13672:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13673:                $looking_for=$character;
                   13674:                next;
                   13675:             }
                   13676: # ignore would be true after we reached the end of a quote
                   13677:             if ($ignore) { next; }
                   13678:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13679:             $field.=$character;
                   13680:             $just_found_separator=0; 
1.31      albertel 13681:         }
1.561     www      13682: # catch the very last entry, since we never encountered the separator
                   13683:         $components{&takeleft($i)}=$field;
1.31      albertel 13684:     }
                   13685:     return %components;
                   13686: }
                   13687: 
1.144     matthew  13688: ######################################################
                   13689: ######################################################
                   13690: 
1.56      matthew  13691: =pod
                   13692: 
1.648     raeburn  13693: =item * &upfile_select_html()
1.41      ng       13694: 
1.144     matthew  13695: Return HTML code to select a file from the users machine and specify 
                   13696: the file type.
1.41      ng       13697: 
                   13698: =cut
                   13699: 
1.144     matthew  13700: ######################################################
                   13701: ######################################################
1.31      albertel 13702: sub upfile_select_html {
1.144     matthew  13703:     my %Types = (
                   13704:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13705:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13706:                  space => &mt('Space separated'),
                   13707:                  tab   => &mt('Tabulator separated'),
                   13708: #                 xml   => &mt('HTML/XML'),
                   13709:                  );
                   13710:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13711:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13712:     foreach my $type (sort(keys(%Types))) {
                   13713:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13714:     }
                   13715:     $Str .= "</select>\n";
                   13716:     return $Str;
1.31      albertel 13717: }
                   13718: 
1.301     albertel 13719: sub get_samples {
                   13720:     my ($records,$toget) = @_;
                   13721:     my @samples=({});
                   13722:     my $got=0;
                   13723:     foreach my $rec (@$records) {
                   13724: 	my %temp = &record_sep($rec);
                   13725: 	if (! grep(/\S/, values(%temp))) { next; }
                   13726: 	if (%temp) {
                   13727: 	    $samples[$got]=\%temp;
                   13728: 	    $got++;
                   13729: 	    if ($got == $toget) { last; }
                   13730: 	}
                   13731:     }
                   13732:     return \@samples;
                   13733: }
                   13734: 
1.144     matthew  13735: ######################################################
                   13736: ######################################################
                   13737: 
1.56      matthew  13738: =pod
                   13739: 
1.648     raeburn  13740: =item * &csv_print_samples($r,$records)
1.41      ng       13741: 
                   13742: Prints a table of sample values from each column uploaded $r is an
                   13743: Apache Request ref, $records is an arrayref from
                   13744: &Apache::loncommon::upfile_record_sep
                   13745: 
                   13746: =cut
                   13747: 
1.144     matthew  13748: ######################################################
                   13749: ######################################################
1.31      albertel 13750: sub csv_print_samples {
                   13751:     my ($r,$records) = @_;
1.662     bisitz   13752:     my $samples = &get_samples($records,5);
1.301     albertel 13753: 
1.594     raeburn  13754:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13755:               &start_data_table_header_row());
1.356     albertel 13756:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13757:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13758:     $r->print(&end_data_table_header_row());
1.301     albertel 13759:     foreach my $hash (@$samples) {
1.594     raeburn  13760: 	$r->print(&start_data_table_row());
1.356     albertel 13761: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13762: 	    $r->print('<td>');
1.356     albertel 13763: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13764: 	    $r->print('</td>');
                   13765: 	}
1.594     raeburn  13766: 	$r->print(&end_data_table_row());
1.31      albertel 13767:     }
1.594     raeburn  13768:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13769: }
                   13770: 
1.144     matthew  13771: ######################################################
                   13772: ######################################################
                   13773: 
1.56      matthew  13774: =pod
                   13775: 
1.648     raeburn  13776: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13777: 
                   13778: Prints a table to create associations between values and table columns.
1.144     matthew  13779: 
1.41      ng       13780: $r is an Apache Request ref,
                   13781: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13782: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13783: 
                   13784: =cut
                   13785: 
1.144     matthew  13786: ######################################################
                   13787: ######################################################
1.31      albertel 13788: sub csv_print_select_table {
                   13789:     my ($r,$records,$d) = @_;
1.301     albertel 13790:     my $i=0;
                   13791:     my $samples = &get_samples($records,1);
1.144     matthew  13792:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13793: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13794:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13795:               '<th>'.&mt('Column').'</th>'.
                   13796:               &end_data_table_header_row()."\n");
1.356     albertel 13797:     foreach my $array_ref (@$d) {
                   13798: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13799: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13800: 
1.875     bisitz   13801: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13802: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13803: 	$r->print('<option value="none"></option>');
1.356     albertel 13804: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13805: 	    $r->print('<option value="'.$sample.'"'.
                   13806:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13807:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13808: 	}
1.594     raeburn  13809: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13810: 	$i++;
                   13811:     }
1.594     raeburn  13812:     $r->print(&end_data_table());
1.31      albertel 13813:     $i--;
                   13814:     return $i;
                   13815: }
1.56      matthew  13816: 
1.144     matthew  13817: ######################################################
                   13818: ######################################################
                   13819: 
1.56      matthew  13820: =pod
1.31      albertel 13821: 
1.648     raeburn  13822: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13823: 
                   13824: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13825: 
                   13826: $r is an Apache Request ref,
                   13827: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13828: $d is an array of 2 element arrays (internal name, displayed name)
                   13829: 
                   13830: =cut
                   13831: 
1.144     matthew  13832: ######################################################
                   13833: ######################################################
1.31      albertel 13834: sub csv_samples_select_table {
                   13835:     my ($r,$records,$d) = @_;
                   13836:     my $i=0;
1.144     matthew  13837:     #
1.662     bisitz   13838:     my $max_samples = 5;
                   13839:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13840:     $r->print(&start_data_table().
                   13841:               &start_data_table_header_row().'<th>'.
                   13842:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13843:               &end_data_table_header_row());
1.301     albertel 13844: 
                   13845:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13846: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13847: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13848: 	foreach my $option (@$d) {
                   13849: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13850: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13851:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13852:                       $display.'</option>');
1.31      albertel 13853: 	}
                   13854: 	$r->print('</select></td><td>');
1.662     bisitz   13855: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13856: 	    if (defined($samples->[$line]{$key})) { 
                   13857: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13858: 	    }
                   13859: 	}
1.594     raeburn  13860: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13861: 	$i++;
                   13862:     }
1.594     raeburn  13863:     $r->print(&end_data_table());
1.31      albertel 13864:     $i--;
                   13865:     return($i);
1.115     matthew  13866: }
                   13867: 
1.144     matthew  13868: ######################################################
                   13869: ######################################################
                   13870: 
1.115     matthew  13871: =pod
                   13872: 
1.648     raeburn  13873: =item * &clean_excel_name($name)
1.115     matthew  13874: 
                   13875: Returns a replacement for $name which does not contain any illegal characters.
                   13876: 
                   13877: =cut
                   13878: 
1.144     matthew  13879: ######################################################
                   13880: ######################################################
1.115     matthew  13881: sub clean_excel_name {
                   13882:     my ($name) = @_;
                   13883:     $name =~ s/[:\*\?\/\\]//g;
                   13884:     if (length($name) > 31) {
                   13885:         $name = substr($name,0,31);
                   13886:     }
                   13887:     return $name;
1.25      albertel 13888: }
1.84      albertel 13889: 
1.85      albertel 13890: =pod
                   13891: 
1.648     raeburn  13892: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13893: 
                   13894: Returns either 1 or undef
                   13895: 
                   13896: 1 if the part is to be hidden, undef if it is to be shown
                   13897: 
                   13898: Arguments are:
                   13899: 
                   13900: $id the id of the part to be checked
                   13901: $symb, optional the symb of the resource to check
                   13902: $udom, optional the domain of the user to check for
                   13903: $uname, optional the username of the user to check for
                   13904: 
                   13905: =cut
1.84      albertel 13906: 
                   13907: sub check_if_partid_hidden {
                   13908:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13909:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13910: 					 $symb,$udom,$uname);
1.141     albertel 13911:     my $truth=1;
                   13912:     #if the string starts with !, then the list is the list to show not hide
                   13913:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13914:     my @hiddenlist=split(/,/,$hiddenparts);
                   13915:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13916: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13917:     }
1.141     albertel 13918:     return !$truth;
1.84      albertel 13919: }
1.127     matthew  13920: 
1.138     matthew  13921: 
                   13922: ############################################################
                   13923: ############################################################
                   13924: 
                   13925: =pod
                   13926: 
1.157     matthew  13927: =back 
                   13928: 
1.138     matthew  13929: =head1 cgi-bin script and graphing routines
                   13930: 
1.157     matthew  13931: =over 4
                   13932: 
1.648     raeburn  13933: =item * &get_cgi_id()
1.138     matthew  13934: 
                   13935: Inputs: none
                   13936: 
                   13937: Returns an id which can be used to pass environment variables
                   13938: to various cgi-bin scripts.  These environment variables will
                   13939: be removed from the users environment after a given time by
                   13940: the routine &Apache::lonnet::transfer_profile_to_env.
                   13941: 
                   13942: =cut
                   13943: 
                   13944: ############################################################
                   13945: ############################################################
1.152     albertel 13946: my $uniq=0;
1.136     matthew  13947: sub get_cgi_id {
1.154     albertel 13948:     $uniq=($uniq+1)%100000;
1.280     albertel 13949:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13950: }
                   13951: 
1.127     matthew  13952: ############################################################
                   13953: ############################################################
                   13954: 
                   13955: =pod
                   13956: 
1.648     raeburn  13957: =item * &DrawBarGraph()
1.127     matthew  13958: 
1.138     matthew  13959: Facilitates the plotting of data in a (stacked) bar graph.
                   13960: Puts plot definition data into the users environment in order for 
                   13961: graph.png to plot it.  Returns an <img> tag for the plot.
                   13962: The bars on the plot are labeled '1','2',...,'n'.
                   13963: 
                   13964: Inputs:
                   13965: 
                   13966: =over 4
                   13967: 
                   13968: =item $Title: string, the title of the plot
                   13969: 
                   13970: =item $xlabel: string, text describing the X-axis of the plot
                   13971: 
                   13972: =item $ylabel: string, text describing the Y-axis of the plot
                   13973: 
                   13974: =item $Max: scalar, the maximum Y value to use in the plot
                   13975: If $Max is < any data point, the graph will not be rendered.
                   13976: 
1.140     matthew  13977: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13978: they are plotted.  If undefined, default values will be used.
                   13979: 
1.178     matthew  13980: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13981: 
1.138     matthew  13982: =item @Values: An array of array references.  Each array reference holds data
                   13983: to be plotted in a stacked bar chart.
                   13984: 
1.239     matthew  13985: =item If the final element of @Values is a hash reference the key/value
                   13986: pairs will be added to the graph definition.
                   13987: 
1.138     matthew  13988: =back
                   13989: 
                   13990: Returns:
                   13991: 
                   13992: An <img> tag which references graph.png and the appropriate identifying
                   13993: information for the plot.
                   13994: 
1.127     matthew  13995: =cut
                   13996: 
                   13997: ############################################################
                   13998: ############################################################
1.134     matthew  13999: sub DrawBarGraph {
1.178     matthew  14000:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14001:     #
                   14002:     if (! defined($colors)) {
                   14003:         $colors = ['#33ff00', 
                   14004:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14005:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14006:                   ]; 
                   14007:     }
1.228     matthew  14008:     my $extra_settings = {};
                   14009:     if (ref($Values[-1]) eq 'HASH') {
                   14010:         $extra_settings = pop(@Values);
                   14011:     }
1.127     matthew  14012:     #
1.136     matthew  14013:     my $identifier = &get_cgi_id();
                   14014:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14015:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14016:         return '';
                   14017:     }
1.225     matthew  14018:     #
                   14019:     my @Labels;
                   14020:     if (defined($labels)) {
                   14021:         @Labels = @$labels;
                   14022:     } else {
                   14023:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14024:             push(@Labels,$i+1);
1.225     matthew  14025:         }
                   14026:     }
                   14027:     #
1.129     matthew  14028:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14029:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14030:     my %ValuesHash;
                   14031:     my $NumSets=1;
                   14032:     foreach my $array (@Values) {
                   14033:         next if (! ref($array));
1.136     matthew  14034:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14035:             join(',',@$array);
1.129     matthew  14036:     }
1.127     matthew  14037:     #
1.136     matthew  14038:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14039:     if ($NumBars < 3) {
                   14040:         $width = 120+$NumBars*32;
1.220     matthew  14041:         $xskip = 1;
1.225     matthew  14042:         $bar_width = 30;
                   14043:     } elsif ($NumBars < 5) {
                   14044:         $width = 120+$NumBars*20;
                   14045:         $xskip = 1;
                   14046:         $bar_width = 20;
1.220     matthew  14047:     } elsif ($NumBars < 10) {
1.136     matthew  14048:         $width = 120+$NumBars*15;
                   14049:         $xskip = 1;
                   14050:         $bar_width = 15;
                   14051:     } elsif ($NumBars <= 25) {
                   14052:         $width = 120+$NumBars*11;
                   14053:         $xskip = 5;
                   14054:         $bar_width = 8;
                   14055:     } elsif ($NumBars <= 50) {
                   14056:         $width = 120+$NumBars*8;
                   14057:         $xskip = 5;
                   14058:         $bar_width = 4;
                   14059:     } else {
                   14060:         $width = 120+$NumBars*8;
                   14061:         $xskip = 5;
                   14062:         $bar_width = 4;
                   14063:     }
                   14064:     #
1.137     matthew  14065:     $Max = 1 if ($Max < 1);
                   14066:     if ( int($Max) < $Max ) {
                   14067:         $Max++;
                   14068:         $Max = int($Max);
                   14069:     }
1.127     matthew  14070:     $Title  = '' if (! defined($Title));
                   14071:     $xlabel = '' if (! defined($xlabel));
                   14072:     $ylabel = '' if (! defined($ylabel));
1.369     www      14073:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14074:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14075:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14076:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14077:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14078:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14079:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14080:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14081:     $ValuesHash{$id.'.height'}   = $height;
                   14082:     $ValuesHash{$id.'.width'}    = $width;
                   14083:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14084:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14085:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14086:     #
1.228     matthew  14087:     # Deal with other parameters
                   14088:     while (my ($key,$value) = each(%$extra_settings)) {
                   14089:         $ValuesHash{$id.'.'.$key} = $value;
                   14090:     }
                   14091:     #
1.646     raeburn  14092:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14093:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14094: }
                   14095: 
                   14096: ############################################################
                   14097: ############################################################
                   14098: 
                   14099: =pod
                   14100: 
1.648     raeburn  14101: =item * &DrawXYGraph()
1.137     matthew  14102: 
1.138     matthew  14103: Facilitates the plotting of data in an XY graph.
                   14104: Puts plot definition data into the users environment in order for 
                   14105: graph.png to plot it.  Returns an <img> tag for the plot.
                   14106: 
                   14107: Inputs:
                   14108: 
                   14109: =over 4
                   14110: 
                   14111: =item $Title: string, the title of the plot
                   14112: 
                   14113: =item $xlabel: string, text describing the X-axis of the plot
                   14114: 
                   14115: =item $ylabel: string, text describing the Y-axis of the plot
                   14116: 
                   14117: =item $Max: scalar, the maximum Y value to use in the plot
                   14118: If $Max is < any data point, the graph will not be rendered.
                   14119: 
                   14120: =item $colors: Array ref containing the hex color codes for the data to be 
                   14121: plotted in.  If undefined, default values will be used.
                   14122: 
                   14123: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14124: 
                   14125: =item $Ydata: Array ref containing Array refs.  
1.185     www      14126: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14127: 
                   14128: =item %Values: hash indicating or overriding any default values which are 
                   14129: passed to graph.png.  
                   14130: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14131: 
                   14132: =back
                   14133: 
                   14134: Returns:
                   14135: 
                   14136: An <img> tag which references graph.png and the appropriate identifying
                   14137: information for the plot.
                   14138: 
1.137     matthew  14139: =cut
                   14140: 
                   14141: ############################################################
                   14142: ############################################################
                   14143: sub DrawXYGraph {
                   14144:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14145:     #
                   14146:     # Create the identifier for the graph
                   14147:     my $identifier = &get_cgi_id();
                   14148:     my $id = 'cgi.'.$identifier;
                   14149:     #
                   14150:     $Title  = '' if (! defined($Title));
                   14151:     $xlabel = '' if (! defined($xlabel));
                   14152:     $ylabel = '' if (! defined($ylabel));
                   14153:     my %ValuesHash = 
                   14154:         (
1.369     www      14155:          $id.'.title'  => &escape($Title),
                   14156:          $id.'.xlabel' => &escape($xlabel),
                   14157:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14158:          $id.'.y_max_value'=> $Max,
                   14159:          $id.'.labels'     => join(',',@$Xlabels),
                   14160:          $id.'.PlotType'   => 'XY',
                   14161:          );
                   14162:     #
                   14163:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14164:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14165:     }
                   14166:     #
                   14167:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14168:         return '';
                   14169:     }
                   14170:     my $NumSets=1;
1.138     matthew  14171:     foreach my $array (@{$Ydata}){
1.137     matthew  14172:         next if (! ref($array));
                   14173:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14174:     }
1.138     matthew  14175:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14176:     #
                   14177:     # Deal with other parameters
                   14178:     while (my ($key,$value) = each(%Values)) {
                   14179:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14180:     }
                   14181:     #
1.646     raeburn  14182:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14183:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14184: }
                   14185: 
                   14186: ############################################################
                   14187: ############################################################
                   14188: 
                   14189: =pod
                   14190: 
1.648     raeburn  14191: =item * &DrawXYYGraph()
1.138     matthew  14192: 
                   14193: Facilitates the plotting of data in an XY graph with two Y axes.
                   14194: Puts plot definition data into the users environment in order for 
                   14195: graph.png to plot it.  Returns an <img> tag for the plot.
                   14196: 
                   14197: Inputs:
                   14198: 
                   14199: =over 4
                   14200: 
                   14201: =item $Title: string, the title of the plot
                   14202: 
                   14203: =item $xlabel: string, text describing the X-axis of the plot
                   14204: 
                   14205: =item $ylabel: string, text describing the Y-axis of the plot
                   14206: 
                   14207: =item $colors: Array ref containing the hex color codes for the data to be 
                   14208: plotted in.  If undefined, default values will be used.
                   14209: 
                   14210: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14211: 
                   14212: =item $Ydata1: The first data set
                   14213: 
                   14214: =item $Min1: The minimum value of the left Y-axis
                   14215: 
                   14216: =item $Max1: The maximum value of the left Y-axis
                   14217: 
                   14218: =item $Ydata2: The second data set
                   14219: 
                   14220: =item $Min2: The minimum value of the right Y-axis
                   14221: 
                   14222: =item $Max2: The maximum value of the left Y-axis
                   14223: 
                   14224: =item %Values: hash indicating or overriding any default values which are 
                   14225: passed to graph.png.  
                   14226: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14227: 
                   14228: =back
                   14229: 
                   14230: Returns:
                   14231: 
                   14232: An <img> tag which references graph.png and the appropriate identifying
                   14233: information for the plot.
1.136     matthew  14234: 
                   14235: =cut
                   14236: 
                   14237: ############################################################
                   14238: ############################################################
1.137     matthew  14239: sub DrawXYYGraph {
                   14240:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14241:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14242:     #
                   14243:     # Create the identifier for the graph
                   14244:     my $identifier = &get_cgi_id();
                   14245:     my $id = 'cgi.'.$identifier;
                   14246:     #
                   14247:     $Title  = '' if (! defined($Title));
                   14248:     $xlabel = '' if (! defined($xlabel));
                   14249:     $ylabel = '' if (! defined($ylabel));
                   14250:     my %ValuesHash = 
                   14251:         (
1.369     www      14252:          $id.'.title'  => &escape($Title),
                   14253:          $id.'.xlabel' => &escape($xlabel),
                   14254:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14255:          $id.'.labels' => join(',',@$Xlabels),
                   14256:          $id.'.PlotType' => 'XY',
                   14257:          $id.'.NumSets' => 2,
1.137     matthew  14258:          $id.'.two_axes' => 1,
                   14259:          $id.'.y1_max_value' => $Max1,
                   14260:          $id.'.y1_min_value' => $Min1,
                   14261:          $id.'.y2_max_value' => $Max2,
                   14262:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14263:          );
                   14264:     #
1.137     matthew  14265:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14266:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14267:     }
                   14268:     #
                   14269:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14270:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14271:         return '';
                   14272:     }
                   14273:     my $NumSets=1;
1.137     matthew  14274:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14275:         next if (! ref($array));
                   14276:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14277:     }
                   14278:     #
                   14279:     # Deal with other parameters
                   14280:     while (my ($key,$value) = each(%Values)) {
                   14281:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14282:     }
                   14283:     #
1.646     raeburn  14284:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14285:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14286: }
                   14287: 
                   14288: ############################################################
                   14289: ############################################################
                   14290: 
                   14291: =pod
                   14292: 
1.157     matthew  14293: =back 
                   14294: 
1.139     matthew  14295: =head1 Statistics helper routines?  
                   14296: 
                   14297: Bad place for them but what the hell.
                   14298: 
1.157     matthew  14299: =over 4
                   14300: 
1.648     raeburn  14301: =item * &chartlink()
1.139     matthew  14302: 
                   14303: Returns a link to the chart for a specific student.  
                   14304: 
                   14305: Inputs:
                   14306: 
                   14307: =over 4
                   14308: 
                   14309: =item $linktext: The text of the link
                   14310: 
                   14311: =item $sname: The students username
                   14312: 
                   14313: =item $sdomain: The students domain
                   14314: 
                   14315: =back
                   14316: 
1.157     matthew  14317: =back
                   14318: 
1.139     matthew  14319: =cut
                   14320: 
                   14321: ############################################################
                   14322: ############################################################
                   14323: sub chartlink {
                   14324:     my ($linktext, $sname, $sdomain) = @_;
                   14325:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14326:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14327:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14328:        '">'.$linktext.'</a>';
1.153     matthew  14329: }
                   14330: 
                   14331: #######################################################
                   14332: #######################################################
                   14333: 
                   14334: =pod
                   14335: 
                   14336: =head1 Course Environment Routines
1.157     matthew  14337: 
                   14338: =over 4
1.153     matthew  14339: 
1.648     raeburn  14340: =item * &restore_course_settings()
1.153     matthew  14341: 
1.648     raeburn  14342: =item * &store_course_settings()
1.153     matthew  14343: 
                   14344: Restores/Store indicated form parameters from the course environment.
                   14345: Will not overwrite existing values of the form parameters.
                   14346: 
                   14347: Inputs: 
                   14348: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14349: 
                   14350: a hash ref describing the data to be stored.  For example:
                   14351:    
                   14352: %Save_Parameters = ('Status' => 'scalar',
                   14353:     'chartoutputmode' => 'scalar',
                   14354:     'chartoutputdata' => 'scalar',
                   14355:     'Section' => 'array',
1.373     raeburn  14356:     'Group' => 'array',
1.153     matthew  14357:     'StudentData' => 'array',
                   14358:     'Maps' => 'array');
                   14359: 
                   14360: Returns: both routines return nothing
                   14361: 
1.631     raeburn  14362: =back
                   14363: 
1.153     matthew  14364: =cut
                   14365: 
                   14366: #######################################################
                   14367: #######################################################
                   14368: sub store_course_settings {
1.496     albertel 14369:     return &store_settings($env{'request.course.id'},@_);
                   14370: }
                   14371: 
                   14372: sub store_settings {
1.153     matthew  14373:     # save to the environment
                   14374:     # appenv the same items, just to be safe
1.300     albertel 14375:     my $udom  = $env{'user.domain'};
                   14376:     my $uname = $env{'user.name'};
1.496     albertel 14377:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14378:     my %SaveHash;
                   14379:     my %AppHash;
                   14380:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14381:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14382:         my $envname = 'environment.'.$basename;
1.258     albertel 14383:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14384:             # Save this value away
                   14385:             if ($type eq 'scalar' &&
1.258     albertel 14386:                 (! exists($env{$envname}) || 
                   14387:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14388:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14389:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14390:             } elsif ($type eq 'array') {
                   14391:                 my $stored_form;
1.258     albertel 14392:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14393:                     $stored_form = join(',',
                   14394:                                         map {
1.369     www      14395:                                             &escape($_);
1.258     albertel 14396:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14397:                 } else {
                   14398:                     $stored_form = 
1.369     www      14399:                         &escape($env{'form.'.$setting});
1.153     matthew  14400:                 }
                   14401:                 # Determine if the array contents are the same.
1.258     albertel 14402:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14403:                     $SaveHash{$basename} = $stored_form;
                   14404:                     $AppHash{$envname}   = $stored_form;
                   14405:                 }
                   14406:             }
                   14407:         }
                   14408:     }
                   14409:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14410:                                           $udom,$uname);
1.153     matthew  14411:     if ($put_result !~ /^(ok|delayed)/) {
                   14412:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14413:                                  'got error:'.$put_result);
                   14414:     }
                   14415:     # Make sure these settings stick around in this session, too
1.646     raeburn  14416:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14417:     return;
                   14418: }
                   14419: 
                   14420: sub restore_course_settings {
1.499     albertel 14421:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14422: }
                   14423: 
                   14424: sub restore_settings {
                   14425:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14426:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14427:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14428:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14429:             '.'.$setting;
1.258     albertel 14430:         if (exists($env{$envname})) {
1.153     matthew  14431:             if ($type eq 'scalar') {
1.258     albertel 14432:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14433:             } elsif ($type eq 'array') {
1.258     albertel 14434:                 $env{'form.'.$setting} = [ 
1.153     matthew  14435:                                            map { 
1.369     www      14436:                                                &unescape($_); 
1.258     albertel 14437:                                            } split(',',$env{$envname})
1.153     matthew  14438:                                            ];
                   14439:             }
                   14440:         }
                   14441:     }
1.127     matthew  14442: }
                   14443: 
1.618     raeburn  14444: #######################################################
                   14445: #######################################################
                   14446: 
                   14447: =pod
                   14448: 
                   14449: =head1 Domain E-mail Routines  
                   14450: 
                   14451: =over 4
                   14452: 
1.648     raeburn  14453: =item * &build_recipient_list()
1.618     raeburn  14454: 
1.1144    raeburn  14455: Build recipient lists for following types of e-mail:
1.766     raeburn  14456: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14457: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14458: module change checking, student/employee ID conflict checks, as
                   14459: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14460: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14461: 
                   14462: Inputs:
1.619     raeburn  14463: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14464: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14465: requestsmail, updatesmail, or idconflictsmail).
                   14466: 
1.619     raeburn  14467: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14468: 
1.619     raeburn  14469: origmail (scalar - email address of recipient from loncapa.conf, 
                   14470: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  14471: 
1.655     raeburn  14472: Returns: comma separated list of addresses to which to send e-mail.
                   14473: 
                   14474: =back
1.618     raeburn  14475: 
                   14476: =cut
                   14477: 
                   14478: ############################################################
                   14479: ############################################################
                   14480: sub build_recipient_list {
1.619     raeburn  14481:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  14482:     my @recipients;
                   14483:     my $otheremails;
                   14484:     my %domconfig =
                   14485:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   14486:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14487:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14488:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14489:                 my @contacts = ('adminemail','supportemail');
                   14490:                 foreach my $item (@contacts) {
                   14491:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14492:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14493:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14494:                             push(@recipients,$addr);
                   14495:                         }
1.619     raeburn  14496:                     }
1.766     raeburn  14497:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  14498:                 }
                   14499:             }
1.766     raeburn  14500:         } elsif ($origmail ne '') {
                   14501:             push(@recipients,$origmail);
1.618     raeburn  14502:         }
1.619     raeburn  14503:     } elsif ($origmail ne '') {
                   14504:         push(@recipients,$origmail);
1.618     raeburn  14505:     }
1.688     raeburn  14506:     if (defined($defmail)) {
                   14507:         if ($defmail ne '') {
                   14508:             push(@recipients,$defmail);
                   14509:         }
1.618     raeburn  14510:     }
                   14511:     if ($otheremails) {
1.619     raeburn  14512:         my @others;
                   14513:         if ($otheremails =~ /,/) {
                   14514:             @others = split(/,/,$otheremails);
1.618     raeburn  14515:         } else {
1.619     raeburn  14516:             push(@others,$otheremails);
                   14517:         }
                   14518:         foreach my $addr (@others) {
                   14519:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14520:                 push(@recipients,$addr);
                   14521:             }
1.618     raeburn  14522:         }
                   14523:     }
1.619     raeburn  14524:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  14525:     return $recipientlist;
                   14526: }
                   14527: 
1.127     matthew  14528: ############################################################
                   14529: ############################################################
1.154     albertel 14530: 
1.655     raeburn  14531: =pod
                   14532: 
1.1224    musolffc 14533: =over 4
                   14534: 
1.1223    musolffc 14535: =item * &mime_email()
                   14536: 
                   14537: Sends an email with a possible attachment
                   14538: 
                   14539: Inputs:
                   14540: 
                   14541: =over 4
                   14542: 
                   14543: from -              Sender's email address
                   14544: 
                   14545: to -                Email address of recipient
                   14546: 
                   14547: subject -           Subject of email
                   14548: 
                   14549: body -              Body of email
                   14550: 
                   14551: cc_string -         Carbon copy email address
                   14552: 
                   14553: bcc -               Blind carbon copy email address
                   14554: 
                   14555: type -              File type of attachment
                   14556: 
                   14557: attachment_path -   Path of file to be attached
                   14558: 
                   14559: file_name -         Name of file to be attached
                   14560: 
                   14561: attachment_text -   The body of an attachment of type "TEXT"
                   14562: 
                   14563: =back
                   14564: 
                   14565: =back
                   14566: 
                   14567: =cut
                   14568: 
                   14569: ############################################################
                   14570: ############################################################
                   14571: 
                   14572: sub mime_email {
                   14573:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   14574:         $file_name, $attachment_text) = @_;
                   14575:     my $msg = MIME::Lite->new(
                   14576:              From    => $from,
                   14577:              To      => $to,
                   14578:              Subject => $subject,
                   14579:              Type    =>'TEXT',
                   14580:              Data    => $body,
                   14581:              );
                   14582:     if ($cc_string ne '') {
                   14583:         $msg->add("Cc" => $cc_string);
                   14584:     }
                   14585:     if ($bcc ne '') {
                   14586:         $msg->add("Bcc" => $bcc);
                   14587:     }
                   14588:     $msg->attr("content-type"         => "text/plain");
                   14589:     $msg->attr("content-type.charset" => "UTF-8");
                   14590:     # Attach file if given
                   14591:     if ($attachment_path) {
                   14592:         unless ($file_name) {
                   14593:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   14594:         }
                   14595:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   14596:         $msg->attach(Type     => $type,
                   14597:                      Path     => $attachment_path,
                   14598:                      Filename => $file_name
                   14599:                      );
                   14600:     # Otherwise attach text if given
                   14601:     } elsif ($attachment_text) {
                   14602:         $msg->attach(Type => 'TEXT',
                   14603:                      Data => $attachment_text);
                   14604:     }
                   14605:     # Send it
                   14606:     $msg->send('sendmail');
                   14607: }
                   14608: 
                   14609: ############################################################
                   14610: ############################################################
                   14611: 
                   14612: =pod
                   14613: 
1.655     raeburn  14614: =head1 Course Catalog Routines
                   14615: 
                   14616: =over 4
                   14617: 
                   14618: =item * &gather_categories()
                   14619: 
                   14620: Converts category definitions - keys of categories hash stored in  
                   14621: coursecategories in configuration.db on the primary library server in a 
                   14622: domain - to an array.  Also generates javascript and idx hash used to 
                   14623: generate Domain Coordinator interface for editing Course Categories.
                   14624: 
                   14625: Inputs:
1.663     raeburn  14626: 
1.655     raeburn  14627: categories (reference to hash of category definitions).
1.663     raeburn  14628: 
1.655     raeburn  14629: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14630:       categories and subcategories).
1.663     raeburn  14631: 
1.655     raeburn  14632: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14633:       editing Course Categories).
1.663     raeburn  14634: 
1.655     raeburn  14635: jsarray (reference to array of categories used to create Javascript arrays for
                   14636:          Domain Coordinator interface for editing Course Categories).
                   14637: 
                   14638: Returns: nothing
                   14639: 
                   14640: Side effects: populates cats, idx and jsarray. 
                   14641: 
                   14642: =cut
                   14643: 
                   14644: sub gather_categories {
                   14645:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14646:     my %counters;
                   14647:     my $num = 0;
                   14648:     foreach my $item (keys(%{$categories})) {
                   14649:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14650:         if ($container eq '' && $depth == 0) {
                   14651:             $cats->[$depth][$categories->{$item}] = $cat;
                   14652:         } else {
                   14653:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14654:         }
                   14655:         my ($escitem,$tail) = split(/:/,$item,2);
                   14656:         if ($counters{$tail} eq '') {
                   14657:             $counters{$tail} = $num;
                   14658:             $num ++;
                   14659:         }
                   14660:         if (ref($idx) eq 'HASH') {
                   14661:             $idx->{$item} = $counters{$tail};
                   14662:         }
                   14663:         if (ref($jsarray) eq 'ARRAY') {
                   14664:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14665:         }
                   14666:     }
                   14667:     return;
                   14668: }
                   14669: 
                   14670: =pod
                   14671: 
                   14672: =item * &extract_categories()
                   14673: 
                   14674: Used to generate breadcrumb trails for course categories.
                   14675: 
                   14676: Inputs:
1.663     raeburn  14677: 
1.655     raeburn  14678: categories (reference to hash of category definitions).
1.663     raeburn  14679: 
1.655     raeburn  14680: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14681:       categories and subcategories).
1.663     raeburn  14682: 
1.655     raeburn  14683: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14684: 
1.655     raeburn  14685: allitems (reference to hash - key is category key 
                   14686:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14687: 
1.655     raeburn  14688: idx (reference to hash of counters used in Domain Coordinator interface for
                   14689:       editing Course Categories).
1.663     raeburn  14690: 
1.655     raeburn  14691: jsarray (reference to array of categories used to create Javascript arrays for
                   14692:          Domain Coordinator interface for editing Course Categories).
                   14693: 
1.665     raeburn  14694: subcats (reference to hash of arrays containing all subcategories within each 
                   14695:          category, -recursive)
                   14696: 
1.655     raeburn  14697: Returns: nothing
                   14698: 
                   14699: Side effects: populates trails and allitems hash references.
                   14700: 
                   14701: =cut
                   14702: 
                   14703: sub extract_categories {
1.665     raeburn  14704:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14705:     if (ref($categories) eq 'HASH') {
                   14706:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14707:         if (ref($cats->[0]) eq 'ARRAY') {
                   14708:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14709:                 my $name = $cats->[0][$i];
                   14710:                 my $item = &escape($name).'::0';
                   14711:                 my $trailstr;
                   14712:                 if ($name eq 'instcode') {
                   14713:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14714:                 } elsif ($name eq 'communities') {
                   14715:                     $trailstr = &mt('Communities');
1.1239    raeburn  14716:                 } elsif ($name eq 'placement') {
                   14717:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  14718:                 } else {
                   14719:                     $trailstr = $name;
                   14720:                 }
                   14721:                 if ($allitems->{$item} eq '') {
                   14722:                     push(@{$trails},$trailstr);
                   14723:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14724:                 }
                   14725:                 my @parents = ($name);
                   14726:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14727:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14728:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14729:                         if (ref($subcats) eq 'HASH') {
                   14730:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14731:                         }
                   14732:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14733:                     }
                   14734:                 } else {
                   14735:                     if (ref($subcats) eq 'HASH') {
                   14736:                         $subcats->{$item} = [];
1.655     raeburn  14737:                     }
                   14738:                 }
                   14739:             }
                   14740:         }
                   14741:     }
                   14742:     return;
                   14743: }
                   14744: 
                   14745: =pod
                   14746: 
1.1162    raeburn  14747: =item * &recurse_categories()
1.655     raeburn  14748: 
                   14749: Recursively used to generate breadcrumb trails for course categories.
                   14750: 
                   14751: Inputs:
1.663     raeburn  14752: 
1.655     raeburn  14753: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14754:       categories and subcategories).
1.663     raeburn  14755: 
1.655     raeburn  14756: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14757: 
                   14758: category (current course category, for which breadcrumb trail is being generated).
                   14759: 
                   14760: trails (reference to array of breadcrumb trails for each category).
                   14761: 
1.655     raeburn  14762: allitems (reference to hash - key is category key
                   14763:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14764: 
1.655     raeburn  14765: parents (array containing containers directories for current category, 
                   14766:          back to top level). 
                   14767: 
                   14768: Returns: nothing
                   14769: 
                   14770: Side effects: populates trails and allitems hash references
                   14771: 
                   14772: =cut
                   14773: 
                   14774: sub recurse_categories {
1.665     raeburn  14775:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14776:     my $shallower = $depth - 1;
                   14777:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14778:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14779:             my $name = $cats->[$depth]{$category}[$k];
                   14780:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14781:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14782:             if ($allitems->{$item} eq '') {
                   14783:                 push(@{$trails},$trailstr);
                   14784:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14785:             }
                   14786:             my $deeper = $depth+1;
                   14787:             push(@{$parents},$category);
1.665     raeburn  14788:             if (ref($subcats) eq 'HASH') {
                   14789:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14790:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14791:                     my $higher;
                   14792:                     if ($j > 0) {
                   14793:                         $higher = &escape($parents->[$j]).':'.
                   14794:                                   &escape($parents->[$j-1]).':'.$j;
                   14795:                     } else {
                   14796:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14797:                     }
                   14798:                     push(@{$subcats->{$higher}},$subcat);
                   14799:                 }
                   14800:             }
                   14801:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14802:                                 $subcats);
1.655     raeburn  14803:             pop(@{$parents});
                   14804:         }
                   14805:     } else {
                   14806:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14807:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14808:         if ($allitems->{$item} eq '') {
                   14809:             push(@{$trails},$trailstr);
                   14810:             $allitems->{$item} = scalar(@{$trails})-1;
                   14811:         }
                   14812:     }
                   14813:     return;
                   14814: }
                   14815: 
1.663     raeburn  14816: =pod
                   14817: 
1.1162    raeburn  14818: =item * &assign_categories_table()
1.663     raeburn  14819: 
                   14820: Create a datatable for display of hierarchical categories in a domain,
                   14821: with checkboxes to allow a course to be categorized. 
                   14822: 
                   14823: Inputs:
                   14824: 
                   14825: cathash - reference to hash of categories defined for the domain (from
                   14826:           configuration.db)
                   14827: 
                   14828: currcat - scalar with an & separated list of categories assigned to a course. 
                   14829: 
1.919     raeburn  14830: type    - scalar contains course type (Course or Community).
                   14831: 
1.1260    raeburn  14832: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14833:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14834: 
1.663     raeburn  14835: Returns: $output (markup to be displayed) 
                   14836: 
                   14837: =cut
                   14838: 
                   14839: sub assign_categories_table {
1.1259    raeburn  14840:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14841:     my $output;
                   14842:     if (ref($cathash) eq 'HASH') {
                   14843:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14844:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14845:         $maxdepth = scalar(@cats);
                   14846:         if (@cats > 0) {
                   14847:             my $itemcount = 0;
                   14848:             if (ref($cats[0]) eq 'ARRAY') {
                   14849:                 my @currcategories;
                   14850:                 if ($currcat ne '') {
                   14851:                     @currcategories = split('&',$currcat);
                   14852:                 }
1.919     raeburn  14853:                 my $table;
1.663     raeburn  14854:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14855:                     my $parent = $cats[0][$i];
1.919     raeburn  14856:                     next if ($parent eq 'instcode');
                   14857:                     if ($type eq 'Community') {
                   14858:                         next unless ($parent eq 'communities');
1.1239    raeburn  14859:                     } elsif ($type eq 'Placement') {
                   14860:                         next unless ($parent eq 'placement');
1.919     raeburn  14861:                     } else {
1.1239    raeburn  14862:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  14863:                     }
1.663     raeburn  14864:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14865:                     my $item = &escape($parent).'::0';
                   14866:                     my $checked = '';
                   14867:                     if (@currcategories > 0) {
                   14868:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14869:                             $checked = ' checked="checked"';
1.663     raeburn  14870:                         }
                   14871:                     }
1.919     raeburn  14872:                     my $parent_title = $parent;
                   14873:                     if ($parent eq 'communities') {
                   14874:                         $parent_title = &mt('Communities');
1.1239    raeburn  14875:                     } elsif ($parent eq 'placement') {
                   14876:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  14877:                     }
                   14878:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14879:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  14880:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14881:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14882:                     my $depth = 1;
                   14883:                     push(@path,$parent);
1.1259    raeburn  14884:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14885:                     pop(@path);
1.919     raeburn  14886:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14887:                     $itemcount ++;
                   14888:                 }
1.919     raeburn  14889:                 if ($itemcount) {
                   14890:                     $output = &Apache::loncommon::start_data_table().
                   14891:                               $table.
                   14892:                               &Apache::loncommon::end_data_table();
                   14893:                 }
1.663     raeburn  14894:             }
                   14895:         }
                   14896:     }
                   14897:     return $output;
                   14898: }
                   14899: 
                   14900: =pod
                   14901: 
1.1162    raeburn  14902: =item * &assign_category_rows()
1.663     raeburn  14903: 
                   14904: Create a datatable row for display of nested categories in a domain,
                   14905: with checkboxes to allow a course to be categorized,called recursively.
                   14906: 
                   14907: Inputs:
                   14908: 
                   14909: itemcount - track row number for alternating colors
                   14910: 
                   14911: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14912:       categories and subcategories.
                   14913: 
                   14914: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14915: 
                   14916: parent - parent of current category item
                   14917: 
                   14918: path - Array containing all categories back up through the hierarchy from the
                   14919:        current category to the top level.
                   14920: 
                   14921: currcategories - reference to array of current categories assigned to the course
                   14922: 
1.1260    raeburn  14923: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14924:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14925: 
1.663     raeburn  14926: Returns: $output (markup to be displayed).
                   14927: 
                   14928: =cut
                   14929: 
                   14930: sub assign_category_rows {
1.1259    raeburn  14931:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14932:     my ($text,$name,$item,$chgstr);
                   14933:     if (ref($cats) eq 'ARRAY') {
                   14934:         my $maxdepth = scalar(@{$cats});
                   14935:         if (ref($cats->[$depth]) eq 'HASH') {
                   14936:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14937:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14938:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  14939:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14940:                 for (my $j=0; $j<$numchildren; $j++) {
                   14941:                     $name = $cats->[$depth]{$parent}[$j];
                   14942:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14943:                     my $deeper = $depth+1;
                   14944:                     my $checked = '';
                   14945:                     if (ref($currcategories) eq 'ARRAY') {
                   14946:                         if (@{$currcategories} > 0) {
                   14947:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14948:                                 $checked = ' checked="checked"';
1.663     raeburn  14949:                             }
                   14950:                         }
                   14951:                     }
1.664     raeburn  14952:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14953:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  14954:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14955:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14956:                              '</td><td>';
1.663     raeburn  14957:                     if (ref($path) eq 'ARRAY') {
                   14958:                         push(@{$path},$name);
1.1259    raeburn  14959:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14960:                         pop(@{$path});
                   14961:                     }
                   14962:                     $text .= '</td></tr>';
                   14963:                 }
                   14964:                 $text .= '</table></td>';
                   14965:             }
                   14966:         }
                   14967:     }
                   14968:     return $text;
                   14969: }
                   14970: 
1.1181    raeburn  14971: =pod
                   14972: 
                   14973: =back
                   14974: 
                   14975: =cut
                   14976: 
1.655     raeburn  14977: ############################################################
                   14978: ############################################################
                   14979: 
                   14980: 
1.443     albertel 14981: sub commit_customrole {
1.664     raeburn  14982:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14983:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14984:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14985:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14986:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14987:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14988:                  '</b><br />';
                   14989:     return $output;
                   14990: }
                   14991: 
                   14992: sub commit_standardrole {
1.1116    raeburn  14993:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14994:     my ($output,$logmsg,$linefeed);
                   14995:     if ($context eq 'auto') {
                   14996:         $linefeed = "\n";
                   14997:     } else {
                   14998:         $linefeed = "<br />\n";
                   14999:     }  
1.443     albertel 15000:     if ($three eq 'st') {
1.541     raeburn  15001:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15002:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15003:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15004:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15005:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15006:         } else {
1.541     raeburn  15007:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15008:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15009:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15010:             if ($context eq 'auto') {
                   15011:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15012:             } else {
                   15013:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15014:                &mt('Add to classlist').': <b>ok</b>';
                   15015:             }
                   15016:             $output .= $linefeed;
1.443     albertel 15017:         }
                   15018:     } else {
                   15019:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15020:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15021:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15022:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15023:         if ($context eq 'auto') {
                   15024:             $output .= $result.$linefeed;
                   15025:         } else {
                   15026:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15027:         }
1.443     albertel 15028:     }
                   15029:     return $output;
                   15030: }
                   15031: 
                   15032: sub commit_studentrole {
1.1116    raeburn  15033:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15034:         $credits) = @_;
1.626     raeburn  15035:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15036:     if ($context eq 'auto') {
                   15037:         $linefeed = "\n";
                   15038:     } else {
                   15039:         $linefeed = '<br />'."\n";
                   15040:     }
1.443     albertel 15041:     if (defined($one) && defined($two)) {
                   15042:         my $cid=$one.'_'.$two;
                   15043:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15044:         my $secchange = 0;
                   15045:         my $expire_role_result;
                   15046:         my $modify_section_result;
1.628     raeburn  15047:         if ($oldsec ne '-1') { 
                   15048:             if ($oldsec ne $sec) {
1.443     albertel 15049:                 $secchange = 1;
1.628     raeburn  15050:                 my $now = time;
1.443     albertel 15051:                 my $uurl='/'.$cid;
                   15052:                 $uurl=~s/\_/\//g;
                   15053:                 if ($oldsec) {
                   15054:                     $uurl.='/'.$oldsec;
                   15055:                 }
1.626     raeburn  15056:                 $oldsecurl = $uurl;
1.628     raeburn  15057:                 $expire_role_result = 
1.652     raeburn  15058:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15059:                 if ($env{'request.course.sec'} ne '') { 
                   15060:                     if ($expire_role_result eq 'refused') {
                   15061:                         my @roles = ('st');
                   15062:                         my @statuses = ('previous');
                   15063:                         my @roledoms = ($one);
                   15064:                         my $withsec = 1;
                   15065:                         my %roleshash = 
                   15066:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15067:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15068:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15069:                             my ($oldstart,$oldend) = 
                   15070:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15071:                             if ($oldend > 0 && $oldend <= $now) {
                   15072:                                 $expire_role_result = 'ok';
                   15073:                             }
                   15074:                         }
                   15075:                     }
                   15076:                 }
1.443     albertel 15077:                 $result = $expire_role_result;
                   15078:             }
                   15079:         }
                   15080:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  15081:             $modify_section_result = 
                   15082:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15083:                                                            undef,undef,undef,$sec,
                   15084:                                                            $end,$start,'','',$cid,
                   15085:                                                            '',$context,$credits);
1.443     albertel 15086:             if ($modify_section_result =~ /^ok/) {
                   15087:                 if ($secchange == 1) {
1.628     raeburn  15088:                     if ($sec eq '') {
                   15089:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15090:                     } else {
                   15091:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15092:                     }
1.443     albertel 15093:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15094:                     if ($sec eq '') {
                   15095:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15096:                     } else {
                   15097:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15098:                     }
1.443     albertel 15099:                 } else {
1.628     raeburn  15100:                     if ($sec eq '') {
                   15101:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15102:                     } else {
                   15103:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15104:                     }
1.443     albertel 15105:                 }
                   15106:             } else {
1.1115    raeburn  15107:                 if ($secchange) { 
1.628     raeburn  15108:                     $$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;
                   15109:                 } else {
                   15110:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15111:                 }
1.443     albertel 15112:             }
                   15113:             $result = $modify_section_result;
                   15114:         } elsif ($secchange == 1) {
1.628     raeburn  15115:             if ($oldsec eq '') {
1.1103    raeburn  15116:                 $$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  15117:             } else {
                   15118:                 $$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;
                   15119:             }
1.626     raeburn  15120:             if ($expire_role_result eq 'refused') {
                   15121:                 my $newsecurl = '/'.$cid;
                   15122:                 $newsecurl =~ s/\_/\//g;
                   15123:                 if ($sec ne '') {
                   15124:                     $newsecurl.='/'.$sec;
                   15125:                 }
                   15126:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15127:                     if ($sec eq '') {
                   15128:                         $$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;
                   15129:                     } else {
                   15130:                         $$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;
                   15131:                     }
                   15132:                 }
                   15133:             }
1.443     albertel 15134:         }
                   15135:     } else {
1.626     raeburn  15136:         $$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 15137:         $result = "error: incomplete course id\n";
                   15138:     }
                   15139:     return $result;
                   15140: }
                   15141: 
1.1108    raeburn  15142: sub show_role_extent {
                   15143:     my ($scope,$context,$role) = @_;
                   15144:     $scope =~ s{^/}{};
                   15145:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15146:     push(@courseroles,'co');
                   15147:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15148:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15149:         $scope =~ s{/}{_};
                   15150:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15151:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15152:         my ($audom,$auname) = split(/\//,$scope);
                   15153:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15154:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15155:     } else {
                   15156:         $scope =~ s{/$}{};
                   15157:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15158:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15159:     }
                   15160: }
                   15161: 
1.443     albertel 15162: ############################################################
                   15163: ############################################################
                   15164: 
1.566     albertel 15165: sub check_clone {
1.578     raeburn  15166:     my ($args,$linefeed) = @_;
1.566     albertel 15167:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15168:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15169:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15170:     my $clonemsg;
                   15171:     my $can_clone = 0;
1.944     raeburn  15172:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15173:     if ($lctype ne 'community') {
                   15174:         $lctype = 'course';
                   15175:     }
1.566     albertel 15176:     if ($clonehome eq 'no_host') {
1.944     raeburn  15177:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15178:             $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'});
                   15179:         } else {
                   15180:             $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'});
                   15181:         }     
1.566     albertel 15182:     } else {
                   15183: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15184:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15185:             if ($clonedesc{'type'} ne 'Community') {
1.1262    raeburn  15186:                 $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  15187:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15188:             }
                   15189:         }
1.1262    raeburn  15190: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15191:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15192: 	    $can_clone = 1;
                   15193: 	} else {
1.1221    raeburn  15194: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15195: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  15196:             if ($clonehash{'cloners'} eq '') {
                   15197:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15198:                 if ($domdefs{'canclone'}) {
                   15199:                     unless ($domdefs{'canclone'} eq 'none') {
                   15200:                         if ($domdefs{'canclone'} eq 'domain') {
                   15201:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15202:                                 $can_clone = 1;
                   15203:                             }
                   15204:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15205:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15206:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15207:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15208:                                 $can_clone = 1;
                   15209:                             }
                   15210:                         }
                   15211:                     }
                   15212:                 }
1.578     raeburn  15213:             } else {
1.1221    raeburn  15214: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15215:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15216:                     $can_clone = 1;
1.1221    raeburn  15217:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15218:                     $can_clone = 1;
1.1225    raeburn  15219:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15220:                     $can_clone = 1;
1.1221    raeburn  15221:                 }
                   15222:                 unless ($can_clone) {
1.1225    raeburn  15223:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15224:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  15225:                         my (%gotdomdefaults,%gotcodedefaults);
                   15226:                         foreach my $cloner (@cloners) {
                   15227:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15228:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15229:                                 my (%codedefaults,@code_order);
                   15230:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15231:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15232:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15233:                                     }
                   15234:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15235:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15236:                                     }
                   15237:                                 } else {
                   15238:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15239:                                                                             \%codedefaults,
                   15240:                                                                             \@code_order);
                   15241:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15242:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15243:                                 }
                   15244:                                 if (@code_order > 0) {
                   15245:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15246:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15247:                                                                                 $args->{'crscode'})) {
                   15248:                                         $can_clone = 1;
                   15249:                                         last;
                   15250:                                     }
                   15251:                                 }
                   15252:                             }
                   15253:                         }
                   15254:                     }
1.1225    raeburn  15255:                 }
                   15256:             }
                   15257:             unless ($can_clone) {
                   15258:                 my $ccrole = 'cc';
                   15259:                 if ($args->{'crstype'} eq 'Community') {
                   15260:                     $ccrole = 'co';
                   15261:                 }
                   15262: 	        my %roleshash =
                   15263: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15264: 					          $args->{'ccdomain'},
                   15265:                                                   'userroles',['active'],[$ccrole],
                   15266: 					          [$args->{'clonedomain'}]);
                   15267: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15268:                     $can_clone = 1;
                   15269:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15270:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15271:                     $can_clone = 1;
1.1221    raeburn  15272:                 }
                   15273:             }
                   15274:             unless ($can_clone) {
                   15275:                 if ($args->{'crstype'} eq 'Community') {
                   15276:                     $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  15277:                 } else {
1.1221    raeburn  15278:                     $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'});
                   15279:                 }
1.566     albertel 15280: 	    }
1.578     raeburn  15281:         }
1.566     albertel 15282:     }
                   15283:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15284: }
                   15285: 
1.444     albertel 15286: sub construct_course {
1.1262    raeburn  15287:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15288:         $cnum,$category,$coderef) = @_;
1.444     albertel 15289:     my $outcome;
1.541     raeburn  15290:     my $linefeed =  '<br />'."\n";
                   15291:     if ($context eq 'auto') {
                   15292:         $linefeed = "\n";
                   15293:     }
1.566     albertel 15294: 
                   15295: #
                   15296: # Are we cloning?
                   15297: #
                   15298:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15299:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15300: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15301: 	if ($context ne 'auto') {
1.578     raeburn  15302:             if ($clonemsg ne '') {
                   15303: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15304:             }
1.566     albertel 15305: 	}
                   15306: 	$outcome .= $clonemsg.$linefeed;
                   15307: 
                   15308:         if (!$can_clone) {
                   15309: 	    return (0,$outcome);
                   15310: 	}
                   15311:     }
                   15312: 
1.444     albertel 15313: #
                   15314: # Open course
                   15315: #
1.1239    raeburn  15316:     my $showncrstype;
                   15317:     if ($args->{'crstype'} eq 'Placement') {
                   15318:         $showncrstype = 'placement test'; 
                   15319:     } else {  
                   15320:         $showncrstype = lc($args->{'crstype'});
                   15321:     }
1.444     albertel 15322:     my %cenv=();
                   15323:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15324:                                              $args->{'cdescr'},
                   15325:                                              $args->{'curl'},
                   15326:                                              $args->{'course_home'},
                   15327:                                              $args->{'nonstandard'},
                   15328:                                              $args->{'crscode'},
                   15329:                                              $args->{'ccuname'}.':'.
                   15330:                                              $args->{'ccdomain'},
1.882     raeburn  15331:                                              $args->{'crstype'},
1.885     raeburn  15332:                                              $cnum,$context,$category);
1.444     albertel 15333: 
                   15334:     # Note: The testing routines depend on this being output; see 
                   15335:     # Utils::Course. This needs to at least be output as a comment
                   15336:     # if anyone ever decides to not show this, and Utils::Course::new
                   15337:     # will need to be suitably modified.
1.1239    raeburn  15338:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
1.943     raeburn  15339:     if ($$courseid =~ /^error:/) {
                   15340:         return (0,$outcome);
                   15341:     }
                   15342: 
1.444     albertel 15343: #
                   15344: # Check if created correctly
                   15345: #
1.479     albertel 15346:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15347:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15348:     if ($crsuhome eq 'no_host') {
                   15349:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15350:         return (0,$outcome);
                   15351:     }
1.541     raeburn  15352:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15353: 
1.444     albertel 15354: #
1.566     albertel 15355: # Do the cloning
                   15356: #   
                   15357:     if ($can_clone && $cloneid) {
1.1239    raeburn  15358: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
1.566     albertel 15359: 	if ($context ne 'auto') {
                   15360: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15361: 	}
                   15362: 	$outcome .= $clonemsg.$linefeed;
                   15363: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15364: # Copy all files
1.637     www      15365: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15366: # Restore URL
1.566     albertel 15367: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15368: # Restore title
1.566     albertel 15369: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15370: # Restore creation date, creator and creation context.
                   15371:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15372:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15373:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15374: # Mark as cloned
1.566     albertel 15375: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15376: # Need to clone grading mode
                   15377:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15378:         $cenv{'grading'}=$newenv{'grading'};
                   15379: # Do not clone these environment entries
                   15380:         &Apache::lonnet::del('environment',
                   15381:                   ['default_enrollment_start_date',
                   15382:                    'default_enrollment_end_date',
                   15383:                    'question.email',
                   15384:                    'policy.email',
                   15385:                    'comment.email',
                   15386:                    'pch.users.denied',
1.725     raeburn  15387:                    'plc.users.denied',
                   15388:                    'hidefromcat',
1.1121    raeburn  15389:                    'checkforpriv',
1.1166    raeburn  15390:                    'categories',
                   15391:                    'internal.uniquecode'],
1.638     www      15392:                    $$crsudom,$$crsunum);
1.1170    raeburn  15393:         if ($args->{'textbook'}) {
                   15394:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15395:         }
1.444     albertel 15396:     }
1.566     albertel 15397: 
1.444     albertel 15398: #
                   15399: # Set environment (will override cloned, if existing)
                   15400: #
                   15401:     my @sections = ();
                   15402:     my @xlists = ();
                   15403:     if ($args->{'crstype'}) {
                   15404:         $cenv{'type'}=$args->{'crstype'};
                   15405:     }
                   15406:     if ($args->{'crsid'}) {
                   15407:         $cenv{'courseid'}=$args->{'crsid'};
                   15408:     }
                   15409:     if ($args->{'crscode'}) {
                   15410:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15411:     }
                   15412:     if ($args->{'crsquota'} ne '') {
                   15413:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15414:     } else {
                   15415:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15416:     }
                   15417:     if ($args->{'ccuname'}) {
                   15418:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15419:                                         ':'.$args->{'ccdomain'};
                   15420:     } else {
                   15421:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15422:     }
1.1116    raeburn  15423:     if ($args->{'defaultcredits'}) {
                   15424:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15425:     }
1.444     albertel 15426:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15427:     if ($args->{'crssections'}) {
                   15428:         $cenv{'internal.sectionnums'} = '';
                   15429:         if ($args->{'crssections'} =~ m/,/) {
                   15430:             @sections = split/,/,$args->{'crssections'};
                   15431:         } else {
                   15432:             $sections[0] = $args->{'crssections'};
                   15433:         }
                   15434:         if (@sections > 0) {
                   15435:             foreach my $item (@sections) {
                   15436:                 my ($sec,$gp) = split/:/,$item;
                   15437:                 my $class = $args->{'crscode'}.$sec;
                   15438:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15439:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15440:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15441:                     push(@badclasses,$class);
1.444     albertel 15442:                 }
                   15443:             }
                   15444:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15445:         }
                   15446:     }
                   15447: # do not hide course coordinator from staff listing, 
                   15448: # even if privileged
                   15449:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  15450: # add course coordinator's domain to domains to check for privileged users
                   15451: # if different to course domain
                   15452:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15453:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15454:     }
1.444     albertel 15455: # add crosslistings
                   15456:     if ($args->{'crsxlist'}) {
                   15457:         $cenv{'internal.crosslistings'}='';
                   15458:         if ($args->{'crsxlist'} =~ m/,/) {
                   15459:             @xlists = split/,/,$args->{'crsxlist'};
                   15460:         } else {
                   15461:             $xlists[0] = $args->{'crsxlist'};
                   15462:         }
                   15463:         if (@xlists > 0) {
                   15464:             foreach my $item (@xlists) {
                   15465:                 my ($xl,$gp) = split/:/,$item;
                   15466:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15467:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15468:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15469:                     push(@badclasses,$xl);
1.444     albertel 15470:                 }
                   15471:             }
                   15472:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15473:         }
                   15474:     }
                   15475:     if ($args->{'autoadds'}) {
                   15476:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15477:     }
                   15478:     if ($args->{'autodrops'}) {
                   15479:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15480:     }
                   15481: # check for notification of enrollment changes
                   15482:     my @notified = ();
                   15483:     if ($args->{'notify_owner'}) {
                   15484:         if ($args->{'ccuname'} ne '') {
                   15485:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15486:         }
                   15487:     }
                   15488:     if ($args->{'notify_dc'}) {
                   15489:         if ($uname ne '') { 
1.630     raeburn  15490:             push(@notified,$uname.':'.$udom);
1.444     albertel 15491:         }
                   15492:     }
                   15493:     if (@notified > 0) {
                   15494:         my $notifylist;
                   15495:         if (@notified > 1) {
                   15496:             $notifylist = join(',',@notified);
                   15497:         } else {
                   15498:             $notifylist = $notified[0];
                   15499:         }
                   15500:         $cenv{'internal.notifylist'} = $notifylist;
                   15501:     }
                   15502:     if (@badclasses > 0) {
                   15503:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  15504:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15505:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15506:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15507:         );
1.1264    raeburn  15508:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15509:                            &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  15510:         if ($context eq 'auto') {
                   15511:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  15512:         } else {
1.566     albertel 15513:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  15514:         }
                   15515:         foreach my $item (@badclasses) {
1.541     raeburn  15516:             if ($context eq 'auto') {
1.1261    raeburn  15517:                 $outcome .= " - $item\n";
1.541     raeburn  15518:             } else {
1.1261    raeburn  15519:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15520:             }
1.1261    raeburn  15521:         }
                   15522:         if ($context eq 'auto') {
                   15523:             $outcome .= $linefeed;
                   15524:         } else {
                   15525:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  15526:         } 
1.444     albertel 15527:     }
                   15528:     if ($args->{'no_end_date'}) {
                   15529:         $args->{'endaccess'} = 0;
                   15530:     }
                   15531:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15532:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15533:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15534:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15535:     if ($args->{'showphotos'}) {
                   15536:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15537:     }
                   15538:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15539:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15540:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15541:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15542:             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'); 
                   15543:             if ($context eq 'auto') {
                   15544:                 $outcome .= $krb_msg;
                   15545:             } else {
1.566     albertel 15546:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15547:             }
                   15548:             $outcome .= $linefeed;
1.444     albertel 15549:         }
                   15550:     }
                   15551:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15552:        if ($args->{'setpolicy'}) {
                   15553:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15554:        }
                   15555:        if ($args->{'setcontent'}) {
                   15556:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15557:        }
1.1251    raeburn  15558:        if ($args->{'setcomment'}) {
                   15559:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15560:        }
1.444     albertel 15561:     }
                   15562:     if ($args->{'reshome'}) {
                   15563: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15564: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15565:     }
                   15566: #
                   15567: # course has keyed access
                   15568: #
                   15569:     if ($args->{'setkeys'}) {
                   15570:        $cenv{'keyaccess'}='yes';
                   15571:     }
                   15572: # if specified, key authority is not course, but user
                   15573: # only active if keyaccess is yes
                   15574:     if ($args->{'keyauth'}) {
1.487     albertel 15575: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15576: 	$user = &LONCAPA::clean_username($user);
                   15577: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15578: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15579: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15580: 	}
                   15581:     }
                   15582: 
1.1166    raeburn  15583: #
1.1167    raeburn  15584: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  15585: #
                   15586:     if ($args->{'uniquecode'}) {
                   15587:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15588:         if ($code) {
                   15589:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  15590:             my %crsinfo =
                   15591:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15592:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15593:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15594:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15595:             } 
1.1166    raeburn  15596:             if (ref($coderef)) {
                   15597:                 $$coderef = $code;
                   15598:             }
                   15599:         }
                   15600:     }
                   15601: 
1.444     albertel 15602:     if ($args->{'disresdis'}) {
                   15603:         $cenv{'pch.roles.denied'}='st';
                   15604:     }
                   15605:     if ($args->{'disablechat'}) {
                   15606:         $cenv{'plc.roles.denied'}='st';
                   15607:     }
                   15608: 
                   15609:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15610:     # course
                   15611:     $cenv{'course.helper.not.run'} = 1;
                   15612:     #
                   15613:     # Use new Randomseed
                   15614:     #
                   15615:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15616:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15617:     #
                   15618:     # The encryption code and receipt prefix for this course
                   15619:     #
                   15620:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15621:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15622:     #
                   15623:     # By default, use standard grading
                   15624:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15625: 
1.541     raeburn  15626:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15627:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15628: #
                   15629: # Open all assignments
                   15630: #
                   15631:     if ($args->{'openall'}) {
                   15632:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15633:        my %storecontent = ($storeunder         => time,
                   15634:                            $storeunder.'.type' => 'date_start');
                   15635:        
                   15636:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15637:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15638:    }
                   15639: #
                   15640: # Set first page
                   15641: #
                   15642:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15643: 	    || ($cloneid)) {
1.445     albertel 15644: 	use LONCAPA::map;
1.444     albertel 15645: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15646: 
                   15647: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15648:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15649: 
1.444     albertel 15650:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15651:         my $title; my $url;
                   15652:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15653: 	    $title=&mt('Syllabus');
1.444     albertel 15654:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15655:         } else {
1.963     raeburn  15656:             $title=&mt('Table of Contents');
1.444     albertel 15657:             $url='/adm/navmaps';
                   15658:         }
1.445     albertel 15659: 
                   15660:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15661: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15662: 
                   15663: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15664:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15665:     }
1.566     albertel 15666: 
1.1237    raeburn  15667: # 
                   15668: # Set params for Placement Tests
                   15669: #
1.1239    raeburn  15670:     if ($args->{'crstype'} eq 'Placement') {
                   15671:        my %storecontent; 
                   15672:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   15673:        my %defaults = (
                   15674:                         buttonshide   => { value => 'yes',
                   15675:                                            type => 'string_yesno',},
                   15676:                         type          => { value => 'randomizetry',
                   15677:                                            type  => 'string_questiontype',},
                   15678:                         maxtries      => { value => 1,
                   15679:                                            type => 'int_pos',},
                   15680:                         problemstatus => { value => 'no',
                   15681:                                            type  => 'string_problemstatus',},
                   15682:                       );
                   15683:        foreach my $key (keys(%defaults)) {
                   15684:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   15685:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   15686:        }
1.1237    raeburn  15687:        &Apache::lonnet::cput
                   15688:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   15689:     }
                   15690: 
1.566     albertel 15691:     return (1,$outcome);
1.444     albertel 15692: }
                   15693: 
1.1166    raeburn  15694: sub make_unique_code {
                   15695:     my ($cdom,$cnum) = @_;
                   15696:     # get lock on uniquecodes db
                   15697:     my $lockhash = {
                   15698:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15699:                                                   ':'.$env{'user.domain'},
                   15700:                    };
                   15701:     my $tries = 0;
                   15702:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15703:     my ($code,$error);
                   15704:   
                   15705:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15706:         $tries ++;
                   15707:         sleep 1;
                   15708:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15709:     }
                   15710:     if ($gotlock eq 'ok') {
                   15711:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15712:         my $gotcode;
                   15713:         my $attempts = 0;
                   15714:         while ((!$gotcode) && ($attempts < 100)) {
                   15715:             $code = &generate_code();
                   15716:             if (!exists($currcodes{$code})) {
                   15717:                 $gotcode = 1;
                   15718:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15719:                     $error = 'nostore';
                   15720:                 }
                   15721:             }
                   15722:             $attempts ++;
                   15723:         }
                   15724:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15725:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15726:     } else {
                   15727:         $error = 'nolock';
                   15728:     }
                   15729:     return ($code,$error);
                   15730: }
                   15731: 
                   15732: sub generate_code {
                   15733:     my $code;
                   15734:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15735:     for (my $i=0; $i<6; $i++) {
                   15736:         my $lettnum = int (rand 2);
                   15737:         my $item = '';
                   15738:         if ($lettnum) {
                   15739:             $item = $letts[int( rand(18) )];
                   15740:         } else {
                   15741:             $item = 1+int( rand(8) );
                   15742:         }
                   15743:         $code .= $item;
                   15744:     }
                   15745:     return $code;
                   15746: }
                   15747: 
1.444     albertel 15748: ############################################################
                   15749: ############################################################
                   15750: 
1.1237    raeburn  15751: # Community, Course and Placement Test
1.378     raeburn  15752: sub course_type {
                   15753:     my ($cid) = @_;
                   15754:     if (!defined($cid)) {
                   15755:         $cid = $env{'request.course.id'};
                   15756:     }
1.404     albertel 15757:     if (defined($env{'course.'.$cid.'.type'})) {
                   15758:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15759:     } else {
                   15760:         return 'Course';
1.377     raeburn  15761:     }
                   15762: }
1.156     albertel 15763: 
1.406     raeburn  15764: sub group_term {
                   15765:     my $crstype = &course_type();
                   15766:     my %names = (
                   15767:                   'Course' => 'group',
1.865     raeburn  15768:                   'Community' => 'group',
1.1237    raeburn  15769:                   'Placement' => 'group',
1.406     raeburn  15770:                 );
                   15771:     return $names{$crstype};
                   15772: }
                   15773: 
1.902     raeburn  15774: sub course_types {
1.1237    raeburn  15775:     my @types = ('official','unofficial','community','textbook','placement');
1.902     raeburn  15776:     my %typename = (
                   15777:                          official   => 'Official course',
                   15778:                          unofficial => 'Unofficial course',
                   15779:                          community  => 'Community',
1.1165    raeburn  15780:                          textbook   => 'Textbook course',
1.1237    raeburn  15781:                          placement  => 'Placement test',
1.902     raeburn  15782:                    );
                   15783:     return (\@types,\%typename);
                   15784: }
                   15785: 
1.156     albertel 15786: sub icon {
                   15787:     my ($file)=@_;
1.505     albertel 15788:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15789:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15790:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15791:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15792: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15793: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15794: 	            $curfext.".gif") {
                   15795: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15796: 		$curfext.".gif";
                   15797: 	}
                   15798:     }
1.249     albertel 15799:     return &lonhttpdurl($iconname);
1.154     albertel 15800: } 
1.84      albertel 15801: 
1.575     albertel 15802: sub lonhttpdurl {
1.692     www      15803: #
                   15804: # Had been used for "small fry" static images on separate port 8080.
                   15805: # Modify here if lightweight http functionality desired again.
                   15806: # Currently eliminated due to increasing firewall issues.
                   15807: #
1.575     albertel 15808:     my ($url)=@_;
1.692     www      15809:     return $url;
1.215     albertel 15810: }
                   15811: 
1.213     albertel 15812: sub connection_aborted {
                   15813:     my ($r)=@_;
                   15814:     $r->print(" ");$r->rflush();
                   15815:     my $c = $r->connection;
                   15816:     return $c->aborted();
                   15817: }
                   15818: 
1.221     foxr     15819: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15820: #    strings as 'strings'.
                   15821: sub escape_single {
1.221     foxr     15822:     my ($input) = @_;
1.223     albertel 15823:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15824:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15825:     return $input;
                   15826: }
1.223     albertel 15827: 
1.222     foxr     15828: #  Same as escape_single, but escape's "'s  This 
                   15829: #  can be used for  "strings"
                   15830: sub escape_double {
                   15831:     my ($input) = @_;
                   15832:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15833:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15834:     return $input;
                   15835: }
1.223     albertel 15836:  
1.222     foxr     15837: #   Escapes the last element of a full URL.
                   15838: sub escape_url {
                   15839:     my ($url)   = @_;
1.238     raeburn  15840:     my @urlslices = split(/\//, $url,-1);
1.369     www      15841:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  15842:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15843: }
1.462     albertel 15844: 
1.820     raeburn  15845: sub compare_arrays {
                   15846:     my ($arrayref1,$arrayref2) = @_;
                   15847:     my (@difference,%count);
                   15848:     @difference = ();
                   15849:     %count = ();
                   15850:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15851:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15852:         foreach my $element (keys(%count)) {
                   15853:             if ($count{$element} == 1) {
                   15854:                 push(@difference,$element);
                   15855:             }
                   15856:         }
                   15857:     }
                   15858:     return @difference;
                   15859: }
                   15860: 
1.817     bisitz   15861: # -------------------------------------------------------- Initialize user login
1.462     albertel 15862: sub init_user_environment {
1.463     albertel 15863:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15864:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15865: 
                   15866:     my $public=($username eq 'public' && $domain eq 'public');
                   15867: 
                   15868: # See if old ID present, if so, remove
                   15869: 
1.1062    raeburn  15870:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15871:     my $now=time;
                   15872: 
                   15873:     if ($public) {
                   15874: 	my $max_public=100;
                   15875: 	my $oldest;
                   15876: 	my $oldest_time=0;
                   15877: 	for(my $next=1;$next<=$max_public;$next++) {
                   15878: 	    if (-e $lonids."/publicuser_$next.id") {
                   15879: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15880: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15881: 		    $oldest_time=$mtime;
                   15882: 		    $oldest=$next;
                   15883: 		}
                   15884: 	    } else {
                   15885: 		$cookie="publicuser_$next";
                   15886: 		last;
                   15887: 	    }
                   15888: 	}
                   15889: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15890:     } else {
1.463     albertel 15891: 	# if this isn't a robot, kill any existing non-robot sessions
                   15892: 	if (!$args->{'robot'}) {
                   15893: 	    opendir(DIR,$lonids);
                   15894: 	    while ($filename=readdir(DIR)) {
                   15895: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   15896: 		    unlink($lonids.'/'.$filename);
                   15897: 		}
1.462     albertel 15898: 	    }
1.463     albertel 15899: 	    closedir(DIR);
1.1204    raeburn  15900: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15901:             my $namespace = 'nohist_courseeditor';
                   15902:             my $lockingkey = 'paste'."\0".'locked_num';
                   15903:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15904:                                                 $domain,$username);
                   15905:             if (exists($lockhash{$lockingkey})) {
                   15906:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15907:                 unless ($delresult eq 'ok') {
                   15908:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15909:                 }
                   15910:             }
1.462     albertel 15911: 	}
                   15912: # Give them a new cookie
1.463     albertel 15913: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15914: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15915: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15916:     
                   15917: # Initialize roles
                   15918: 
1.1062    raeburn  15919: 	($userroles,$firstaccenv,$timerintenv) = 
                   15920:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15921:     }
                   15922: # ------------------------------------ Check browser type and MathML capability
                   15923: 
1.1194    raeburn  15924:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15925:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15926: 
                   15927: # ------------------------------------------------------------- Get environment
                   15928: 
                   15929:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15930:     my ($tmp) = keys(%userenv);
                   15931:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15932:     } else {
                   15933: 	undef(%userenv);
                   15934:     }
                   15935:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15936: 	$form->{'interface'}=$userenv{'interface'};
                   15937:     }
                   15938:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15939: 
                   15940: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15941:     foreach my $option ('interface','localpath','localres') {
                   15942:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15943:     }
                   15944: # --------------------------------------------------------- Write first profile
                   15945: 
                   15946:     {
                   15947: 	my %initial_env = 
                   15948: 	    ("user.name"          => $username,
                   15949: 	     "user.domain"        => $domain,
                   15950: 	     "user.home"          => $authhost,
                   15951: 	     "browser.type"       => $clientbrowser,
                   15952: 	     "browser.version"    => $clientversion,
                   15953: 	     "browser.mathml"     => $clientmathml,
                   15954: 	     "browser.unicode"    => $clientunicode,
                   15955: 	     "browser.os"         => $clientos,
1.1137    raeburn  15956:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  15957:              "browser.info"       => $clientinfo,
1.1194    raeburn  15958:              "browser.osversion"  => $clientosversion,
1.462     albertel 15959: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15960: 	     "request.course.fn"  => '',
                   15961: 	     "request.course.uri" => '',
                   15962: 	     "request.course.sec" => '',
                   15963: 	     "request.role"       => 'cm',
                   15964: 	     "request.role.adv"   => $env{'user.adv'},
                   15965: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15966: 
                   15967:         if ($form->{'localpath'}) {
                   15968: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15969: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15970:         }
                   15971: 	
                   15972: 	if ($form->{'interface'}) {
                   15973: 	    $form->{'interface'}=~s/\W//gs;
                   15974: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15975: 	    $env{'browser.interface'}=$form->{'interface'};
                   15976: 	}
                   15977: 
1.1157    raeburn  15978:         if ($form->{'iptoken'}) {
                   15979:             my $lonhost = $r->dir_config('lonHostID');
                   15980:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15981:             $env{'user.noloadbalance'} = $lonhost;
                   15982:         }
                   15983: 
1.981     raeburn  15984:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  15985:         my %domdef;
                   15986:         unless ($domain eq 'public') {
                   15987:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   15988:         }
1.980     raeburn  15989: 
1.1081    raeburn  15990:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  15991:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  15992:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15993:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  15994:         }
                   15995: 
1.1237    raeburn  15996:         foreach my $crstype ('official','unofficial','community','textbook','placement') {
1.765     raeburn  15997:             $userenv{'canrequest.'.$crstype} =
                   15998:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  15999:                                                   'reload','requestcourses',
                   16000:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  16001:         }
                   16002: 
1.1092    raeburn  16003:         $userenv{'canrequest.author'} =
                   16004:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16005:                                         'reload','requestauthor',
                   16006:                                         \%userenv,\%domdef,\%is_adv);
                   16007:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16008:                                              $domain,$username);
                   16009:         my $reqstatus = $reqauthor{'author_status'};
                   16010:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   16011:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   16012:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16013:                                                   $reqauthor{'author'}{'timestamp'};
                   16014:             }
                   16015:         }
                   16016: 
1.462     albertel 16017: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16018: 
1.462     albertel 16019: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16020: 		 &GDBM_WRCREAT(),0640)) {
                   16021: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16022: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16023: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16024:             if (ref($firstaccenv) eq 'HASH') {
                   16025:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16026:             }
                   16027:             if (ref($timerintenv) eq 'HASH') {
                   16028:                 &_add_to_env(\%disk_env,$timerintenv);
                   16029:             }
1.463     albertel 16030: 	    if (ref($args->{'extra_env'})) {
                   16031: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16032: 	    }
1.462     albertel 16033: 	    untie(%disk_env);
                   16034: 	} else {
1.705     tempelho 16035: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16036: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16037: 	    return 'error: '.$!;
                   16038: 	}
                   16039:     }
                   16040:     $env{'request.role'}='cm';
                   16041:     $env{'request.role.adv'}=$env{'user.adv'};
                   16042:     $env{'browser.type'}=$clientbrowser;
                   16043: 
                   16044:     return $cookie;
                   16045: 
                   16046: }
                   16047: 
                   16048: sub _add_to_env {
                   16049:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16050:     if (ref($env_data) eq 'HASH') {
                   16051:         while (my ($key,$value) = each(%$env_data)) {
                   16052: 	    $idf->{$prefix.$key} = $value;
                   16053: 	    $env{$prefix.$key}   = $value;
                   16054:         }
1.462     albertel 16055:     }
                   16056: }
                   16057: 
1.685     tempelho 16058: # --- Get the symbolic name of a problem and the url
                   16059: sub get_symb {
                   16060:     my ($request,$silent) = @_;
1.726     raeburn  16061:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16062:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16063:     if ($symb eq '') {
                   16064:         if (!$silent) {
1.1071    raeburn  16065:             if (ref($request)) { 
                   16066:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16067:             }
1.685     tempelho 16068:             return ();
                   16069:         }
                   16070:     }
                   16071:     &Apache::lonenc::check_decrypt(\$symb);
                   16072:     return ($symb);
                   16073: }
                   16074: 
                   16075: # --------------------------------------------------------------Get annotation
                   16076: 
                   16077: sub get_annotation {
                   16078:     my ($symb,$enc) = @_;
                   16079: 
                   16080:     my $key = $symb;
                   16081:     if (!$enc) {
                   16082:         $key =
                   16083:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16084:     }
                   16085:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16086:     return $annotation{$key};
                   16087: }
                   16088: 
                   16089: sub clean_symb {
1.731     raeburn  16090:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16091: 
                   16092:     &Apache::lonenc::check_decrypt(\$symb);
                   16093:     my $enc = $env{'request.enc'};
1.731     raeburn  16094:     if ($delete_enc) {
1.730     raeburn  16095:         delete($env{'request.enc'});
                   16096:     }
1.685     tempelho 16097: 
                   16098:     return ($symb,$enc);
                   16099: }
1.462     albertel 16100: 
1.1181    raeburn  16101: ############################################################
                   16102: ############################################################
                   16103: 
                   16104: =pod
                   16105: 
                   16106: =head1 Routines for building display used to search for courses
                   16107: 
                   16108: 
                   16109: =over 4
                   16110: 
                   16111: =item * &build_filters()
                   16112: 
                   16113: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  16114: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16115: and quotacheck.pl
                   16116: 
1.1181    raeburn  16117: 
                   16118: Inputs:
                   16119: 
                   16120: filterlist - anonymous array of fields to include as potential filters 
                   16121: 
                   16122: crstype - course type
                   16123: 
                   16124: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16125:               to pop-open a course selector (will contain "extra element"). 
                   16126: 
                   16127: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16128: 
                   16129: filter - anonymous hash of criteria and their values
                   16130: 
                   16131: action - form action
                   16132: 
                   16133: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16134: 
1.1182    raeburn  16135: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  16136: 
                   16137: cloneruname - username of owner of new course who wants to clone
                   16138: 
                   16139: clonerudom - domain of owner of new course who wants to clone
                   16140: 
                   16141: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   16142: 
                   16143: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16144: 
                   16145: codedom - domain
                   16146: 
                   16147: formname - value of form element named "form". 
                   16148: 
                   16149: fixeddom - domain, if fixed.
                   16150: 
                   16151: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   16152: 
                   16153: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   16154: 
                   16155: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16156: 
                   16157: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16158: 
                   16159: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16160: 
                   16161: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16162: 
                   16163: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16164: 
1.1182    raeburn  16165: 
1.1181    raeburn  16166: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16167: 
1.1182    raeburn  16168: 
1.1181    raeburn  16169: Side Effects: None
                   16170: 
                   16171: =cut
                   16172: 
                   16173: # ---------------------------------------------- search for courses based on last activity etc.
                   16174: 
                   16175: sub build_filters {
                   16176:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16177:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16178:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16179:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16180:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  16181:     my ($list,$jscript);
1.1181    raeburn  16182:     my $onchange = 'javascript:updateFilters(this)';
                   16183:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16184:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16185:         $typeselectform,$instcodetitle);
                   16186:     if ($formname eq '') {
                   16187:         $formname = $caller;
                   16188:     }
                   16189:     foreach my $item (@{$filterlist}) {
                   16190:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16191:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16192:             if ($item eq 'domainfilter') {
                   16193:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16194:             } elsif ($item eq 'coursefilter') {
                   16195:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16196:             } elsif ($item eq 'ownerfilter') {
                   16197:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16198:             } elsif ($item eq 'ownerdomfilter') {
                   16199:                 $filter->{'ownerdomfilter'} =
                   16200:                     &LONCAPA::clean_domain($filter->{$item});
                   16201:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16202:                                                        'ownerdomfilter',1);
                   16203:             } elsif ($item eq 'personfilter') {
                   16204:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16205:             } elsif ($item eq 'persondomfilter') {
                   16206:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16207:                                                         'persondomfilter',1);
                   16208:             } else {
                   16209:                 $filter->{$item} =~ s/\W//g;
                   16210:             }
                   16211:             if (!$filter->{$item}) {
                   16212:                 $filter->{$item} = '';
                   16213:             }
                   16214:         }
                   16215:         if ($item eq 'domainfilter') {
                   16216:             my $allow_blank = 1;
                   16217:             if ($formname eq 'portform') {
                   16218:                 $allow_blank=0;
                   16219:             } elsif ($formname eq 'studentform') {
                   16220:                 $allow_blank=0;
                   16221:             }
                   16222:             if ($fixeddom) {
                   16223:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16224:                                     ' value="'.$codedom.'" />'.
                   16225:                                     &Apache::lonnet::domain($codedom,'description');
                   16226:             } else {
                   16227:                 $domainselectform = &select_dom_form($filter->{$item},
                   16228:                                                      'domainfilter',
                   16229:                                                       $allow_blank,'',$onchange);
                   16230:             }
                   16231:         } else {
                   16232:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16233:         }
                   16234:     }
                   16235: 
                   16236:     # last course activity filter and selection
                   16237:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16238: 
                   16239:     # course created filter and selection
                   16240:     if (exists($filter->{'createdfilter'})) {
                   16241:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16242:     }
                   16243: 
1.1239    raeburn  16244:     my $prefix = $crstype;
                   16245:     if ($crstype eq 'Placement') {
                   16246:         $prefix = 'Placement Test'
                   16247:     }
1.1181    raeburn  16248:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  16249:                 'cac' => "$prefix Activity",
                   16250:                 'ccr' => "$prefix Created",
                   16251:                 'cde' => "$prefix Title",
                   16252:                 'cdo' => "$prefix Domain",
1.1181    raeburn  16253:                 'ins' => 'Institutional Code',
                   16254:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  16255:                 'cow' => "$prefix Owner/Co-owner",
                   16256:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  16257:                 'cog' => 'Type',
                   16258:              );
                   16259: 
                   16260:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16261:         my $typeval = 'Course';
                   16262:         if ($crstype eq 'Community') {
                   16263:             $typeval = 'Community';
1.1239    raeburn  16264:         } elsif ($crstype eq 'Placement') {
                   16265:             $typeval = 'Placement';
1.1181    raeburn  16266:         }
                   16267:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16268:     } else {
                   16269:         $typeselectform =  '<select name="type" size="1"';
                   16270:         if ($onchange) {
                   16271:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16272:         }
                   16273:         $typeselectform .= '>'."\n";
1.1237    raeburn  16274:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  16275:             my $shown;
                   16276:             if ($posstype eq 'Placement') {
                   16277:                 $shown = &mt('Placement Test');
                   16278:             } else {
                   16279:                 $shown = &mt($posstype);
                   16280:             }
1.1181    raeburn  16281:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  16282:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  16283:         }
                   16284:         $typeselectform.="</select>";
                   16285:     }
                   16286: 
                   16287:     my ($cloneableonlyform,$cloneabletitle);
                   16288:     if (exists($filter->{'cloneableonly'})) {
                   16289:         my $cloneableon = '';
                   16290:         my $cloneableoff = ' checked="checked"';
                   16291:         if ($filter->{'cloneableonly'}) {
                   16292:             $cloneableon = $cloneableoff;
                   16293:             $cloneableoff = '';
                   16294:         }
                   16295:         $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>';
                   16296:         if ($formname eq 'ccrs') {
1.1187    bisitz   16297:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  16298:         } else {
                   16299:             $cloneabletitle = &mt('Cloneable by you');
                   16300:         }
                   16301:     }
                   16302:     my $officialjs;
                   16303:     if ($crstype eq 'Course') {
                   16304:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  16305: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16306: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16307:             if ($codedom) { 
1.1181    raeburn  16308:                 $officialjs = 1;
                   16309:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16310:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16311:                                                                   $officialjs,$codetitlesref);
                   16312:                 if ($jscript) {
1.1182    raeburn  16313:                     $jscript = '<script type="text/javascript">'."\n".
                   16314:                                '// <![CDATA['."\n".
                   16315:                                $jscript."\n".
                   16316:                                '// ]]>'."\n".
                   16317:                                '</script>'."\n";
1.1181    raeburn  16318:                 }
                   16319:             }
                   16320:             if ($instcodeform eq '') {
                   16321:                 $instcodeform =
                   16322:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16323:                     $list->{'instcodefilter'}.'" />';
                   16324:                 $instcodetitle = $lt{'ins'};
                   16325:             } else {
                   16326:                 $instcodetitle = $lt{'inc'};
                   16327:             }
                   16328:             if ($fixeddom) {
                   16329:                 $instcodetitle .= '<br />('.$codedom.')';
                   16330:             }
                   16331:         }
                   16332:     }
                   16333:     my $output = qq|
                   16334: <form method="post" name="filterpicker" action="$action">
                   16335: <input type="hidden" name="form" value="$formname" />
                   16336: |;
                   16337:     if ($formname eq 'modifycourse') {
                   16338:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16339:                    '<input type="hidden" name="prevphase" value="'.
                   16340:                    $prevphase.'" />'."\n";
1.1198    musolffc 16341:     } elsif ($formname eq 'quotacheck') {
                   16342:         $output .= qq|
                   16343: <input type="hidden" name="sortby" value="" />
                   16344: <input type="hidden" name="sortorder" value="" />
                   16345: |;
                   16346:     } else {
1.1181    raeburn  16347:         my $name_input;
                   16348:         if ($cnameelement ne '') {
                   16349:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16350:                           $cnameelement.'" />';
                   16351:         }
                   16352:         $output .= qq|
1.1182    raeburn  16353: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16354: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  16355: $name_input
                   16356: $roleelement
                   16357: $multelement
                   16358: $typeelement
                   16359: |;
                   16360:         if ($formname eq 'portform') {
                   16361:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16362:         }
                   16363:     }
                   16364:     if ($fixeddom) {
                   16365:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16366:     }
                   16367:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16368:     if ($sincefilterform) {
                   16369:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16370:                   .$sincefilterform
                   16371:                   .&Apache::lonhtmlcommon::row_closure();
                   16372:     }
                   16373:     if ($createdfilterform) {
                   16374:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16375:                   .$createdfilterform
                   16376:                   .&Apache::lonhtmlcommon::row_closure();
                   16377:     }
                   16378:     if ($domainselectform) {
                   16379:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16380:                   .$domainselectform
                   16381:                   .&Apache::lonhtmlcommon::row_closure();
                   16382:     }
                   16383:     if ($typeselectform) {
                   16384:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16385:             $output .= $typeselectform;
                   16386:         } else {
                   16387:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16388:                       .$typeselectform
                   16389:                       .&Apache::lonhtmlcommon::row_closure();
                   16390:         }
                   16391:     }
                   16392:     if ($instcodeform) {
                   16393:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16394:                   .$instcodeform
                   16395:                   .&Apache::lonhtmlcommon::row_closure();
                   16396:     }
                   16397:     if (exists($filter->{'ownerfilter'})) {
                   16398:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16399:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16400:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16401:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16402:                    $ownerdomselectform.'</td></tr></table>'.
                   16403:                    &Apache::lonhtmlcommon::row_closure();
                   16404:     }
                   16405:     if (exists($filter->{'personfilter'})) {
                   16406:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16407:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16408:                    '<input type="text" name="personfilter" size="20" value="'.
                   16409:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16410:                    $persondomselectform.'</td></tr></table>'.
                   16411:                    &Apache::lonhtmlcommon::row_closure();
                   16412:     }
                   16413:     if (exists($filter->{'coursefilter'})) {
                   16414:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16415:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16416:                   .$list->{'coursefilter'}.'" />'
                   16417:                   .&Apache::lonhtmlcommon::row_closure();
                   16418:     }
                   16419:     if ($cloneableonlyform) {
                   16420:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16421:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16422:     }
                   16423:     if (exists($filter->{'descriptfilter'})) {
                   16424:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16425:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16426:                   .$list->{'descriptfilter'}.'" />'
                   16427:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16428:     }
                   16429:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16430:                '<input type="hidden" name="updater" value="" />'."\n".
                   16431:                '<input type="submit" name="gosearch" value="'.
                   16432:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16433:     return $jscript.$clonewarning.$output;
                   16434: }
                   16435: 
                   16436: =pod 
                   16437: 
                   16438: =item * &timebased_select_form()
                   16439: 
1.1182    raeburn  16440: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  16441: filter e.g., Course Activity, Course Created, when searching for courses
                   16442: or communities
                   16443: 
                   16444: Inputs:
                   16445: 
                   16446: item - name of form element (sincefilter or createdfilter)
                   16447: 
                   16448: filter - anonymous hash of criteria and their values
                   16449: 
                   16450: Returns: HTML for a select box contained a blank, then six time selections,
                   16451:          with value set in incoming form variables currently selected. 
                   16452: 
                   16453: Side Effects: None
                   16454: 
                   16455: =cut
                   16456: 
                   16457: sub timebased_select_form {
                   16458:     my ($item,$filter) = @_;
                   16459:     if (ref($filter) eq 'HASH') {
                   16460:         $filter->{$item} =~ s/[^\d-]//g;
                   16461:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16462:         return &select_form(
                   16463:                             $filter->{$item},
                   16464:                             $item,
                   16465:                             {      '-1' => '',
                   16466:                                 '86400' => &mt('today'),
                   16467:                                '604800' => &mt('last week'),
                   16468:                               '2592000' => &mt('last month'),
                   16469:                               '7776000' => &mt('last three months'),
                   16470:                              '15552000' => &mt('last six months'),
                   16471:                              '31104000' => &mt('last year'),
                   16472:                     'select_form_order' =>
                   16473:                            ['-1','86400','604800','2592000','7776000',
                   16474:                             '15552000','31104000']});
                   16475:     }
                   16476: }
                   16477: 
                   16478: =pod
                   16479: 
                   16480: =item * &js_changer()
                   16481: 
                   16482: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  16483: when course type or domain is changed, and also to hide 'Searching ...' on
                   16484: page load completion for page showing search result.
1.1181    raeburn  16485: 
                   16486: Inputs: None
                   16487: 
1.1183    raeburn  16488: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  16489: 
                   16490: Side Effects: None
                   16491: 
                   16492: =cut
                   16493: 
                   16494: sub js_changer {
                   16495:     return <<ENDJS;
                   16496: <script type="text/javascript">
                   16497: // <![CDATA[
                   16498: function updateFilters(caller) {
                   16499:     if (typeof(caller) != "undefined") {
                   16500:         document.filterpicker.updater.value = caller.name;
                   16501:     }
                   16502:     document.filterpicker.submit();
                   16503: }
1.1183    raeburn  16504: 
                   16505: function hideSearching() {
                   16506:     if (document.getElementById('searching')) {
                   16507:         document.getElementById('searching').style.display = 'none';
                   16508:     }
                   16509:     return;
                   16510: }
                   16511: 
1.1181    raeburn  16512: // ]]>
                   16513: </script>
                   16514: 
                   16515: ENDJS
                   16516: }
                   16517: 
                   16518: =pod
                   16519: 
1.1182    raeburn  16520: =item * &search_courses()
                   16521: 
                   16522: Process selected filters form course search form and pass to lonnet::courseiddump
                   16523: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16524: 
                   16525: Inputs:
                   16526: 
                   16527: dom - domain being searched 
                   16528: 
                   16529: type - course type ('Course' or 'Community' or '.' if any).
                   16530: 
                   16531: filter - anonymous hash of criteria and their values
                   16532: 
                   16533: numtitles - for institutional codes - number of categories
                   16534: 
                   16535: cloneruname - optional username of new course owner
                   16536: 
                   16537: clonerudom - optional domain of new course owner
                   16538: 
1.1221    raeburn  16539: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  16540:             (used when DC is using course creation form)
                   16541: 
                   16542: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16543: 
1.1221    raeburn  16544: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16545:            (and so can clone automatically)
                   16546: 
                   16547: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16548: 
                   16549: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   16550:               courses to clone 
1.1182    raeburn  16551: 
                   16552: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16553: 
                   16554: 
                   16555: Side Effects: None
                   16556: 
                   16557: =cut
                   16558: 
                   16559: 
                   16560: sub search_courses {
1.1221    raeburn  16561:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16562:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  16563:     my (%courses,%showcourses,$cloner);
                   16564:     if (($filter->{'ownerfilter'} ne '') ||
                   16565:         ($filter->{'ownerdomfilter'} ne '')) {
                   16566:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16567:                                        $filter->{'ownerdomfilter'};
                   16568:     }
                   16569:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16570:         if (!$filter->{$item}) {
                   16571:             $filter->{$item}='.';
                   16572:         }
                   16573:     }
                   16574:     my $now = time;
                   16575:     my $timefilter =
                   16576:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16577:     my ($createdbefore,$createdafter);
                   16578:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16579:         $createdbefore = $now;
                   16580:         $createdafter = $now-$filter->{'createdfilter'};
                   16581:     }
                   16582:     my ($instcodefilter,$regexpok);
                   16583:     if ($numtitles) {
                   16584:         if ($env{'form.official'} eq 'on') {
                   16585:             $instcodefilter =
                   16586:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16587:             $regexpok = 1;
                   16588:         } elsif ($env{'form.official'} eq 'off') {
                   16589:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16590:             unless ($instcodefilter eq '') {
                   16591:                 $regexpok = -1;
                   16592:             }
                   16593:         }
                   16594:     } else {
                   16595:         $instcodefilter = $filter->{'instcodefilter'};
                   16596:     }
                   16597:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16598:     if ($type eq '') { $type = '.'; }
                   16599: 
                   16600:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16601:         $cloner = $cloneruname.':'.$clonerudom;
                   16602:     }
                   16603:     %courses = &Apache::lonnet::courseiddump($dom,
                   16604:                                              $filter->{'descriptfilter'},
                   16605:                                              $timefilter,
                   16606:                                              $instcodefilter,
                   16607:                                              $filter->{'combownerfilter'},
                   16608:                                              $filter->{'coursefilter'},
                   16609:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  16610:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  16611:                                              $filter->{'cloneableonly'},
                   16612:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  16613:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  16614:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16615:         my $ccrole;
                   16616:         if ($type eq 'Community') {
                   16617:             $ccrole = 'co';
                   16618:         } else {
                   16619:             $ccrole = 'cc';
                   16620:         }
                   16621:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16622:                                                      $filter->{'persondomfilter'},
                   16623:                                                      'userroles',undef,
                   16624:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16625:                                                      $dom);
                   16626:         foreach my $role (keys(%rolehash)) {
                   16627:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16628:             my $cid = $cdom.'_'.$cnum;
                   16629:             if (exists($courses{$cid})) {
                   16630:                 if (ref($courses{$cid}) eq 'HASH') {
                   16631:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16632:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  16633:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  16634:                         }
                   16635:                     } else {
                   16636:                         $courses{$cid}{roles} = [$courserole];
                   16637:                     }
                   16638:                     $showcourses{$cid} = $courses{$cid};
                   16639:                 }
                   16640:             }
                   16641:         }
                   16642:         %courses = %showcourses;
                   16643:     }
                   16644:     return %courses;
                   16645: }
                   16646: 
                   16647: =pod
                   16648: 
1.1181    raeburn  16649: =back
                   16650: 
1.1207    raeburn  16651: =head1 Routines for version requirements for current course.
                   16652: 
                   16653: =over 4
                   16654: 
                   16655: =item * &check_release_required()
                   16656: 
                   16657: Compares required LON-CAPA version with version on server, and
                   16658: if required version is newer looks for a server with the required version.
                   16659: 
                   16660: Looks first at servers in user's owen domain; if none suitable, looks at
                   16661: servers in course's domain are permitted to host sessions for user's domain.
                   16662: 
                   16663: Inputs:
                   16664: 
                   16665: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16666: 
                   16667: $courseid - Course ID of current course
                   16668: 
                   16669: $rolecode - User's current role in course (for switchserver query string).
                   16670: 
                   16671: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16672: 
                   16673: 
                   16674: Returns:
                   16675: 
                   16676: $switchserver - query string tp append to /adm/switchserver call (if 
                   16677:                 current server's LON-CAPA version is too old. 
                   16678: 
                   16679: $warning - Message is displayed if no suitable server could be found.
                   16680: 
                   16681: =cut
                   16682: 
                   16683: sub check_release_required {
                   16684:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16685:     my ($switchserver,$warning);
                   16686:     if ($required ne '') {
                   16687:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16688:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16689:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16690:             my $otherserver;
                   16691:             if (($major eq '' && $minor eq '') ||
                   16692:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16693:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16694:                 my $switchlcrev =
                   16695:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16696:                                                            $userdomserver);
                   16697:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16698:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16699:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16700:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16701:                     if ($cdom ne $env{'user.domain'}) {
                   16702:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16703:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16704:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16705:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16706:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16707:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16708:                         my $canhost =
                   16709:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16710:                                                               $coursedomserver,
                   16711:                                                               $remoterev,
                   16712:                                                               $udomdefaults{'remotesessions'},
                   16713:                                                               $defdomdefaults{'hostedsessions'});
                   16714: 
                   16715:                         if ($canhost) {
                   16716:                             $otherserver = $coursedomserver;
                   16717:                         } else {
                   16718:                             $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.");
                   16719:                         }
                   16720:                     } else {
                   16721:                         $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).");
                   16722:                     }
                   16723:                 } else {
                   16724:                     $otherserver = $userdomserver;
                   16725:                 }
                   16726:             }
                   16727:             if ($otherserver ne '') {
                   16728:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16729:             }
                   16730:         }
                   16731:     }
                   16732:     return ($switchserver,$warning);
                   16733: }
                   16734: 
                   16735: =pod
                   16736: 
                   16737: =item * &check_release_result()
                   16738: 
                   16739: Inputs:
                   16740: 
                   16741: $switchwarning - Warning message if no suitable server found to host session.
                   16742: 
                   16743: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16744:                 and current role.
                   16745: 
                   16746: Returns: HTML to display with information about requirement to switch server.
                   16747:          Either displaying warning with link to Roles/Courses screen or
                   16748:          display link to switchserver.
                   16749: 
1.1181    raeburn  16750: =cut
                   16751: 
1.1207    raeburn  16752: sub check_release_result {
                   16753:     my ($switchwarning,$switchserver) = @_;
                   16754:     my $output = &start_page('Selected course unavailable on this server').
                   16755:                  '<p class="LC_warning">';
                   16756:     if ($switchwarning) {
                   16757:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16758:         if (&show_course()) {
                   16759:             $output .= &mt('Display courses');
                   16760:         } else {
                   16761:             $output .= &mt('Display roles');
                   16762:         }
                   16763:         $output .= '</a>';
                   16764:     } elsif ($switchserver) {
                   16765:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16766:                    '<br />'.
                   16767:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16768:                    &mt('Switch Server').
                   16769:                    '</a>';
                   16770:     }
                   16771:     $output .= '</p>'.&end_page();
                   16772:     return $output;
                   16773: }
                   16774: 
                   16775: =pod
                   16776: 
                   16777: =item * &needs_coursereinit()
                   16778: 
                   16779: Determine if course contents stored for user's session needs to be
                   16780: refreshed, because content has changed since "Big Hash" last tied.
                   16781: 
                   16782: Check for change is made if time last checked is more than 10 minutes ago
                   16783: (by default).
                   16784: 
                   16785: Inputs:
                   16786: 
                   16787: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16788: 
                   16789: $interval (optional) - Time which may elapse (in s) between last check for content
                   16790:                        change in current course. (default: 600 s).  
                   16791: 
                   16792: Returns: an array; first element is:
                   16793: 
                   16794: =over 4
                   16795: 
                   16796: 'switch' - if content updates mean user's session
                   16797:            needs to be switched to a server running a newer LON-CAPA version
                   16798:  
                   16799: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16800:            on current server hosting user's session                
                   16801: 
                   16802: ''       - if no action required.
                   16803: 
                   16804: =back
                   16805: 
                   16806: If first item element is 'switch':
                   16807: 
                   16808: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   16809: 
                   16810: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16811:                               and current role. 
                   16812: 
                   16813: otherwise: no other elements returned.
                   16814: 
                   16815: =back
                   16816: 
                   16817: =cut
                   16818: 
                   16819: sub needs_coursereinit {
                   16820:     my ($loncaparev,$interval) = @_;
                   16821:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16822:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16823:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16824:     my $now = time;
                   16825:     if ($interval eq '') {
                   16826:         $interval = 600;
                   16827:     }
                   16828:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16829:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16830:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16831:         if ($lastchange > $env{'request.course.tied'}) {
                   16832:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16833:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16834:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16835:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16836:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16837:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16838:                     my ($switchserver,$switchwarning) =
                   16839:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16840:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16841:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16842:                         return ('switch',$switchwarning,$switchserver);
                   16843:                     }
                   16844:                 }
                   16845:             }
                   16846:             return ('update');
                   16847:         }
                   16848:     }
                   16849:     return ();
                   16850: }
1.1181    raeburn  16851: 
1.1083    raeburn  16852: sub update_content_constraints {
                   16853:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16854:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16855:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16856:     my %checkresponsetypes;
                   16857:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  16858:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  16859:         if ($item eq 'resourcetag') {
                   16860:             if ($name eq 'responsetype') {
                   16861:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16862:             }
                   16863:         }
                   16864:     }
                   16865:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16866:     if (defined($navmap)) {
                   16867:         my %allresponses;
                   16868:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16869:             my %responses = $res->responseTypes();
                   16870:             foreach my $key (keys(%responses)) {
                   16871:                 next unless(exists($checkresponsetypes{$key}));
                   16872:                 $allresponses{$key} += $responses{$key};
                   16873:             }
                   16874:         }
                   16875:         foreach my $key (keys(%allresponses)) {
                   16876:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16877:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16878:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16879:             }
                   16880:         }
                   16881:         undef($navmap);
                   16882:     }
                   16883:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16884:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16885:     }
                   16886:     return;
                   16887: }
                   16888: 
1.1110    raeburn  16889: sub allmaps_incourse {
                   16890:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16891:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16892:         $cid = $env{'request.course.id'};
                   16893:         $cdom = $env{'course.'.$cid.'.domain'};
                   16894:         $cnum = $env{'course.'.$cid.'.num'};
                   16895:         $chome = $env{'course.'.$cid.'.home'};
                   16896:     }
                   16897:     my %allmaps = ();
                   16898:     my $lastchange =
                   16899:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16900:     if ($lastchange > $env{'request.course.tied'}) {
                   16901:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16902:         unless ($ferr) {
                   16903:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16904:         }
                   16905:     }
                   16906:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16907:     if (defined($navmap)) {
                   16908:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16909:             $allmaps{$res->src()} = 1;
                   16910:         }
                   16911:     }
                   16912:     return \%allmaps;
                   16913: }
                   16914: 
1.1083    raeburn  16915: sub parse_supplemental_title {
                   16916:     my ($title) = @_;
                   16917: 
                   16918:     my ($foldertitle,$renametitle);
                   16919:     if ($title =~ /&amp;&amp;&amp;/) {
                   16920:         $title = &HTML::Entites::decode($title);
                   16921:     }
                   16922:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16923:         $renametitle=$4;
                   16924:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16925:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16926:         my $name =  &plainname($uname,$udom);
                   16927:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16928:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16929:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16930:             $name.': <br />'.$foldertitle;
                   16931:     }
                   16932:     if (wantarray) {
                   16933:         return ($title,$foldertitle,$renametitle);
                   16934:     }
                   16935:     return $title;
                   16936: }
                   16937: 
1.1143    raeburn  16938: sub recurse_supplemental {
                   16939:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16940:     if ($suppmap) {
                   16941:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16942:         if ($fatal) {
                   16943:             $errors ++;
                   16944:         } else {
                   16945:             if ($#LONCAPA::map::resources > 0) {
                   16946:                 foreach my $res (@LONCAPA::map::resources) {
                   16947:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16948:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  16949:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16950:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  16951:                         } else {
                   16952:                             $numfiles ++;
                   16953:                         }
                   16954:                     }
                   16955:                 }
                   16956:             }
                   16957:         }
                   16958:     }
                   16959:     return ($numfiles,$errors);
                   16960: }
                   16961: 
1.1101    raeburn  16962: sub symb_to_docspath {
1.1267  ! raeburn  16963:     my ($symb,$navmapref) = @_;
        !          16964:     return unless ($symb && ref($navmapref));
1.1101    raeburn  16965:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16966:     if ($resurl=~/\.(sequence|page)$/) {
                   16967:         $mapurl=$resurl;
                   16968:     } elsif ($resurl eq 'adm/navmaps') {
                   16969:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16970:     }
                   16971:     my $mapresobj;
1.1267  ! raeburn  16972:     unless (ref($$navmapref)) {
        !          16973:         $$navmapref = Apache::lonnavmaps::navmap->new();
        !          16974:     }
        !          16975:     if (ref($$navmapref)) {
        !          16976:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  16977:     }
                   16978:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16979:     my $type=$2;
                   16980:     my $path;
                   16981:     if (ref($mapresobj)) {
                   16982:         my $pcslist = $mapresobj->map_hierarchy();
                   16983:         if ($pcslist ne '') {
                   16984:             foreach my $pc (split(/,/,$pcslist)) {
                   16985:                 next if ($pc <= 1);
1.1267  ! raeburn  16986:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  16987:                 if (ref($res)) {
                   16988:                     my $thisurl = $res->src();
                   16989:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16990:                     my $thistitle = $res->title();
                   16991:                     $path .= '&'.
                   16992:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  16993:                              &escape($thistitle).
1.1101    raeburn  16994:                              ':'.$res->randompick().
                   16995:                              ':'.$res->randomout().
                   16996:                              ':'.$res->encrypted().
                   16997:                              ':'.$res->randomorder().
                   16998:                              ':'.$res->is_page();
                   16999:                 }
                   17000:             }
                   17001:         }
                   17002:         $path =~ s/^\&//;
                   17003:         my $maptitle = $mapresobj->title();
                   17004:         if ($mapurl eq 'default') {
1.1129    raeburn  17005:             $maptitle = 'Main Content';
1.1101    raeburn  17006:         }
                   17007:         $path .= (($path ne '')? '&' : '').
                   17008:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17009:                  &escape($maptitle).
1.1101    raeburn  17010:                  ':'.$mapresobj->randompick().
                   17011:                  ':'.$mapresobj->randomout().
                   17012:                  ':'.$mapresobj->encrypted().
                   17013:                  ':'.$mapresobj->randomorder().
                   17014:                  ':'.$mapresobj->is_page();
                   17015:     } else {
                   17016:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17017:         my $ispage = (($type eq 'page')? 1 : '');
                   17018:         if ($mapurl eq 'default') {
1.1129    raeburn  17019:             $maptitle = 'Main Content';
1.1101    raeburn  17020:         }
                   17021:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17022:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  17023:     }
                   17024:     unless ($mapurl eq 'default') {
                   17025:         $path = 'default&'.
1.1146    raeburn  17026:                 &escape('Main Content').
1.1101    raeburn  17027:                 ':::::&'.$path;
                   17028:     }
                   17029:     return $path;
                   17030: }
                   17031: 
1.1094    raeburn  17032: sub captcha_display {
                   17033:     my ($context,$lonhost) = @_;
                   17034:     my ($output,$error);
1.1234    raeburn  17035:     my ($captcha,$pubkey,$privkey,$version) = 
                   17036:         &get_captcha_config($context,$lonhost);
1.1095    raeburn  17037:     if ($captcha eq 'original') {
1.1094    raeburn  17038:         $output = &create_captcha();
                   17039:         unless ($output) {
1.1172    raeburn  17040:             $error = 'captcha';
1.1094    raeburn  17041:         }
                   17042:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17043:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  17044:         unless ($output) {
1.1172    raeburn  17045:             $error = 'recaptcha';
1.1094    raeburn  17046:         }
                   17047:     }
1.1234    raeburn  17048:     return ($output,$error,$captcha,$version);
1.1094    raeburn  17049: }
                   17050: 
                   17051: sub captcha_response {
                   17052:     my ($context,$lonhost) = @_;
                   17053:     my ($captcha_chk,$captcha_error);
1.1234    raeburn  17054:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  17055:     if ($captcha eq 'original') {
1.1094    raeburn  17056:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17057:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17058:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  17059:     } else {
                   17060:         $captcha_chk = 1;
                   17061:     }
                   17062:     return ($captcha_chk,$captcha_error);
                   17063: }
                   17064: 
                   17065: sub get_captcha_config {
                   17066:     my ($context,$lonhost) = @_;
1.1234    raeburn  17067:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  17068:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17069:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17070:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  17071:     if ($context eq 'usercreation') {
                   17072:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17073:         if (ref($domconfig{$context}) eq 'HASH') {
                   17074:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17075:             if (ref($hashtocheck) eq 'HASH') {
                   17076:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17077:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17078:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17079:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17080:                     }
                   17081:                     if ($privkey && $pubkey) {
                   17082:                         $captcha = 'recaptcha';
1.1234    raeburn  17083:                         $version = $hashtocheck->{'recaptchaversion'};
                   17084:                         if ($version ne '2') {
                   17085:                             $version = 1;
                   17086:                         }
1.1095    raeburn  17087:                     } else {
                   17088:                         $captcha = 'original';
                   17089:                     }
                   17090:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17091:                     $captcha = 'original';
                   17092:                 }
1.1094    raeburn  17093:             }
1.1095    raeburn  17094:         } else {
                   17095:             $captcha = 'captcha';
                   17096:         }
                   17097:     } elsif ($context eq 'login') {
                   17098:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17099:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17100:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17101:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  17102:             if ($privkey && $pubkey) {
                   17103:                 $captcha = 'recaptcha';
1.1234    raeburn  17104:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17105:                 if ($version ne '2') {
                   17106:                     $version = 1; 
                   17107:                 }
1.1095    raeburn  17108:             } else {
                   17109:                 $captcha = 'original';
1.1094    raeburn  17110:             }
1.1095    raeburn  17111:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17112:             $captcha = 'original';
1.1094    raeburn  17113:         }
                   17114:     }
1.1234    raeburn  17115:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  17116: }
                   17117: 
                   17118: sub create_captcha {
                   17119:     my %captcha_params = &captcha_settings();
                   17120:     my ($output,$maxtries,$tries) = ('',10,0);
                   17121:     while ($tries < $maxtries) {
                   17122:         $tries ++;
                   17123:         my $captcha = Authen::Captcha->new (
                   17124:                                            output_folder => $captcha_params{'output_dir'},
                   17125:                                            data_folder   => $captcha_params{'db_dir'},
                   17126:                                           );
                   17127:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17128: 
                   17129:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17130:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17131:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  17132:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17133:                       '<br />'.
                   17134:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  17135:             last;
                   17136:         }
                   17137:     }
                   17138:     return $output;
                   17139: }
                   17140: 
                   17141: sub captcha_settings {
                   17142:     my %captcha_params = (
                   17143:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17144:                            www_output_dir => "/captchaspool",
                   17145:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17146:                            numchars       => '5',
                   17147:                          );
                   17148:     return %captcha_params;
                   17149: }
                   17150: 
                   17151: sub check_captcha {
                   17152:     my ($captcha_chk,$captcha_error);
                   17153:     my $code = $env{'form.code'};
                   17154:     my $md5sum = $env{'form.crypt'};
                   17155:     my %captcha_params = &captcha_settings();
                   17156:     my $captcha = Authen::Captcha->new(
                   17157:                       output_folder => $captcha_params{'output_dir'},
                   17158:                       data_folder   => $captcha_params{'db_dir'},
                   17159:                   );
1.1109    raeburn  17160:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  17161:     my %captcha_hash = (
                   17162:                         0       => 'Code not checked (file error)',
                   17163:                        -1      => 'Failed: code expired',
                   17164:                        -2      => 'Failed: invalid code (not in database)',
                   17165:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17166:     );
                   17167:     if ($captcha_chk != 1) {
                   17168:         $captcha_error = $captcha_hash{$captcha_chk}
                   17169:     }
                   17170:     return ($captcha_chk,$captcha_error);
                   17171: }
                   17172: 
                   17173: sub create_recaptcha {
1.1234    raeburn  17174:     my ($pubkey,$version) = @_;
                   17175:     if ($version >= 2) {
                   17176:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17177:     } else {
                   17178:         my $use_ssl;
                   17179:         if ($ENV{'SERVER_PORT'} == 443) {
                   17180:             $use_ssl = 1;
                   17181:         }
                   17182:         my $captcha = Captcha::reCAPTCHA->new;
                   17183:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17184:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17185:                &mt('If the text is hard to read, [_1] will replace them.',
                   17186:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17187:                '<br /><br />';
                   17188:     }
1.1094    raeburn  17189: }
                   17190: 
                   17191: sub check_recaptcha {
1.1234    raeburn  17192:     my ($privkey,$version) = @_;
1.1094    raeburn  17193:     my $captcha_chk;
1.1234    raeburn  17194:     if ($version >= 2) {
                   17195:         my $ua = LWP::UserAgent->new;
                   17196:         $ua->timeout(10);
                   17197:         my %info = (
                   17198:                      secret   => $privkey, 
                   17199:                      response => $env{'form.g-recaptcha-response'},
                   17200:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17201:                    );
                   17202:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17203:         if ($response->is_success)  {
                   17204:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17205:             if (ref($data) eq 'HASH') {
                   17206:                 if ($data->{'success'}) {
                   17207:                     $captcha_chk = 1;
                   17208:                 }
                   17209:             }
                   17210:         }
                   17211:     } else {
                   17212:         my $captcha = Captcha::reCAPTCHA->new;
                   17213:         my $captcha_result =
                   17214:             $captcha->check_answer(
                   17215:                                     $privkey,
                   17216:                                     $ENV{'REMOTE_ADDR'},
                   17217:                                     $env{'form.recaptcha_challenge_field'},
                   17218:                                     $env{'form.recaptcha_response_field'},
                   17219:                                   );
                   17220:         if ($captcha_result->{is_valid}) {
                   17221:             $captcha_chk = 1;
                   17222:         }
1.1094    raeburn  17223:     }
                   17224:     return $captcha_chk;
                   17225: }
                   17226: 
1.1174    raeburn  17227: sub emailusername_info {
1.1244    raeburn  17228:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  17229:     my %titles = &Apache::lonlocal::texthash (
                   17230:                      lastname      => 'Last Name',
                   17231:                      firstname     => 'First Name',
                   17232:                      institution   => 'School/college/university',
                   17233:                      location      => "School's city, state/province, country",
                   17234:                      web           => "School's web address",
                   17235:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  17236:                      id            => 'Student/Employee ID',
1.1174    raeburn  17237:                  );
                   17238:     return (\@fields,\%titles);
                   17239: }
                   17240: 
1.1161    raeburn  17241: sub cleanup_html {
                   17242:     my ($incoming) = @_;
                   17243:     my $outgoing;
                   17244:     if ($incoming ne '') {
                   17245:         $outgoing = $incoming;
                   17246:         $outgoing =~ s/;/&#059;/g;
                   17247:         $outgoing =~ s/\#/&#035;/g;
                   17248:         $outgoing =~ s/\&/&#038;/g;
                   17249:         $outgoing =~ s/</&#060;/g;
                   17250:         $outgoing =~ s/>/&#062;/g;
                   17251:         $outgoing =~ s/\(/&#040/g;
                   17252:         $outgoing =~ s/\)/&#041;/g;
                   17253:         $outgoing =~ s/"/&#034;/g;
                   17254:         $outgoing =~ s/'/&#039;/g;
                   17255:         $outgoing =~ s/\$/&#036;/g;
                   17256:         $outgoing =~ s{/}{&#047;}g;
                   17257:         $outgoing =~ s/=/&#061;/g;
                   17258:         $outgoing =~ s/\\/&#092;/g
                   17259:     }
                   17260:     return $outgoing;
                   17261: }
                   17262: 
1.1190    musolffc 17263: # Checks for critical messages and returns a redirect url if one exists.
                   17264: # $interval indicates how often to check for messages.
                   17265: sub critical_redirect {
                   17266:     my ($interval) = @_;
                   17267:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   17268:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   17269:                                         $env{'user.name'});
                   17270:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  17271:         my $redirecturl;
1.1190    musolffc 17272:         if ($what[0]) {
                   17273: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17274: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  17275: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17276:                 return (1, $url);
1.1190    musolffc 17277:             }
1.1191    raeburn  17278:         }
                   17279:     } 
                   17280:     return ();
1.1190    musolffc 17281: }
                   17282: 
1.1174    raeburn  17283: # Use:
                   17284: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17285: #
                   17286: ##################################################
                   17287: #          password associated functions         #
                   17288: ##################################################
                   17289: sub des_keys {
                   17290:     # Make a new key for DES encryption.
                   17291:     # Each key has two parts which are returned separately.
                   17292:     # Please note:  Each key must be passed through the &hex function
                   17293:     # before it is output to the web browser.  The hex versions cannot
                   17294:     # be used to decrypt.
                   17295:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17296:                 '8','9','a','b','c','d','e','f');
                   17297:     my $lkey='';
                   17298:     for (0..7) {
                   17299:         $lkey.=$hexstr[rand(15)];
                   17300:     }
                   17301:     my $ukey='';
                   17302:     for (0..7) {
                   17303:         $ukey.=$hexstr[rand(15)];
                   17304:     }
                   17305:     return ($lkey,$ukey);
                   17306: }
                   17307: 
                   17308: sub des_decrypt {
                   17309:     my ($key,$cyphertext) = @_;
                   17310:     my $keybin=pack("H16",$key);
                   17311:     my $cypher;
                   17312:     if ($Crypt::DES::VERSION>=2.03) {
                   17313:         $cypher=new Crypt::DES $keybin;
                   17314:     } else {
                   17315:         $cypher=new DES $keybin;
                   17316:     }
1.1233    raeburn  17317:     my $plaintext='';
                   17318:     my $cypherlength = length($cyphertext);
                   17319:     my $numchunks = int($cypherlength/32);
                   17320:     for (my $j=0; $j<$numchunks; $j++) {
                   17321:         my $start = $j*32;
                   17322:         my $cypherblock = substr($cyphertext,$start,32);
                   17323:         my $chunk =
                   17324:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17325:         $chunk .=
                   17326:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17327:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17328:         $plaintext .= $chunk;
                   17329:     }
1.1174    raeburn  17330:     return $plaintext;
                   17331: }
                   17332: 
1.112     bowersj2 17333: 1;
                   17334: __END__;
1.41      ng       17335: 

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