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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1457  ! raeburn     4: # $Id: loncommon.pm,v 1.1456 2025/02/17 18:48:06 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.1383    raeburn    64: use Apache::lonnavmaps();
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.1409    raeburn    74: use LONCAPA::ltiutils;
1.1280    raeburn    75: use LONCAPA::LWPReq;
1.1395    raeburn    76: use LONCAPA::map();
1.1328    raeburn    77: use HTTP::Request;
1.657     raeburn    78: use DateTime::TimeZone;
1.1241    raeburn    79: use DateTime::Locale;
1.1220    raeburn    80: use Encode();
1.1091    foxr       81: use Text::Aspell;
1.1094    raeburn    82: use Authen::Captcha;
                     83: use Captcha::reCAPTCHA;
1.1234    raeburn    84: use JSON::DWIW;
1.1174    raeburn    85: use Crypt::DES;
                     86: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   87: use MIME::Lite;
                     88: use MIME::Types;
1.1292    raeburn    89: use File::Copy();
1.1300    raeburn    90: use File::Path();
1.1309    raeburn    91: use String::CRC32();
                     92: use Short::URL();
1.117     www        93: 
1.517     raeburn    94: # ---------------------------------------------- Designs
                     95: use vars qw(%defaultdesign);
                     96: 
1.22      www        97: my $readit;
                     98: 
1.517     raeburn    99: 
1.157     matthew   100: ##
                    101: ## Global Variables
                    102: ##
1.46      matthew   103: 
1.643     foxr      104: 
                    105: # ----------------------------------------------- SSI with retries:
                    106: #
                    107: 
                    108: =pod
                    109: 
1.648     raeburn   110: =head1 Server Side include with retries:
1.643     foxr      111: 
                    112: =over 4
                    113: 
1.648     raeburn   114: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      115: 
                    116: Performs an ssi with some number of retries.  Retries continue either
                    117: until the result is ok or until the retry count supplied by the
                    118: caller is exhausted.  
                    119: 
                    120: Inputs:
1.648     raeburn   121: 
                    122: =over 4
                    123: 
1.643     foxr      124: resource   - Identifies the resource to insert.
1.648     raeburn   125: 
1.643     foxr      126: retries    - Count of the number of retries allowed.
1.648     raeburn   127: 
1.643     foxr      128: form       - Hash that identifies the rendering options.
                    129: 
1.648     raeburn   130: =back
                    131: 
                    132: Returns:
                    133: 
                    134: =over 4
                    135: 
1.643     foxr      136: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   137: 
1.643     foxr      138: response   - The response from the last attempt (which may or may not have been successful.
                    139: 
1.648     raeburn   140: =back
                    141: 
                    142: =back
                    143: 
1.643     foxr      144: =cut
                    145: 
                    146: sub ssi_with_retries {
                    147:     my ($resource, $retries, %form) = @_;
                    148: 
                    149: 
                    150:     my $ok = 0;			# True if we got a good response.
                    151:     my $content;
                    152:     my $response;
                    153: 
                    154:     # Try to get the ssi done. within the retries count:
                    155: 
                    156:     do {
                    157: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    158: 	$ok      = $response->is_success;
1.650     www       159:         if (!$ok) {
                    160:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    161:         }
1.643     foxr      162: 	$retries--;
                    163:     } while (!$ok && ($retries > 0));
                    164: 
                    165:     if (!$ok) {
                    166: 	$content = '';		# On error return an empty content.
                    167:     }
                    168:     return ($content, $response);
                    169: 
                    170: }
                    171: 
                    172: 
                    173: 
1.20      www       174: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  175: my %language;
1.124     www       176: my %supported_language;
1.1088    foxr      177: my %supported_codes;
1.1048    foxr      178: my %latex_language;		# For choosing hyphenation in <transl..>
                    179: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  180: my %cprtag;
1.192     taceyjo1  181: my %scprtag;
1.351     www       182: my %fe; my %fd; my %fm;
1.41      ng        183: my %category_extensions;
1.12      harris41  184: 
1.46      matthew   185: # ---------------------------------------------- Thesaurus variables
1.144     matthew   186: #
                    187: # %Keywords:
                    188: #      A hash used by &keyword to determine if a word is considered a keyword.
                    189: # $thesaurus_db_file 
                    190: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   191: 
                    192: my %Keywords;
                    193: my $thesaurus_db_file;
                    194: 
1.144     matthew   195: #
                    196: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    197: # thesaurus.tab, and filecategories.tab.
                    198: #
1.18      www       199: BEGIN {
1.46      matthew   200:     # Variable initialization
                    201:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    202:     #
1.22      www       203:     unless ($readit) {
1.12      harris41  204: # ------------------------------------------------------------------- languages
                    205:     {
1.158     raeburn   206:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    207:                                    '/language.tab';
1.1317    raeburn   208:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  209:             while (my $line = <$fh>) {
                    210:                 next if ($line=~/^\#/);
                    211:                 chomp($line);
1.1088    foxr      212:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   213:                 $language{$key}=$val.' - '.$enc;
                    214:                 if ($sup) {
                    215:                     $supported_language{$key}=$sup;
1.1088    foxr      216: 		    $supported_codes{$key}   = $code;
1.158     raeburn   217:                 }
1.1048    foxr      218: 		if ($latex) {
                    219: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      220: 		    $latex_language{$code} = $latex;
1.1048    foxr      221: 		}
1.158     raeburn   222:             }
                    223:             close($fh);
                    224:         }
1.12      harris41  225:     }
                    226: # ------------------------------------------------------------------ copyrights
                    227:     {
1.158     raeburn   228:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    229:                                   '/copyright.tab';
1.1317    raeburn   230:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  231:             while (my $line = <$fh>) {
                    232:                 next if ($line=~/^\#/);
                    233:                 chomp($line);
                    234:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   235:                 $cprtag{$key}=$val;
                    236:             }
                    237:             close($fh);
                    238:         }
1.12      harris41  239:     }
1.351     www       240: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  241:     {
                    242:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    243:                                   '/source_copyright.tab';
1.1317    raeburn   244:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  245:             while (my $line = <$fh>) {
                    246:                 next if ($line =~ /^\#/);
                    247:                 chomp($line);
                    248:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  249:                 $scprtag{$key}=$val;
                    250:             }
                    251:             close($fh);
                    252:         }
                    253:     }
1.63      www       254: 
1.517     raeburn   255: # -------------------------------------------------------------- default domain designs
1.63      www       256:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   257:     my $designfile = $designdir.'/default.tab';
1.1317    raeburn   258:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   259:         while (my $line = <$fh>) {
                    260:             next if ($line =~ /^\#/);
                    261:             chomp($line);
                    262:             my ($key,$val)=(split(/\=/,$line));
                    263:             if ($val) { $defaultdesign{$key}=$val; }
                    264:         }
                    265:         close($fh);
1.63      www       266:     }
                    267: 
1.15      harris41  268: # ------------------------------------------------------------- file categories
                    269:     {
1.158     raeburn   270:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    271:                                   '/filecategories.tab';
1.1317    raeburn   272:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  273: 	    while (my $line = <$fh>) {
                    274: 		next if ($line =~ /^\#/);
                    275: 		chomp($line);
                    276:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   277:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   278:             }
                    279:             close($fh);
                    280:         }
                    281: 
1.15      harris41  282:     }
1.12      harris41  283: # ------------------------------------------------------------------ file types
                    284:     {
1.158     raeburn   285:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    286:                '/filetypes.tab';
1.1317    raeburn   287:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  288:             while (my $line = <$fh>) {
                    289: 		next if ($line =~ /^\#/);
                    290: 		chomp($line);
                    291:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   292:                 if ($descr ne '') {
                    293:                     $fe{$ending}=lc($emb);
                    294:                     $fd{$ending}=$descr;
1.351     www       295:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   296:                 }
                    297:             }
                    298:             close($fh);
                    299:         }
1.12      harris41  300:     }
1.22      www       301:     &Apache::lonnet::logthis(
1.705     tempelho  302:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       303:     $readit=1;
1.46      matthew   304:     }  # end of unless($readit) 
1.32      matthew   305:     
                    306: }
1.112     bowersj2  307: 
1.42      matthew   308: ###############################################################
                    309: ##           HTML and Javascript Helper Functions            ##
                    310: ###############################################################
                    311: 
                    312: =pod 
                    313: 
1.112     bowersj2  314: =head1 HTML and Javascript Functions
1.42      matthew   315: 
1.112     bowersj2  316: =over 4
                    317: 
1.648     raeburn   318: =item * &browser_and_searcher_javascript()
1.112     bowersj2  319: 
                    320: X<browsing, javascript>X<searching, javascript>Returns a string
                    321: containing javascript with two functions, C<openbrowser> and
                    322: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    323: tags.
1.42      matthew   324: 
1.648     raeburn   325: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   326: 
                    327: inputs: formname, elementname, only, omit
                    328: 
                    329: formname and elementname indicate the name of the html form and name of
                    330: the element that the results of the browsing selection are to be placed in. 
                    331: 
                    332: Specifying 'only' will restrict the browser to displaying only files
1.185     www       333: with the given extension.  Can be a comma separated list.
1.42      matthew   334: 
                    335: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       336: with the given extension.  Can be a comma separated list.
1.42      matthew   337: 
1.648     raeburn   338: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   339: 
                    340: Inputs: formname, elementname
                    341: 
                    342: formname and elementname specify the name of the html form and the name
                    343: of the element the selection from the search results will be placed in.
1.542     raeburn   344: 
1.42      matthew   345: =cut
                    346: 
                    347: sub browser_and_searcher_javascript {
1.199     albertel  348:     my ($mode)=@_;
                    349:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  350:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   351:     return <<END;
1.219     albertel  352: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   353:     var editbrowser = null;
1.135     albertel  354:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       355:         var url = '$resurl/?';
1.42      matthew   356:         if (editbrowser == null) {
                    357:             url += 'launch=1&';
                    358:         }
                    359:         url += 'catalogmode=interactive&';
1.199     albertel  360:         url += 'mode=$mode&';
1.611     albertel  361:         url += 'inhibitmenu=yes&';
1.42      matthew   362:         url += 'form=' + formname + '&';
                    363:         if (only != null) {
                    364:             url += 'only=' + only + '&';
1.217     albertel  365:         } else {
                    366:             url += 'only=&';
                    367: 	}
1.42      matthew   368:         if (omit != null) {
                    369:             url += 'omit=' + omit + '&';
1.217     albertel  370:         } else {
                    371:             url += 'omit=&';
                    372: 	}
1.135     albertel  373:         if (titleelement != null) {
                    374:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  375:         } else {
                    376: 	    url += 'titleelement=&';
                    377: 	}
1.42      matthew   378:         url += 'element=' + elementname + '';
                    379:         var title = 'Browser';
1.435     albertel  380:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   381:         options += ',width=700,height=600';
                    382:         editbrowser = open(url,title,options,'1');
                    383:         editbrowser.focus();
                    384:     }
                    385:     var editsearcher;
1.135     albertel  386:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   387:         var url = '/adm/searchcat?';
                    388:         if (editsearcher == null) {
                    389:             url += 'launch=1&';
                    390:         }
                    391:         url += 'catalogmode=interactive&';
1.199     albertel  392:         url += 'mode=$mode&';
1.42      matthew   393:         url += 'form=' + formname + '&';
1.135     albertel  394:         if (titleelement != null) {
                    395:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  396:         } else {
                    397: 	    url += 'titleelement=&';
                    398: 	}
1.42      matthew   399:         url += 'element=' + elementname + '';
                    400:         var title = 'Search';
1.435     albertel  401:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   402:         options += ',width=700,height=600';
                    403:         editsearcher = open(url,title,options,'1');
                    404:         editsearcher.focus();
                    405:     }
1.219     albertel  406: // END LON-CAPA Internal -->
1.42      matthew   407: END
1.170     www       408: }
                    409: 
                    410: sub lastresurl {
1.258     albertel  411:     if ($env{'environment.lastresurl'}) {
                    412: 	return $env{'environment.lastresurl'}
1.170     www       413:     } else {
                    414: 	return '/res';
                    415:     }
                    416: }
                    417: 
                    418: sub storeresurl {
                    419:     my $resurl=&Apache::lonnet::clutter(shift);
                    420:     unless ($resurl=~/^\/res/) { return 0; }
                    421:     $resurl=~s/\/$//;
                    422:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   423:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       424:     return 1;
1.42      matthew   425: }
                    426: 
1.74      www       427: sub studentbrowser_javascript {
1.111     www       428:    unless (
1.258     albertel  429:             (($env{'request.course.id'}) && 
1.302     albertel  430:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    431: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    432: 					  '/'.$env{'request.course.sec'})
                    433: 	      ))
1.258     albertel  434:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       435:           ) { return ''; }  
1.74      www       436:    return (<<'ENDSTDBRW');
1.776     bisitz    437: <script type="text/javascript" language="Javascript">
1.824     bisitz    438: // <![CDATA[
1.74      www       439:     var stdeditbrowser;
1.1413    raeburn   440:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv,uident) {
1.74      www       441:         var url = '/adm/pickstudent?';
                    442:         var filter;
1.558     albertel  443: 	if (!ignorefilter) {
                    444: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    445: 	}
1.74      www       446:         if (filter != null) {
                    447:            if (filter != '') {
                    448:                url += 'filter='+filter+'&';
                    449: 	   }
                    450:         }
                    451:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       452:                                     '&udomelement='+udom+
                    453:                                     '&clicker='+clicker;
1.111     www       454: 	if (roleflag) { url+="&roles=1"; }
1.1337    raeburn   455:         if (courseadv == 'condition') {
                    456:             if (document.getElementById('courseadv')) {
                    457:                 courseadv = document.getElementById('courseadv').value;
                    458:             }
                    459:         }
                    460:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.1413    raeburn   461:         if (uident !== '') { url+="&identelement="+uident; } 
1.102     www       462:         var title = 'Student_Browser';
1.74      www       463:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    464:         options += ',width=700,height=600';
                    465:         stdeditbrowser = open(url,title,options,'1');
                    466:         stdeditbrowser.focus();
                    467:     }
1.824     bisitz    468: // ]]>
1.74      www       469: </script>
                    470: ENDSTDBRW
                    471: }
1.42      matthew   472: 
1.1003    www       473: sub resourcebrowser_javascript {
                    474:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       475:    return (<<'ENDRESBRW');
1.1003    www       476: <script type="text/javascript" language="Javascript">
                    477: // <![CDATA[
                    478:     var reseditbrowser;
1.1004    www       479:     function openresbrowser(formname,reslink) {
1.1005    www       480:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       481:         var title = 'Resource_Browser';
                    482:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       483:         options += ',width=700,height=500';
1.1004    www       484:         reseditbrowser = open(url,title,options,'1');
                    485:         reseditbrowser.focus();
1.1003    www       486:     }
                    487: // ]]>
                    488: </script>
1.1004    www       489: ENDRESBRW
1.1003    www       490: }
                    491: 
1.74      www       492: sub selectstudent_link {
1.1413    raeburn   493:    my ($form,$unameele,$udomele,$courseadv,$clickerid,$identelem)=@_;
1.999     www       494:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    495:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    496:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  497:    if ($env{'request.course.id'}) {  
1.302     albertel  498:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    499: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    500: 					'/'.$env{'request.course.sec'})) {
1.111     www       501: 	   return '';
                    502:        }
1.999     www       503:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1337    raeburn   504:        if ($courseadv eq 'only') {
                    505:            $callargs .= ",'',1,'$courseadv'";
                    506:        } elsif ($courseadv eq 'none') {
                    507:            $callargs .= ",'','','$courseadv'";
                    508:        } elsif ($courseadv eq 'condition') {
                    509:            $callargs .= ",'','','$courseadv'";
1.1413    raeburn   510:        } elsif ($identelem ne '') {
                    511:            $callargs .= ",'','',''";
                    512:        }
                    513:        if ($identelem ne '') {
                    514:            $callargs .= ",'".&Apache::lonhtmlcommon::entity_encode($identelem)."'";
1.793     raeburn   515:        }
                    516:        return '<span class="LC_nobreak">'.
                    517:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    518:               &mt('Select User').'</a></span>';
1.74      www       519:    }
1.258     albertel  520:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       521:        $callargs .= ",'',1"; 
1.793     raeburn   522:        return '<span class="LC_nobreak">'.
                    523:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    524:               &mt('Select User').'</a></span>';
1.111     www       525:    }
                    526:    return '';
1.91      www       527: }
                    528: 
1.1004    www       529: sub selectresource_link {
                    530:    my ($form,$reslink,$arg)=@_;
                    531:    
                    532:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    533:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    534:    unless ($env{'request.course.id'}) { return $arg; }
                    535:    return '<span class="LC_nobreak">'.
                    536:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    537:               $arg.'</a></span>';
                    538: }
                    539: 
                    540: 
                    541: 
1.653     raeburn   542: sub authorbrowser_javascript {
                    543:     return <<"ENDAUTHORBRW";
1.776     bisitz    544: <script type="text/javascript" language="JavaScript">
1.824     bisitz    545: // <![CDATA[
1.653     raeburn   546: var stdeditbrowser;
                    547: 
                    548: function openauthorbrowser(formname,udom) {
                    549:     var url = '/adm/pickauthor?';
                    550:     url += 'form='+formname+'&roledom='+udom;
                    551:     var title = 'Author_Browser';
                    552:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    553:     options += ',width=700,height=600';
                    554:     stdeditbrowser = open(url,title,options,'1');
                    555:     stdeditbrowser.focus();
                    556: }
                    557: 
1.824     bisitz    558: // ]]>
1.653     raeburn   559: </script>
                    560: ENDAUTHORBRW
                    561: }
                    562: 
1.91      www       563: sub coursebrowser_javascript {
1.1116    raeburn   564:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   565:         $credits_element,$instcode) = @_;
1.932     raeburn   566:     my $wintitle = 'Course_Browser';
1.931     raeburn   567:     if ($crstype eq 'Community') {
1.932     raeburn   568:         $wintitle = 'Community_Browser';
1.909     raeburn   569:     }
1.876     raeburn   570:     my $id_functions = &javascript_index_functions();
                    571:     my $output = '
1.776     bisitz    572: <script type="text/javascript" language="JavaScript">
1.824     bisitz    573: // <![CDATA[
1.468     raeburn   574:     var stdeditbrowser;'."\n";
1.876     raeburn   575: 
                    576:     $output .= <<"ENDSTDBRW";
1.909     raeburn   577:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       578:         var url = '/adm/pickcourse?';
1.895     raeburn   579:         var formid = getFormIdByName(formname);
1.876     raeburn   580:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  581:         if (domainfilter != null) {
                    582:            if (domainfilter != '') {
                    583:                url += 'domainfilter='+domainfilter+'&';
                    584: 	   }
                    585:         }
1.91      www       586:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  587: 	                            '&cdomelement='+udom+
                    588:                                     '&cnameelement='+desc;
1.468     raeburn   589:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   590:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   591:                 url += '&roleelement='+extra_element;
                    592:                 if (domainfilter == null || domainfilter == '') {
                    593:                     url += '&domainfilter='+extra_element;
                    594:                 }
1.234     raeburn   595:             }
1.468     raeburn   596:             else {
                    597:                 if (formname == 'portform') {
                    598:                     url += '&setroles='+extra_element;
1.800     raeburn   599:                 } else {
                    600:                     if (formname == 'rules') {
                    601:                         url += '&fixeddom='+extra_element; 
                    602:                     }
1.468     raeburn   603:                 }
                    604:             }     
1.230     raeburn   605:         }
1.909     raeburn   606:         if (type != null && type != '') {
                    607:             url += '&type='+type;
                    608:         }
                    609:         if (type_elem != null && type_elem != '') {
                    610:             url += '&typeelement='+type_elem;
                    611:         }
1.872     raeburn   612:         if (formname == 'ccrs') {
                    613:             var ownername = document.forms[formid].ccuname.value;
                    614:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   615:             url += '&cloner='+ownername+':'+ownerdom;
                    616:             if (type == 'Course') {
                    617:                 url += '&crscode='+document.forms[formid].crscode.value;
                    618:             }
1.1221    raeburn   619:         }
                    620:         if (formname == 'requestcrs') {
                    621:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   622:         }
1.293     raeburn   623:         if (multflag !=null && multflag != '') {
                    624:             url += '&multiple='+multflag;
                    625:         }
1.909     raeburn   626:         var title = '$wintitle';
1.91      www       627:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    628:         options += ',width=700,height=600';
                    629:         stdeditbrowser = open(url,title,options,'1');
                    630:         stdeditbrowser.focus();
                    631:     }
1.876     raeburn   632: $id_functions
                    633: ENDSTDBRW
1.1116    raeburn   634:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    635:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    636:                                       $credits_element);
1.876     raeburn   637:     }
                    638:     $output .= '
                    639: // ]]>
                    640: </script>';
                    641:     return $output;
                    642: }
                    643: 
                    644: sub javascript_index_functions {
                    645:     return <<"ENDJS";
                    646: 
                    647: function getFormIdByName(formname) {
                    648:     for (var i=0;i<document.forms.length;i++) {
                    649:         if (document.forms[i].name == formname) {
                    650:             return i;
                    651:         }
                    652:     }
                    653:     return -1;
                    654: }
                    655: 
                    656: function getIndexByName(formid,item) {
                    657:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    658:         if (document.forms[formid].elements[i].name == item) {
                    659:             return i;
                    660:         }
                    661:     }
                    662:     return -1;
                    663: }
1.468     raeburn   664: 
1.876     raeburn   665: function getDomainFromSelectbox(formname,udom) {
                    666:     var userdom;
                    667:     var formid = getFormIdByName(formname);
                    668:     if (formid > -1) {
                    669:         var domid = getIndexByName(formid,udom);
                    670:         if (domid > -1) {
                    671:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    672:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    673:             }
                    674:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    675:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   676:             }
                    677:         }
                    678:     }
1.876     raeburn   679:     return userdom;
                    680: }
                    681: 
                    682: ENDJS
1.468     raeburn   683: 
1.876     raeburn   684: }
                    685: 
1.1017    raeburn   686: sub javascript_array_indexof {
1.1018    raeburn   687:     return <<ENDJS;
1.1017    raeburn   688: <script type="text/javascript" language="JavaScript">
                    689: // <![CDATA[
                    690: 
                    691: if (!Array.prototype.indexOf) {
                    692:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    693:         "use strict";
                    694:         if (this === void 0 || this === null) {
                    695:             throw new TypeError();
                    696:         }
                    697:         var t = Object(this);
                    698:         var len = t.length >>> 0;
                    699:         if (len === 0) {
                    700:             return -1;
                    701:         }
                    702:         var n = 0;
                    703:         if (arguments.length > 0) {
                    704:             n = Number(arguments[1]);
1.1088    foxr      705:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   706:                 n = 0;
                    707:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    708:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    709:             }
                    710:         }
                    711:         if (n >= len) {
                    712:             return -1;
                    713:         }
                    714:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    715:         for (; k < len; k++) {
                    716:             if (k in t && t[k] === searchElement) {
                    717:                 return k;
                    718:             }
                    719:         }
                    720:         return -1;
                    721:     }
                    722: }
                    723: 
                    724: // ]]>
                    725: </script>
                    726: 
                    727: ENDJS
                    728: 
                    729: }
                    730: 
1.876     raeburn   731: sub userbrowser_javascript {
                    732:     my $id_functions = &javascript_index_functions();
                    733:     return <<"ENDUSERBRW";
                    734: 
1.888     raeburn   735: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   736:     var url = '/adm/pickuser?';
                    737:     var userdom = getDomainFromSelectbox(formname,udom);
                    738:     if (userdom != null) {
                    739:        if (userdom != '') {
                    740:            url += 'srchdom='+userdom+'&';
                    741:        }
                    742:     }
                    743:     url += 'form=' + formname + '&unameelement='+uname+
                    744:                                 '&udomelement='+udom+
                    745:                                 '&ulastelement='+ulast+
                    746:                                 '&ufirstelement='+ufirst+
                    747:                                 '&uemailelement='+uemail+
1.881     raeburn   748:                                 '&hideudomelement='+hideudom+
                    749:                                 '&coursedom='+crsdom;
1.888     raeburn   750:     if ((caller != null) && (caller != undefined)) {
                    751:         url += '&caller='+caller;
                    752:     }
1.876     raeburn   753:     var title = 'User_Browser';
                    754:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    755:     options += ',width=700,height=600';
                    756:     var stdeditbrowser = open(url,title,options,'1');
                    757:     stdeditbrowser.focus();
                    758: }
                    759: 
1.888     raeburn   760: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   761:     var formid = getFormIdByName(formname);
                    762:     if (formid > -1) {
1.888     raeburn   763:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   764:         var domid = getIndexByName(formid,udom);
                    765:         var hidedomid = getIndexByName(formid,origdom);
                    766:         if (hidedomid > -1) {
                    767:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   768:             var unameval = document.forms[formid].elements[unameid].value;
                    769:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    770:                 if (domid > -1) {
                    771:                     var slct = document.forms[formid].elements[domid];
                    772:                     if (slct.type == 'select-one') {
                    773:                         var i;
                    774:                         for (i=0;i<slct.length;i++) {
                    775:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    776:                         }
                    777:                     }
                    778:                     if (slct.type == 'hidden') {
                    779:                         slct.value = fixeddom;
1.876     raeburn   780:                     }
                    781:                 }
1.468     raeburn   782:             }
                    783:         }
                    784:     }
1.876     raeburn   785:     return;
                    786: }
                    787: 
                    788: $id_functions
                    789: ENDUSERBRW
1.468     raeburn   790: }
                    791: 
                    792: sub setsec_javascript {
1.1116    raeburn   793:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   794:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    795:         $communityrolestr);
                    796:     if ($role_element ne '') {
                    797:         my @allroles = ('st','ta','ep','in','ad');
                    798:         foreach my $crstype ('Course','Community') {
                    799:             if ($crstype eq 'Community') {
                    800:                 foreach my $role (@allroles) {
                    801:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    802:                 }
                    803:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    804:             } else {
                    805:                 foreach my $role (@allroles) {
                    806:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    807:                 }
                    808:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    809:             }
                    810:         }
                    811:         $rolestr = '"'.join('","',@allroles).'"';
                    812:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    813:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    814:     }
1.468     raeburn   815:     my $setsections = qq|
                    816: function setSect(sectionlist) {
1.629     raeburn   817:     var sectionsArray = new Array();
                    818:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    819:         sectionsArray = sectionlist.split(",");
                    820:     }
1.468     raeburn   821:     var numSections = sectionsArray.length;
                    822:     document.$formname.$sec_element.length = 0;
                    823:     if (numSections == 0) {
                    824:         document.$formname.$sec_element.multiple=false;
                    825:         document.$formname.$sec_element.size=1;
                    826:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    827:     } else {
                    828:         if (numSections == 1) {
                    829:             document.$formname.$sec_element.multiple=false;
                    830:             document.$formname.$sec_element.size=1;
                    831:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    832:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    833:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    834:         } else {
                    835:             for (var i=0; i<numSections; i++) {
                    836:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    837:             }
                    838:             document.$formname.$sec_element.multiple=true
                    839:             if (numSections < 3) {
                    840:                 document.$formname.$sec_element.size=numSections;
                    841:             } else {
                    842:                 document.$formname.$sec_element.size=3;
                    843:             }
                    844:             document.$formname.$sec_element.options[0].selected = false
                    845:         }
                    846:     }
1.91      www       847: }
1.905     raeburn   848: 
                    849: function setRole(crstype) {
1.468     raeburn   850: |;
1.905     raeburn   851:     if ($role_element eq '') {
                    852:         $setsections .= '    return;
                    853: }
                    854: ';
                    855:     } else {
                    856:         $setsections .= qq|
                    857:     var elementLength = document.$formname.$role_element.length;
                    858:     var allroles = Array($rolestr);
                    859:     var courserolenames = Array($courserolestr);
                    860:     var communityrolenames = Array($communityrolestr);
                    861:     if (elementLength != undefined) {
                    862:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    863:             if (crstype == 'Course') {
                    864:                 return;
                    865:             } else {
                    866:                 allroles[5] = 'co';
                    867:                 for (var i=0; i<6; i++) {
                    868:                     document.$formname.$role_element.options[i].value = allroles[i];
                    869:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    870:                 }
                    871:             }
                    872:         } else {
                    873:             if (crstype == 'Community') {
                    874:                 return;
                    875:             } else {
                    876:                 allroles[5] = 'cc';
                    877:                 for (var i=0; i<6; i++) {
                    878:                     document.$formname.$role_element.options[i].value = allroles[i];
                    879:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    880:                 }
                    881:             }
                    882:         }
                    883:     }
                    884:     return;
                    885: }
                    886: |;
                    887:     }
1.1116    raeburn   888:     if ($credits_element) {
                    889:         $setsections .= qq|
                    890: function setCredits(defaultcredits) {
                    891:     document.$formname.$credits_element.value = defaultcredits;
                    892:     return;
                    893: }
                    894: |;
                    895:     }
1.468     raeburn   896:     return $setsections;
                    897: }
                    898: 
1.91      www       899: sub selectcourse_link {
1.909     raeburn   900:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    901:        $typeelement) = @_;
                    902:    my $type = $selecttype;
1.871     raeburn   903:    my $linktext = &mt('Select Course');
                    904:    if ($selecttype eq 'Community') {
1.909     raeburn   905:        $linktext = &mt('Select Community');
1.1239    raeburn   906:    } elsif ($selecttype eq 'Placement') {
                    907:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   908:    } elsif ($selecttype eq 'Course/Community') {
                    909:        $linktext = &mt('Select Course/Community');
1.909     raeburn   910:        $type = '';
1.1019    raeburn   911:    } elsif ($selecttype eq 'Select') {
                    912:        $linktext = &mt('Select');
                    913:        $type = '';
1.871     raeburn   914:    }
1.787     bisitz    915:    return '<span class="LC_nobreak">'
                    916:          ."<a href='"
                    917:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    918:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   919:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   920:          ."'>".$linktext.'</a>'
1.787     bisitz    921:          .'</span>';
1.74      www       922: }
1.42      matthew   923: 
1.653     raeburn   924: sub selectauthor_link {
                    925:    my ($form,$udom)=@_;
                    926:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    927:           &mt('Select Author').'</a>';
                    928: }
                    929: 
1.876     raeburn   930: sub selectuser_link {
1.881     raeburn   931:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   932:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   933:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   934:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   935:            ');">'.$linktext.'</a>';
1.876     raeburn   936: }
                    937: 
1.273     raeburn   938: sub check_uncheck_jscript {
                    939:     my $jscript = <<"ENDSCRT";
                    940: function checkAll(field) {
                    941:     if (field.length > 0) {
                    942:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   943:             if (!field[i].disabled) { 
                    944:                 field[i].checked = true;
                    945:             }
1.273     raeburn   946:         }
                    947:     } else {
1.1093    raeburn   948:         if (!field.disabled) { 
                    949:             field.checked = true;
                    950:         }
1.273     raeburn   951:     }
                    952: }
                    953:  
                    954: function uncheckAll(field) {
                    955:     if (field.length > 0) {
                    956:         for (i = 0; i < field.length; i++) {
                    957:             field[i].checked = false ;
1.543     albertel  958:         }
                    959:     } else {
1.273     raeburn   960:         field.checked = false ;
                    961:     }
                    962: }
                    963: ENDSCRT
                    964:     return $jscript;
                    965: }
                    966: 
1.656     www       967: sub select_timezone {
1.1387    raeburn   968:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
                    969:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
1.659     raeburn   970:    if ($includeempty) {
                    971:        $output .= '<option value=""';
                    972:        if (($selected eq '') || ($selected eq 'local')) {
                    973:            $output .= ' selected="selected" ';
                    974:        }
                    975:        $output .= '> </option>';
                    976:    }
1.657     raeburn   977:    my @timezones = DateTime::TimeZone->all_names;
                    978:    foreach my $tzone (@timezones) {
                    979:        $output.= '<option value="'.$tzone.'"';
                    980:        if ($tzone eq $selected) {
                    981:            $output.=' selected="selected"';
                    982:        }
                    983:        $output.=">$tzone</option>\n";
1.656     www       984:    }
                    985:    $output.="</select>";
                    986:    return $output;
                    987: }
1.273     raeburn   988: 
1.687     raeburn   989: sub select_datelocale {
1.1256    raeburn   990:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    991:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   992:     if ($includeempty) {
                    993:         $output .= '<option value=""';
                    994:         if ($selected eq '') {
                    995:             $output .= ' selected="selected" ';
                    996:         }
                    997:         $output .= '> </option>';
                    998:     }
1.1241    raeburn   999:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn  1000:     my (@possibles,%locale_names);
1.1241    raeburn  1001:     my @locales = DateTime::Locale->ids();
                   1002:     foreach my $id (@locales) {
                   1003:         if ($id ne '') {
                   1004:             my ($en_terr,$native_terr);
                   1005:             my $loc = DateTime::Locale->load($id);
                   1006:             if (ref($loc)) {
                   1007:                 $en_terr = $loc->name();
                   1008:                 $native_terr = $loc->native_name();
1.687     raeburn  1009:                 if (grep(/^en$/,@languages) || !@languages) {
                   1010:                     if ($en_terr ne '') {
                   1011:                         $locale_names{$id} = '('.$en_terr.')';
                   1012:                     } elsif ($native_terr ne '') {
                   1013:                         $locale_names{$id} = $native_terr;
                   1014:                     }
                   1015:                 } else {
                   1016:                     if ($native_terr ne '') {
                   1017:                         $locale_names{$id} = $native_terr.' ';
                   1018:                     } elsif ($en_terr ne '') {
                   1019:                         $locale_names{$id} = '('.$en_terr.')';
                   1020:                     }
                   1021:                 }
1.1220    raeburn  1022:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1023:                 push(@possibles,$id);
                   1024:             } 
1.687     raeburn  1025:         }
                   1026:     }
                   1027:     foreach my $item (sort(@possibles)) {
                   1028:         $output.= '<option value="'.$item.'"';
                   1029:         if ($item eq $selected) {
                   1030:             $output.=' selected="selected"';
                   1031:         }
                   1032:         $output.=">$item";
                   1033:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1034:             $output.='  '.$locale_names{$item};
1.687     raeburn  1035:         }
                   1036:         $output.="</option>\n";
                   1037:     }
                   1038:     $output.="</select>";
                   1039:     return $output;
                   1040: }
                   1041: 
1.792     raeburn  1042: sub select_language {
1.1256    raeburn  1043:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1044:     my %langchoices;
                   1045:     if ($includeempty) {
1.1117    raeburn  1046:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1047:     }
                   1048:     foreach my $id (&languageids()) {
                   1049:         my $code = &supportedlanguagecode($id);
                   1050:         if ($code) {
                   1051:             $langchoices{$code} = &plainlanguagedescription($id);
                   1052:         }
                   1053:     }
1.1117    raeburn  1054:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1055:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1056: }
                   1057: 
1.42      matthew  1058: =pod
1.36      matthew  1059: 
1.1088    foxr     1060: 
                   1061: =item * &list_languages()
                   1062: 
                   1063: Returns an array reference that is suitable for use in language prompters.
                   1064: Each array element is itself a two element array.  The first element
                   1065: is the language code.  The second element a descsriptiuon of the 
                   1066: language itself.  This is suitable for use in e.g.
                   1067: &Apache::edit::select_arg (once dereferenced that is).
                   1068: 
                   1069: =cut 
                   1070: 
                   1071: sub list_languages {
                   1072:     my @lang_choices;
                   1073: 
                   1074:     foreach my $id (&languageids()) {
                   1075: 	my $code = &supportedlanguagecode($id);
                   1076: 	if ($code) {
                   1077: 	    my $selector    = $supported_codes{$id};
                   1078: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1079: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1080: 	}
                   1081:     }
                   1082:     return \@lang_choices;
                   1083: }
                   1084: 
                   1085: =pod
                   1086: 
1.648     raeburn  1087: =item * &linked_select_forms(...)
1.36      matthew  1088: 
                   1089: linked_select_forms returns a string containing a <script></script> block
                   1090: and html for two <select> menus.  The select menus will be linked in that
                   1091: changing the value of the first menu will result in new values being placed
                   1092: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1093: order unless a defined order is provided.
1.36      matthew  1094: 
                   1095: linked_select_forms takes the following ordered inputs:
                   1096: 
                   1097: =over 4
                   1098: 
1.112     bowersj2 1099: =item * $formname, the name of the <form> tag
1.36      matthew  1100: 
1.112     bowersj2 1101: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1102: 
1.112     bowersj2 1103: =item * $firstdefault, the default value for the first menu
1.36      matthew  1104: 
1.112     bowersj2 1105: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1106: 
1.112     bowersj2 1107: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1108: 
1.112     bowersj2 1109: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1110: 
1.609     raeburn  1111: =item * $menuorder, the order of values in the first menu
                   1112: 
1.1115    raeburn  1113: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1114:         event for the first <select> tag
                   1115: 
                   1116: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1117:         event for the second <select> tag
                   1118: 
1.1245    raeburn  1119: =item * $suffix, to differentiate separate uses of select2data javascript
                   1120:         objects in a page.
                   1121: 
1.41      ng       1122: =back 
                   1123: 
1.36      matthew  1124: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1125: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1126: values for the first select menu.  The text that coincides with the 
1.41      ng       1127: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1128: and text for the second menu are given in the hash pointed to by 
                   1129: $menu{$choice1}->{'select2'}.  
                   1130: 
1.112     bowersj2 1131:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1132:                        default => "B3",
                   1133:                        select2 => { 
                   1134:                            B1 => "Choice B1",
                   1135:                            B2 => "Choice B2",
                   1136:                            B3 => "Choice B3",
                   1137:                            B4 => "Choice B4"
1.609     raeburn  1138:                            },
                   1139:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1140:                    },
                   1141:                A2 => { text =>"Choice A2" ,
                   1142:                        default => "C2",
                   1143:                        select2 => { 
                   1144:                            C1 => "Choice C1",
                   1145:                            C2 => "Choice C2",
                   1146:                            C3 => "Choice C3"
1.609     raeburn  1147:                            },
                   1148:                        order => ['C2','C1','C3'],
1.112     bowersj2 1149:                    },
                   1150:                A3 => { text =>"Choice A3" ,
                   1151:                        default => "D6",
                   1152:                        select2 => { 
                   1153:                            D1 => "Choice D1",
                   1154:                            D2 => "Choice D2",
                   1155:                            D3 => "Choice D3",
                   1156:                            D4 => "Choice D4",
                   1157:                            D5 => "Choice D5",
                   1158:                            D6 => "Choice D6",
                   1159:                            D7 => "Choice D7"
1.609     raeburn  1160:                            },
                   1161:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1162:                    }
                   1163:                );
1.36      matthew  1164: 
                   1165: =cut
                   1166: 
                   1167: sub linked_select_forms {
                   1168:     my ($formname,
                   1169:         $middletext,
                   1170:         $firstdefault,
                   1171:         $firstselectname,
                   1172:         $secondselectname, 
1.609     raeburn  1173:         $hashref,
                   1174:         $menuorder,
1.1115    raeburn  1175:         $onchangefirst,
1.1245    raeburn  1176:         $onchangesecond,
1.1450    raeburn  1177:         $suffix,
                   1178:         $haslabel
1.36      matthew  1179:         ) = @_;
                   1180:     my $second = "document.$formname.$secondselectname";
                   1181:     my $first = "document.$formname.$firstselectname";
                   1182:     # output the javascript to do the changing
                   1183:     my $result = '';
1.776     bisitz   1184:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1185:     $result.="// <![CDATA[\n";
1.1245    raeburn  1186:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1187:     $" = '","';
                   1188:     my $debug = '';
                   1189:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1190:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1191:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1192:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1193:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1194:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1195:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1196:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1197:         }
1.36      matthew  1198:         $result.="\"@s2values\");\n";
1.1245    raeburn  1199:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1200:         my @s2texts;
                   1201:         foreach my $value (@s2values) {
1.1263    raeburn  1202:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1203:         }
                   1204:         $result.="\"@s2texts\");\n";
                   1205:     }
                   1206:     $"=' ';
                   1207:     $result.= <<"END";
                   1208: 
1.1245    raeburn  1209: function select1${suffix}_changed() {
1.36      matthew  1210:     // Determine new choice
1.1245    raeburn  1211:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1212:     // update select2
1.1245    raeburn  1213:     var values     = select2data${suffix}[newvalue].values;
                   1214:     var texts      = select2data${suffix}[newvalue].texts;
                   1215:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1216:     var i;
                   1217:     // out with the old
1.1245    raeburn  1218:     $second.options.length = 0;
                   1219:     // in with the new
1.36      matthew  1220:     for (i=0;i<values.length; i++) {
                   1221:         $second.options[i] = new Option(values[i]);
1.143     matthew  1222:         $second.options[i].value = values[i];
1.36      matthew  1223:         $second.options[i].text = texts[i];
                   1224:         if (values[i] == select2def) {
                   1225:             $second.options[i].selected = true;
                   1226:         }
                   1227:     }
                   1228: }
1.824     bisitz   1229: // ]]>
1.36      matthew  1230: </script>
                   1231: END
                   1232:     # output the initial values for the selection lists
1.1245    raeburn  1233:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1234:     my @order = sort(keys(%{$hashref}));
                   1235:     if (ref($menuorder) eq 'ARRAY') {
                   1236:         @order = @{$menuorder};
                   1237:     }
                   1238:     foreach my $value (@order) {
1.36      matthew  1239:         $result.="    <option value=\"$value\" ";
1.253     albertel 1240:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1241:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1242:     }
                   1243:     $result .= "</select>\n";
1.1450    raeburn  1244:     if ($haslabel) {
                   1245:         $result .= '</label>';
                   1246:     }
1.1400    raeburn  1247:     my %select2;
                   1248:     if (ref($hashref->{$firstdefault}) eq 'HASH') {
                   1249:         if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
                   1250:             %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1251:         }
                   1252:     }
1.1450    raeburn  1253:     if ($middletext ne '') {
1.1452    raeburn  1254:         $result .= '<label>'.$middletext;
1.1450    raeburn  1255:     }
1.1115    raeburn  1256:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1257:     if ($onchangesecond) {
                   1258:         $result .= ' onchange="'.$onchangesecond.'"';
                   1259:     }
                   1260:     $result .= ">\n";
1.36      matthew  1261:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1262:     
                   1263:     my @secondorder = sort(keys(%select2));
                   1264:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1265:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1266:     }
                   1267:     foreach my $value (@secondorder) {
1.36      matthew  1268:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1269:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1270:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1271:     }
                   1272:     $result .= "</select>\n";
1.1450    raeburn  1273:     if ($middletext ne '') {
                   1274:         $result .= '</label>';
                   1275:     }
1.36      matthew  1276:     #    return $debug;
                   1277:     return $result;
                   1278: }   #  end of sub linked_select_forms {
                   1279: 
1.45      matthew  1280: =pod
1.44      bowersj2 1281: 
1.1381    raeburn  1282: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1283: 
1.112     bowersj2 1284: Returns a string corresponding to an HTML link to the given help
                   1285: $topic, where $topic corresponds to the name of a .tex file in
                   1286: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1287: spaces. 
                   1288: 
                   1289: $text will optionally be linked to the same topic, allowing you to
                   1290: link text in addition to the graphic. If you do not want to link
                   1291: text, but wish to specify one of the later parameters, pass an
                   1292: empty string. 
                   1293: 
                   1294: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1295: the link will not open a new window. If false, the link will open
                   1296: a new window using Javascript. (Default is false.) 
                   1297: 
                   1298: $width and $height are optional numerical parameters that will
                   1299: override the width and height of the popped up window, which may
1.973     raeburn  1300: be useful for certain help topics with big pictures included.
                   1301: 
                   1302: $imgid is the id of the img tag used for the help icon. This may be
                   1303: used in a javascript call to switch the image src.  See 
                   1304: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1305: 
1.1381    raeburn  1306: $links_target will optionally be set to a target (_top, _parent or _self).
                   1307: 
1.44      bowersj2 1308: =cut
                   1309: 
                   1310: sub help_open_topic {
1.1381    raeburn  1311:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1312:     $text = "" if (not defined $text);
1.44      bowersj2 1313:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1314:     $width = 500 if (not defined $width);
1.44      bowersj2 1315:     $height = 400 if (not defined $height);
                   1316:     my $filename = $topic;
                   1317:     $filename =~ s/ /_/g;
                   1318: 
1.48      bowersj2 1319:     my $template = "";
                   1320:     my $link;
1.572     banghart 1321:     
1.159     www      1322:     $topic=~s/\W/\_/g;
1.44      bowersj2 1323: 
1.572     banghart 1324:     if (!$stayOnPage) {
1.1033    www      1325: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1326:     } elsif ($stayOnPage eq 'popup') {
                   1327:         $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 1328:     } else {
1.48      bowersj2 1329: 	$link = "/adm/help/${filename}.hlp";
                   1330:     }
                   1331: 
                   1332:     # Add the text
1.1314    raeburn  1333:     my $target = ' target="_top"';
1.1381    raeburn  1334:     if ($links_target) {
                   1335:         $target = ' target="'.$links_target.'"';
                   1336:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1337:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1338:         $target = '';
1.1378    raeburn  1339:     }
1.1380    raeburn  1340:     if ($text ne "") {
1.763     bisitz   1341: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1342:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1343:                   .$text.'</a>';
1.48      bowersj2 1344:     }
                   1345: 
1.763     bisitz   1346:     # (Always) Add the graphic
1.179     matthew  1347:     my $title = &mt('Online Help');
1.667     raeburn  1348:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1349:     if ($imgid ne '') {
                   1350:         $imgid = ' id="'.$imgid.'"';
                   1351:     }
1.1314    raeburn  1352:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1353:               .'<img src="'.$helpicon.'" border="0"'
                   1354:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1355:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1356:               .' /></a>';
                   1357:     if ($text ne "") {	
                   1358:         $template.='</span>';
                   1359:     }
1.44      bowersj2 1360:     return $template;
                   1361: 
1.106     bowersj2 1362: }
                   1363: 
                   1364: # This is a quicky function for Latex cheatsheet editing, since it 
                   1365: # appears in at least four places
                   1366: sub helpLatexCheatsheet {
1.1037    www      1367:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1368:     my $out;
1.106     bowersj2 1369:     my $addOther = '';
1.732     raeburn  1370:     if ($topic) {
1.1037    www      1371: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1372:     }
                   1373:     $out = '<span>' # Start cheatsheet
                   1374: 	  .$addOther
                   1375:           .'<span>'
1.1037    www      1376: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1377: 	  .'</span> <span>'
1.1037    www      1378: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1379: 	  .'</span>';
1.732     raeburn  1380:     unless ($not_author) {
1.1186    kruse    1381:         $out .= '<span>'
                   1382:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1383:                .'</span> <span>'
1.1424    raeburn  1384:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.763     bisitz   1385: 	       .'</span>';
1.732     raeburn  1386:     }
1.763     bisitz   1387:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1388:     return $out;
1.172     www      1389: }
                   1390: 
1.430     albertel 1391: sub general_help {
                   1392:     my $helptopic='Student_Intro';
                   1393:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1394: 	$helptopic='Authoring_Intro';
1.907     raeburn  1395:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1396: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1397:     } elsif ($env{'request.role'}=~/^dc/) {
                   1398:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1399:     }
                   1400:     return $helptopic;
                   1401: }
                   1402: 
                   1403: sub update_help_link {
                   1404:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1405:     my $origurl = $ENV{'REQUEST_URI'};
                   1406:     $origurl=~s|^/~|/priv/|;
                   1407:     my $timestamp = time;
                   1408:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1409:         $$datum = &escape($$datum);
                   1410:     }
                   1411: 
                   1412:     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";
                   1413:     my $output .= <<"ENDOUTPUT";
                   1414: <script type="text/javascript">
1.824     bisitz   1415: // <![CDATA[
1.430     albertel 1416: banner_link = '$banner_link';
1.824     bisitz   1417: // ]]>
1.430     albertel 1418: </script>
                   1419: ENDOUTPUT
                   1420:     return $output;
                   1421: }
                   1422: 
                   1423: # now just updates the help link and generates a blue icon
1.193     raeburn  1424: sub help_open_menu {
1.1381    raeburn  1425:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1426: 	= @_;    
1.949     droeschl 1427:     $stayOnPage = 1;
1.430     albertel 1428:     my $output;
                   1429:     if ($component_help) {
                   1430: 	if (!$text) {
                   1431: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1381    raeburn  1432: 				       $width,$height,'',$links_target);
1.430     albertel 1433: 	} else {
                   1434: 	    my $help_text;
                   1435: 	    $help_text=&unescape($topic);
                   1436: 	    $output='<table><tr><td>'.
                   1437: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1381    raeburn  1438: 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1439: 	}
                   1440:     }
                   1441:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1442:     return $output.$banner_link;
                   1443: }
                   1444: 
                   1445: sub top_nav_help {
1.1369    raeburn  1446:     my ($text,$linkattr) = @_;
1.436     albertel 1447:     $text = &mt($text);
1.949     droeschl 1448:     my $stay_on_page = 1;
                   1449: 
1.1168    raeburn  1450:     my ($link,$banner_link);
                   1451:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1452:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1453: 	                         : "javascript:helpMenu('open')";
                   1454:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1455:     }
1.201     raeburn  1456:     my $title = &mt('Get help');
1.1168    raeburn  1457:     if ($link) {
                   1458:         return <<"END";
1.436     albertel 1459: $banner_link
1.1369    raeburn  1460: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1461: END
1.1168    raeburn  1462:     } else {
                   1463:         return '&nbsp;'.$text.'&nbsp;';
                   1464:     }
1.436     albertel 1465: }
                   1466: 
                   1467: sub help_menu_js {
1.1154    raeburn  1468:     my ($httphost) = @_;
1.949     droeschl 1469:     my $stayOnPage = 1;
1.436     albertel 1470:     my $width = 620;
                   1471:     my $height = 600;
1.430     albertel 1472:     my $helptopic=&general_help();
1.1154    raeburn  1473:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1474:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1475:     my $start_page =
                   1476:         &Apache::loncommon::start_page('Help Menu', undef,
                   1477: 				       {'frameset'    => 1,
                   1478: 					'js_ready'    => 1,
1.1154    raeburn  1479:                                         'use_absolute' => $httphost,
1.331     albertel 1480: 					'add_entries' => {
1.1168    raeburn  1481: 					    'border' => '0', 
1.579     raeburn  1482: 					    'rows'   => "110,*",},});
1.331     albertel 1483:     my $end_page =
                   1484:         &Apache::loncommon::end_page({'frameset' => 1,
                   1485: 				      'js_ready' => 1,});
                   1486: 
1.436     albertel 1487:     my $template .= <<"ENDTEMPLATE";
                   1488: <script type="text/javascript">
1.877     bisitz   1489: // <![CDATA[
1.253     albertel 1490: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1491: var banner_link = '';
1.243     raeburn  1492: function helpMenu(target) {
                   1493:     var caller = this;
                   1494:     if (target == 'open') {
                   1495:         var newWindow = null;
                   1496:         try {
1.262     albertel 1497:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1498:         }
                   1499:         catch(error) {
                   1500:             writeHelp(caller);
                   1501:             return;
                   1502:         }
                   1503:         if (newWindow) {
                   1504:             caller = newWindow;
                   1505:         }
1.193     raeburn  1506:     }
1.243     raeburn  1507:     writeHelp(caller);
                   1508:     return;
                   1509: }
                   1510: function writeHelp(caller) {
1.1168    raeburn  1511:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1512:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1513:     caller.document.close();
                   1514:     caller.focus();
1.193     raeburn  1515: }
1.877     bisitz   1516: // END LON-CAPA Internal -->
1.253     albertel 1517: // ]]>
1.436     albertel 1518: </script>
1.193     raeburn  1519: ENDTEMPLATE
                   1520:     return $template;
                   1521: }
                   1522: 
1.172     www      1523: sub help_open_bug {
                   1524:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1525:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1526:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1527:     $text = "" if (not defined $text);
                   1528: 	$stayOnPage=1;
1.184     albertel 1529:     $width = 600 if (not defined $width);
                   1530:     $height = 600 if (not defined $height);
1.172     www      1531: 
                   1532:     $topic=~s/\W+/\+/g;
                   1533:     my $link='';
                   1534:     my $template='';
1.379     albertel 1535:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1536: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1537:     if (!$stayOnPage)
                   1538:     {
                   1539: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1540:     }
                   1541:     else
                   1542:     {
                   1543: 	$link = $url;
                   1544:     }
1.1314    raeburn  1545: 
1.1382    raeburn  1546:     my $target = '_top';
                   1547:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1548:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1549:         $target = '_blank';
1.1378    raeburn  1550:     }
1.1382    raeburn  1551: 
1.172     www      1552:     # Add the text
                   1553:     if ($text ne "")
                   1554:     {
                   1555: 	$template .= 
                   1556:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1382    raeburn  1557:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1558:     }
                   1559: 
                   1560:     # Add the graphic
1.179     matthew  1561:     my $title = &mt('Report a Bug');
1.215     albertel 1562:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1563:     $template .= <<"ENDTEMPLATE";
1.1382    raeburn  1564:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1565: ENDTEMPLATE
                   1566:     if ($text ne '') { $template.='</td></tr></table>' };
                   1567:     return $template;
                   1568: 
                   1569: }
                   1570: 
                   1571: sub help_open_faq {
                   1572:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1573:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1574:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1575:     $text = "" if (not defined $text);
                   1576: 	$stayOnPage=1;
                   1577:     $width = 350 if (not defined $width);
                   1578:     $height = 400 if (not defined $height);
                   1579: 
                   1580:     $topic=~s/\W+/\+/g;
                   1581:     my $link='';
                   1582:     my $template='';
                   1583:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1584:     if (!$stayOnPage)
                   1585:     {
                   1586: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1587:     }
                   1588:     else
                   1589:     {
                   1590: 	$link = $url;
                   1591:     }
                   1592: 
                   1593:     # Add the text
                   1594:     if ($text ne "")
                   1595:     {
                   1596: 	$template .= 
1.173     www      1597:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1598:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1599:     }
                   1600: 
                   1601:     # Add the graphic
1.179     matthew  1602:     my $title = &mt('View the FAQ');
1.215     albertel 1603:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1604:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1605:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1606: ENDTEMPLATE
                   1607:     if ($text ne '') { $template.='</td></tr></table>' };
                   1608:     return $template;
                   1609: 
1.44      bowersj2 1610: }
1.37      matthew  1611: 
1.180     matthew  1612: ###############################################################
                   1613: ###############################################################
                   1614: 
1.45      matthew  1615: =pod
                   1616: 
1.648     raeburn  1617: =item * &change_content_javascript():
1.256     matthew  1618: 
                   1619: This and the next function allow you to create small sections of an
                   1620: otherwise static HTML page that you can update on the fly with
                   1621: Javascript, even in Netscape 4.
                   1622: 
                   1623: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1624: must be written to the HTML page once. It will prove the Javascript
                   1625: function "change(name, content)". Calling the change function with the
                   1626: name of the section 
                   1627: you want to update, matching the name passed to C<changable_area>, and
                   1628: the new content you want to put in there, will put the content into
                   1629: that area.
                   1630: 
                   1631: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1632: to contain room for the original contents. You need to "make space"
                   1633: for whatever changes you wish to make, and be B<sure> to check your
                   1634: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1635: it's adequate for updating a one-line status display, but little more.
                   1636: This script will set the space to 100% width, so you only need to
                   1637: worry about height in Netscape 4.
                   1638: 
                   1639: Modern browsers are much less limiting, and if you can commit to the
                   1640: user not using Netscape 4, this feature may be used freely with
                   1641: pretty much any HTML.
                   1642: 
                   1643: =cut
                   1644: 
                   1645: sub change_content_javascript {
                   1646:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1647:     if ($env{'browser.type'} eq 'netscape' &&
                   1648: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1649: 	return (<<NETSCAPE4);
                   1650: 	function change(name, content) {
                   1651: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1652: 	    doc.open();
                   1653: 	    doc.write(content);
                   1654: 	    doc.close();
                   1655: 	}
                   1656: NETSCAPE4
                   1657:     } else {
                   1658: 	# Otherwise, we need to use semi-standards-compliant code
                   1659: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1660: 	# is really scary, and every useful browser supports it
                   1661: 	return (<<DOMBASED);
                   1662: 	function change(name, content) {
                   1663: 	    element = document.getElementById(name);
                   1664: 	    element.innerHTML = content;
                   1665: 	}
                   1666: DOMBASED
                   1667:     }
                   1668: }
                   1669: 
                   1670: =pod
                   1671: 
1.648     raeburn  1672: =item * &changable_area($name,$origContent):
1.256     matthew  1673: 
                   1674: This provides a "changable area" that can be modified on the fly via
                   1675: the Javascript code provided in C<change_content_javascript>. $name is
                   1676: the name you will use to reference the area later; do not repeat the
                   1677: same name on a given HTML page more then once. $origContent is what
                   1678: the area will originally contain, which can be left blank.
                   1679: 
                   1680: =cut
                   1681: 
                   1682: sub changable_area {
                   1683:     my ($name, $origContent) = @_;
                   1684: 
1.258     albertel 1685:     if ($env{'browser.type'} eq 'netscape' &&
                   1686: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1687: 	# If this is netscape 4, we need to use the Layer tag
                   1688: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1689:     } else {
                   1690: 	return "<span id='$name'>$origContent</span>";
                   1691:     }
                   1692: }
                   1693: 
                   1694: =pod
                   1695: 
1.648     raeburn  1696: =item * &viewport_geometry_js 
1.590     raeburn  1697: 
                   1698: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1699: 
                   1700: =cut
                   1701: 
                   1702: 
                   1703: sub viewport_geometry_js { 
                   1704:     return <<"GEOMETRY";
                   1705: var Geometry = {};
                   1706: function init_geometry() {
                   1707:     if (Geometry.init) { return };
                   1708:     Geometry.init=1;
                   1709:     if (window.innerHeight) {
                   1710:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1711:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1712:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1713:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1714:     }
                   1715:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1716:         Geometry.getViewportHeight =
                   1717:             function() { return document.documentElement.clientHeight; };
                   1718:         Geometry.getViewportWidth =
                   1719:             function() { return document.documentElement.clientWidth; };
                   1720: 
                   1721:         Geometry.getHorizontalScroll =
                   1722:             function() { return document.documentElement.scrollLeft; };
                   1723:         Geometry.getVerticalScroll =
                   1724:             function() { return document.documentElement.scrollTop; };
                   1725:     }
                   1726:     else if (document.body.clientHeight) {
                   1727:         Geometry.getViewportHeight =
                   1728:             function() { return document.body.clientHeight; };
                   1729:         Geometry.getViewportWidth =
                   1730:             function() { return document.body.clientWidth; };
                   1731:         Geometry.getHorizontalScroll =
                   1732:             function() { return document.body.scrollLeft; };
                   1733:         Geometry.getVerticalScroll =
                   1734:             function() { return document.body.scrollTop; };
                   1735:     }
                   1736: }
                   1737: 
                   1738: GEOMETRY
                   1739: }
                   1740: 
                   1741: =pod
                   1742: 
1.648     raeburn  1743: =item * &viewport_size_js()
1.590     raeburn  1744: 
                   1745: 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. 
                   1746: 
                   1747: =cut
                   1748: 
                   1749: sub viewport_size_js {
                   1750:     my $geometry = &viewport_geometry_js();
                   1751:     return <<"DIMS";
                   1752: 
                   1753: $geometry
                   1754: 
                   1755: function getViewportDims(width,height) {
                   1756:     init_geometry();
                   1757:     width.value = Geometry.getViewportWidth();
                   1758:     height.value = Geometry.getViewportHeight();
                   1759:     return;
                   1760: }
                   1761: 
                   1762: DIMS
                   1763: }
                   1764: 
                   1765: =pod
                   1766: 
1.648     raeburn  1767: =item * &resize_textarea_js()
1.565     albertel 1768: 
                   1769: emits the needed javascript to resize a textarea to be as big as possible
                   1770: 
                   1771: creates a function resize_textrea that takes two IDs first should be
                   1772: the id of the element to resize, second should be the id of a div that
                   1773: surrounds everything that comes after the textarea, this routine needs
                   1774: to be attached to the <body> for the onload and onresize events.
                   1775: 
                   1776: =cut
                   1777: 
                   1778: sub resize_textarea_js {
1.590     raeburn  1779:     my $geometry = &viewport_geometry_js();
1.565     albertel 1780:     return <<"RESIZE";
                   1781:     <script type="text/javascript">
1.824     bisitz   1782: // <![CDATA[
1.590     raeburn  1783: $geometry
1.565     albertel 1784: 
1.588     albertel 1785: function getX(element) {
                   1786:     var x = 0;
                   1787:     while (element) {
                   1788: 	x += element.offsetLeft;
                   1789: 	element = element.offsetParent;
                   1790:     }
                   1791:     return x;
                   1792: }
                   1793: function getY(element) {
                   1794:     var y = 0;
                   1795:     while (element) {
                   1796: 	y += element.offsetTop;
                   1797: 	element = element.offsetParent;
                   1798:     }
                   1799:     return y;
                   1800: }
                   1801: 
                   1802: 
1.565     albertel 1803: function resize_textarea(textarea_id,bottom_id) {
                   1804:     init_geometry();
                   1805:     var textarea        = document.getElementById(textarea_id);
                   1806:     //alert(textarea);
                   1807: 
1.588     albertel 1808:     var textarea_top    = getY(textarea);
1.565     albertel 1809:     var textarea_height = textarea.offsetHeight;
                   1810:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1811:     var bottom_top      = getY(bottom);
1.565     albertel 1812:     var bottom_height   = bottom.offsetHeight;
                   1813:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1814:     var fudge           = 23;
1.565     albertel 1815:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1816:     if (new_height < 300) {
                   1817: 	new_height = 300;
                   1818:     }
                   1819:     textarea.style.height=new_height+'px';
                   1820: }
1.824     bisitz   1821: // ]]>
1.565     albertel 1822: </script>
                   1823: RESIZE
                   1824: 
                   1825: }
                   1826: 
1.1205    golterma 1827: sub colorfuleditor_js {
1.1248    raeburn  1828:     my $browse_or_search;
                   1829:     my $respath;
                   1830:     my ($cnum,$cdom) = &crsauthor_url();
                   1831:     if ($cnum) {
                   1832:         $respath = "/res/$cdom/$cnum/";
                   1833:         my %js_lt = &Apache::lonlocal::texthash(
                   1834:             sunm => 'Sub-directory name',
                   1835:             save => 'Save page to make this permanent',
                   1836:         );
                   1837:         &js_escape(\%js_lt);
1.1400    raeburn  1838:         my $showfile_js = &show_crsfiles_js();
1.1248    raeburn  1839:         $browse_or_search = <<"END";
                   1840: 
1.1400    raeburn  1841:     $showfile_js
                   1842: 
1.1248    raeburn  1843:     function toggleChooser(form,element,titleid,only,search) {
                   1844:         var disp = 'none';
                   1845:         if (document.getElementById('chooser_'+element)) {
                   1846:             var curr = document.getElementById('chooser_'+element).style.display;
                   1847:             if (curr == 'none') {
                   1848:                 disp='inline';
                   1849:                 if (form.elements['chooser_'+element].length) {
                   1850:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1851:                         form.elements['chooser_'+element][i].checked = false;
                   1852:                     }
                   1853:                 }
                   1854:                 toggleResImport(form,element);
                   1855:             }
                   1856:             document.getElementById('chooser_'+element).style.display = disp;
1.1400    raeburn  1857:             var dirsel = '';
                   1858:             var filesel = '';
                   1859:             if (document.getElementById('chooser_'+element+'_crsres')) {
                   1860:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1861:                 if (currcrsres == 'none') {
                   1862:                     dirsel = 'coursepath_'+element;
                   1863:                     var filesel = 'coursefile_'+element;
                   1864:                     var include;
                   1865:                     if (document.getElementById('crsres_include_'+element)) {
                   1866:                         include = document.getElementById('crsres_include_'+element).value;
                   1867:                     }
1.1402    raeburn  1868:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
1.1400    raeburn  1869:                 }
                   1870:             }
                   1871:             if (document.getElementById('chooser_'+element+'_upload')) {
                   1872:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
                   1873:                 if (currcrsupload == 'none') {
                   1874:                     dirsel = 'crsauthorpath_'+element;
                   1875:                     filesel = '';
1.1402    raeburn  1876:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
1.1400    raeburn  1877:                 }
                   1878:             }
1.1248    raeburn  1879:         }
                   1880:     }
                   1881: 
1.1400    raeburn  1882:     function toggleCrsFile(form,element) {
1.1248    raeburn  1883:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1884:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1885:             if (curr == 'none') {
1.1400    raeburn  1886:                 if (document.getElementById('coursepath_'+element)) {
                   1887:                     var numdirs;
                   1888:                     if (document.getElementById('coursepath_'+element).length) {
                   1889:                         numdirs = document.getElementById('coursepath_'+element).length;
                   1890:                     }
1.1402    raeburn  1891:                     if ((document.getElementById('hascrsres_'+element)) &&
                   1892:                         (document.getElementById('nocrsres_'+element))) {
                   1893:                         if (numdirs) {
                   1894:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
                   1895:                             document.getElementById('nocrsres_'+element).style.display='none';
                   1896:                         } else {
                   1897:                             document.getElementById('hascrsres_'+element).style.display='none';
                   1898:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
                   1899:                         }
                   1900:                     }
1.1248    raeburn  1901:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1902:                     if (numdirs > 1) {
1.1400    raeburn  1903:                         var selelem = form.elements['coursefile_'+element];
                   1904:                         var i, len = selelem.options.length -1;
                   1905:                         if (len >=0) {
                   1906:                             for (i = len; i >= 0; i--) {
                   1907:                                 selelem.remove(i);
                   1908:                             }
                   1909:                             selelem.options[0] = new Option('','');
                   1910:                         }
1.1248    raeburn  1911:                     }
                   1912:                 }
1.1400    raeburn  1913:             }
1.1248    raeburn  1914:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1915:         }
                   1916:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1917:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1918:             if (document.getElementById('uploadcrsres_'+element)) {
                   1919:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1920:             }
                   1921:         }
                   1922:         return;
                   1923:     }
                   1924: 
1.1400    raeburn  1925:     function toggleCrsUpload(form,element) {
1.1248    raeburn  1926:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1927:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1928:         }
                   1929:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1930:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1931:             if (curr == 'none') {
1.1400    raeburn  1932:                 form.elements['newsubdir_'+element][0].checked = true;
                   1933:                 toggleNewsubdir(form,element);
                   1934:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1935:                 if (document.getElementById('uploadcrsres_'+element)) {
                   1936:                     document.getElementById('uploadcrsres_'+element).value = '';
1.1248    raeburn  1937:                 }
                   1938:             }
                   1939:         }
                   1940:         return;
                   1941:     }
                   1942: 
                   1943:     function toggleResImport(form,element) {
                   1944:         var choices = new Array('crsres','upload');
                   1945:         for (var i=0; i<choices.length; i++) {
                   1946:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1947:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1948:             }
                   1949:         }
                   1950:     }
                   1951: 
                   1952:     function toggleNewsubdir(form,element) {
                   1953:         var newsub = form.elements['newsubdir_'+element];
                   1954:         if (newsub) {
                   1955:             if (newsub.length) {
                   1956:                 for (var j=0; j<newsub.length; j++) {
                   1957:                     if (newsub[j].checked) {
                   1958:                         if (document.getElementById('newsubdirname_'+element)) {
                   1959:                             if (newsub[j].value == '1') {
                   1960:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1961:                                 if (document.getElementById('newsubdir_'+element)) {
                   1962:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1963:                                 }
                   1964:                             } else {
                   1965:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1966:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1967:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1968:                             }
                   1969:                         }
                   1970:                         break; 
                   1971:                     }
                   1972:                 }
                   1973:             }
                   1974:         }
                   1975:     }
                   1976: 
                   1977:     function updateCrsFile(form,element) {
                   1978:         var directory = form.elements['coursepath_'+element];
                   1979:         var filename = form.elements['coursefile_'+element];
                   1980:         var path = directory.options[directory.selectedIndex].value;
                   1981:         var file = filename.options[filename.selectedIndex].value;
1.1400    raeburn  1982:         if (file != '') {
                   1983:             form.elements[element].value = '$respath';
                   1984:             if (path == '/') {
                   1985:                 form.elements[element].value += file;
                   1986:             } else {
                   1987:                 form.elements[element].value += path+'/'+file;
                   1988:             }
                   1989:             unClean();
                   1990:             if (document.getElementById('previewimg_'+element)) {
                   1991:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1992:                 var newsrc = document.getElementById('previewimg_'+element).src; 
                   1993:             }
                   1994:             if (document.getElementById('showimg_'+element)) {
                   1995:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1996:             }
1.1248    raeburn  1997:         }
                   1998:         toggleChooser(form,element);
                   1999:         return;
                   2000:     }
                   2001: 
                   2002:     function uploadDone(suffix,name) {
                   2003:         if (name) {
                   2004: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   2005:             unClean();
                   2006:             toggleChooser(document.forms["lonhomework"],suffix);
                   2007:         }
                   2008:     }
                   2009: 
                   2010: \$(document).ready(function(){
                   2011: 
                   2012:     \$(document).delegate('form :submit', 'click', function( event ) {
                   2013:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   2014:             var buttonId = this.id;
                   2015:             var suffix = buttonId.toString();
                   2016:             suffix = suffix.replace(/^crsupload_/,'');
                   2017:             event.preventDefault();
                   2018:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   2019:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   2020:             \$(this.form).submit();
                   2021:             document.lonhomework.target = '';
                   2022:             if (document.getElementById('crsuploadto_'+suffix)) {
                   2023:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   2024:             }
                   2025:             return false;
                   2026:         }
                   2027:     });
                   2028: });
                   2029: END
                   2030:     }
1.1205    golterma 2031:     return <<"COLORFULEDIT"
                   2032: <script type="text/javascript">
                   2033: // <![CDATA[>
                   2034:     function fold_box(curDepth, lastresource){
                   2035: 
                   2036:     // we need a list because there can be several blocks you need to fold in one tag
                   2037:         var block = document.getElementsByName('foldblock_'+curDepth);
                   2038:     // but there is only one folding button per tag
                   2039:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   2040: 
                   2041:         if(block.item(0).style.display == 'none'){
                   2042: 
                   2043:             foldbutton.value = '@{[&mt("Hide")]}';
                   2044:             for (i = 0; i < block.length; i++){
                   2045:                 block.item(i).style.display = '';
                   2046:             }
                   2047:         }else{
                   2048: 
                   2049:             foldbutton.value = '@{[&mt("Show")]}';
                   2050:             for (i = 0; i < block.length; i++){
                   2051:                 // block.item(i).style.visibility = 'collapse';
                   2052:                 block.item(i).style.display = 'none';
                   2053:             }
                   2054:         };
                   2055:         saveState(lastresource);
                   2056:     }
                   2057: 
                   2058:     function saveState (lastresource) {
                   2059: 
                   2060:         var tag_list = getTagList();
                   2061:         if(tag_list != null){
                   2062:             var timestamp = new Date().getTime();
                   2063:             var key = lastresource;
                   2064: 
                   2065:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   2066:             // starting with timestamp
                   2067:             var value = timestamp+';';
                   2068: 
                   2069:             // building the list of key-value pairs
                   2070:             for(var i = 0; i < tag_list.length; i++){
                   2071:                 value += tag_list[i]+',';
                   2072:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   2073:             }
                   2074: 
                   2075:             // only iterate whole storage if nothing to override
                   2076:             if(localStorage.getItem(key) == null){        
                   2077: 
                   2078:                 // prevent storage from growing large
                   2079:                 if(localStorage.length > 50){
                   2080:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2081:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2082:                     var oldest_key;
                   2083:                     
                   2084:                     for(var i = 1; i < localStorage.length; i++){
                   2085:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2086:                             oldest_key = localStorage.key(i);
                   2087:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2088:                         }
                   2089:                     }
                   2090:                     localStorage.removeItem(oldest_key);
                   2091:                 }
                   2092:             }
                   2093:             localStorage.setItem(key,value);
                   2094:         }
                   2095:     }
                   2096: 
                   2097:     // restore folding status of blocks (on page load)
                   2098:     function restoreState (lastresource) {
                   2099:         if(localStorage.getItem(lastresource) != null){
                   2100:             var key = lastresource;
                   2101:             var value = localStorage.getItem(key);
                   2102:             var regex_delTimestamp = /^\d+;/;
                   2103: 
                   2104:             value.replace(regex_delTimestamp, '');
                   2105: 
                   2106:             var valueArr = value.split(';');
                   2107:             var pairs;
                   2108:             var elements;
                   2109:             for (var i = 0; i < valueArr.length; i++){
                   2110:                 pairs = valueArr[i].split(',');
                   2111:                 elements = document.getElementsByName(pairs[0]);
                   2112: 
                   2113:                 for (var j = 0; j < elements.length; j++){  
                   2114:                     elements[j].style.display = pairs[1];
                   2115:                     if (pairs[1] == "none"){
                   2116:                         var regex_id = /([_\\d]+)\$/;
                   2117:                         regex_id.exec(pairs[0]);
                   2118:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2119:                     }
                   2120:                 }
                   2121:             }
                   2122:         }
                   2123:     }
                   2124: 
                   2125:     function getTagList () {
                   2126:         
                   2127:         var stringToSearch = document.lonhomework.innerHTML;
                   2128: 
                   2129:         var ret = new Array();
                   2130:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2131:         var tag_list = stringToSearch.match(regex_findBlock);
                   2132: 
                   2133:         if(tag_list != null){
                   2134:             for(var i = 0; i < tag_list.length; i++){            
                   2135:                 ret.push(tag_list[i].replace(/"/, ''));
                   2136:             }
                   2137:         }
                   2138:         return ret;
                   2139:     }
                   2140: 
                   2141:     function saveScrollPosition (resource) {
                   2142:         var tag_list = getTagList();
                   2143: 
                   2144:         // we dont always want to jump to the first block
                   2145:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2146:         if(\$(window).scrollTop() > 170){
                   2147:             if(tag_list != null){
                   2148:                 var result;
                   2149:                 for(var i = 0; i < tag_list.length; i++){
                   2150:                     if(isElementInViewport(tag_list[i])){
                   2151:                         result += tag_list[i]+';';
                   2152:                     }
                   2153:                 }
                   2154:                 sessionStorage.setItem('anchor_'+resource, result);
                   2155:             }
                   2156:         } else {
                   2157:             // we dont need to save zero, just delete the item to leave everything tidy
                   2158:             sessionStorage.removeItem('anchor_'+resource);
                   2159:         }
                   2160:     }
                   2161: 
                   2162:     function restoreScrollPosition(resource){
                   2163: 
                   2164:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2165:         if(elem != null){
                   2166:             var tag_list = elem.split(';');
                   2167:             var elem_list;
                   2168: 
                   2169:             for(var i = 0; i < tag_list.length; i++){
                   2170:                 elem_list = document.getElementsByName(tag_list[i]);
                   2171:                 
                   2172:                 if(elem_list.length > 0){
                   2173:                     elem = elem_list[0];
                   2174:                     break;
                   2175:                 }
                   2176:             }
                   2177:             elem.scrollIntoView();
                   2178:         }
                   2179:     }
                   2180: 
                   2181:     function isElementInViewport(el) {
                   2182: 
                   2183:         // change to last element instead of first
                   2184:         var elem = document.getElementsByName(el);
                   2185:         var rect = elem[0].getBoundingClientRect();
                   2186: 
                   2187:         return (
                   2188:             rect.top >= 0 &&
                   2189:             rect.left >= 0 &&
                   2190:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2191:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2192:         );
                   2193:     }
                   2194:     
                   2195:     function autosize(depth){
                   2196:         var cmInst = window['cm'+depth];
                   2197:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2198: 
                   2199:         // is fixed size, switching to dynamic
                   2200:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2201:             cmInst.setSize("","auto");
                   2202:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2203:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2204: 
                   2205:         // is dynamic size, switching to fixed
                   2206:         } else {
                   2207:             cmInst.setSize("","300px");
                   2208:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2209:             sessionStorage.removeItem("autosized_"+depth);
                   2210:         }
                   2211:     }
                   2212: 
1.1248    raeburn  2213: $browse_or_search
1.1205    golterma 2214: 
                   2215: // ]]>
                   2216: </script>
                   2217: COLORFULEDIT
                   2218: }
                   2219: 
                   2220: sub xmleditor_js {
                   2221:     return <<XMLEDIT
                   2222: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2223: <script type="text/javascript">
                   2224: // <![CDATA[>
                   2225: 
                   2226:     function saveScrollPosition (resource) {
                   2227: 
                   2228:         var scrollPos = \$(window).scrollTop();
                   2229:         sessionStorage.setItem(resource,scrollPos);
                   2230:     }
                   2231: 
                   2232:     function restoreScrollPosition(resource){
                   2233: 
                   2234:         var scrollPos = sessionStorage.getItem(resource);
                   2235:         \$(window).scrollTop(scrollPos);
                   2236:     }
                   2237: 
                   2238:     // unless internet explorer
                   2239:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2240: 
                   2241:         \$(document).ready(function() {
                   2242:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2243:         });
                   2244:     }
                   2245: 
                   2246:     // inserts text at cursor position into codemirror (xml editor only)
                   2247:     function insertText(text){
                   2248:         cm.focus();
                   2249:         var curPos = cm.getCursor();
                   2250:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2251:     }
                   2252: // ]]>
                   2253: </script>
                   2254: XMLEDIT
                   2255: }
                   2256: 
                   2257: sub insert_folding_button {
                   2258:     my $curDepth = $Apache::lonxml::curdepth;
                   2259:     my $lastresource = $env{'request.ambiguous'};
                   2260: 
                   2261:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2262:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2263: }
                   2264: 
1.1248    raeburn  2265: sub crsauthor_url {
                   2266:     my ($url) = @_;
                   2267:     if ($url eq '') {
                   2268:         $url = $ENV{'REQUEST_URI'};
                   2269:     }
                   2270:     my ($cnum,$cdom);
                   2271:     if ($env{'request.course.id'}) {
                   2272:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2273:         if ($audom ne '' && $auname ne '') {
                   2274:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2275:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2276:                 $cnum = $auname;
                   2277:                 $cdom = $audom;
                   2278:             }
                   2279:         }
                   2280:     }
                   2281:     return ($cnum,$cdom);
                   2282: }
                   2283: 
                   2284: sub import_crsauthor_form {
1.1400    raeburn  2285:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2286:     return (0) unless ($env{'request.course.id'});
                   2287:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2288:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2289:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2290:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2291:     my @ids=&Apache::lonnet::current_machine_ids();
1.1400    raeburn  2292:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
1.1402    raeburn  2293: 
1.1248    raeburn  2294:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2295:         $is_home = 1;
                   2296:     }
1.1400    raeburn  2297:     $toppath = "/priv/$cdom/$cnum";
                   2298:     my $nonemptydir = 1;
                   2299:     my $js_only;
                   2300:     if ($only) {
                   2301:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
                   2302:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
                   2303:     }
                   2304:     $exclude = &Apache::lonnet::priv_exclude();
1.1402    raeburn  2305:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
1.1400    raeburn  2306:     my $numdirs = scalar(keys(%files));
1.1248    raeburn  2307:     my %lt = &Apache::lonlocal::texthash (
                   2308:         fnam => 'Filename',
                   2309:         dire => 'Directory',
1.1400    raeburn  2310:         se   => 'Select',
1.1248    raeburn  2311:     );
1.1450    raeburn  2312:     $output = '<label>'.$lt{'dire'}.':&nbsp;'.
1.1400    raeburn  2313:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
1.1402    raeburn  2314:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
1.1400    raeburn  2315:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
1.1402    raeburn  2316:     if ($files{'/'}) {
                   2317:         $output .= '<option value="/">/</option>'."\n";
                   2318:     }
1.1400    raeburn  2319:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
1.1402    raeburn  2320:         next if ($key eq '/');
1.1400    raeburn  2321:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
                   2322:     }
1.1450    raeburn  2323:     $output .= '</select></label><br /><label>'."\n".
1.1402    raeburn  2324:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
1.1400    raeburn  2325:                '<option value="" selected="selected"></option>'."\n".
1.1450    raeburn  2326:                '</select></label>'."\n".
1.1402    raeburn  2327:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
1.1400    raeburn  2328:     return ($numdirs,$output);
                   2329: }
                   2330: 
                   2331: sub show_crsfiles_js {
                   2332:     my $excluderef = &Apache::lonnet::priv_exclude();
                   2333:     my $se = &js_escape(&mt('Select'));
                   2334:     my $exclude;
                   2335:     if (ref($excluderef) eq 'HASH') {
                   2336:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
                   2337:     }
                   2338:     my $js = <<"END";
                   2339: 
                   2340: 
1.1402    raeburn  2341:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
1.1400    raeburn  2342:         var relpath = '';
                   2343:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2344:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
                   2345:             if (currdir == '') {
                   2346:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2347:                     selelem = form.elements[filesel];
                   2348:                     var j, numfiles = selelem.options.length -1;
                   2349:                     if (numfiles >=0) {
                   2350:                         for (j = numfiles; j >= 0; j--) {
                   2351:                             selelem.remove(j);
                   2352:                         }
                   2353:                     }
                   2354:                     if (selelem.options.length == 0) {
                   2355:                         selelem.options[selelem.options.length] = new Option('','');
                   2356:                         selelem.selectedIndex = 0;
1.1248    raeburn  2357:                     }
                   2358:                 }
1.1400    raeburn  2359:                 return;
                   2360:             } else {
                   2361:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
1.1248    raeburn  2362:             }
                   2363:         }
1.1400    raeburn  2364:         var http = new XMLHttpRequest();
                   2365:         var url = "/adm/courseauthor";
                   2366:         var crsrole = "$env{'request.role'}";
                   2367:         var exclude = '';
                   2368:         if (exc) {
                   2369:             exclude = '$exclude';
                   2370:         }
1.1402    raeburn  2371:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
1.1400    raeburn  2372:         http.open("POST", url, true);
                   2373:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                   2374:         http.onreadystatechange = function() {
                   2375:             if (http.readyState == 4 && http.status == 200) {
                   2376:                 var data = JSON.parse(http.responseText);
                   2377:                 var selelem;
                   2378:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2379:                     if (Array.isArray(data.dirs)) {
                   2380:                         selelem = form.elements[dirsel];
                   2381:                         var i, numdirs = selelem.options.length -1;
                   2382:                         if (numdirs >=0) {
                   2383:                             for (i = numdirs; i >= 0; i--) {
                   2384:                                 selelem.remove(i);
                   2385:                             }
                   2386:                         }
                   2387:                         var len = data.dirs.length;
                   2388:                         if (len) {
1.1402    raeburn  2389:                             selelem.options[selelem.options.length] = new Option('$se','');
1.1400    raeburn  2390:                             var j;
                   2391:                             for (j = 0; j < len; j++) {
                   2392:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
                   2393:                             }
                   2394:                             selelem.selectedIndex = 0;
                   2395:                         }
                   2396:                         if (!setfile) {
                   2397:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2398:                                 selelem = form.elements[filesel];
                   2399:                                 var j, numfiles = selelem.options.length -1;
                   2400:                                 if (numfiles >=0) {
                   2401:                                     for (j = numfiles; j >= 0; j--) {
                   2402:                                         selelem.remove(j);
                   2403:                                     }
                   2404:                                 }
                   2405:                                 if (selelem.options.length == 0) {
                   2406:                                     selelem.options[selelem.options.length] = new Option('','');
                   2407:                                     selelem.selectedIndex = 0;
                   2408:                                 }
                   2409:                             }
                   2410:                         }
                   2411:                     }
                   2412:                 }
                   2413:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2414:                     selelem = form.elements[filesel];
                   2415:                     var i, numfiles = selelem.options.length -1;
                   2416:                     if (numfiles >=0) {
                   2417:                         for (i = numfiles; i >= 0; i--) {
                   2418:                             selelem.remove(i);
                   2419:                         }
                   2420:                     }
                   2421:                     var x;
                   2422:                     for (x in data.files) {
                   2423:                         if (Array.isArray(data.files[x])) {
                   2424:                             if (data.files[x].length > 1) {
                   2425:                                 selelem.options[selelem.options.length] = new Option('$se','');
                   2426:                             }
                   2427:                             var len = data.files[x].length;
                   2428:                             if (len) {
                   2429:                                 var k;
                   2430:                                 for (k = 0; k < len; k++) {
                   2431:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
                   2432:                                 }
                   2433:                                 selelem.selectedIndex = 0;
                   2434:                             }
                   2435:                         }
                   2436:                     }
                   2437:                     if (selelem.options.length == 0) {
                   2438:                         selelem.options[selelem.options.length] = new Option('','');
                   2439:                         selelem.selectedIndex = 0;
                   2440:                     }
1.1248    raeburn  2441:                 }
                   2442:             }
                   2443:         }
1.1400    raeburn  2444:         http.send(params);
1.1248    raeburn  2445:     }
1.1400    raeburn  2446: END
1.1248    raeburn  2447: }
                   2448: 
1.1426    raeburn  2449: sub crsauthor_rights {
                   2450:     my ($rightsfile,$path,$docroot,$cnum,$cdom) = @_;
                   2451:     my $sourcerights = "$path/$rightsfile";
                   2452:     my $now = time;
                   2453:     if (!-e $sourcerights) {
                   2454:         my $cid = $cdom.'_'.$cnum;
                   2455:         if (!-e "$docroot/priv/$cdom") {
                   2456:             mkdir("$docroot/priv/$cdom",0755);
                   2457:         }
                   2458:         if (!-e "$docroot/priv/$cdom/$cnum") {
                   2459:             mkdir("$docroot/priv/$cdom/$cnum",0755);
                   2460:         }
                   2461:         if (open(my $fh,">$sourcerights")) {
                   2462:             print $fh <<END;
                   2463: <accessrule effect="deny" realm="" type="course" role="" />
                   2464: <accessrule effect="allow" realm="$cid" type="course" role="" />
                   2465: END
                   2466:             close($fh);
                   2467:         }
                   2468:     }
                   2469:     if (!-e "$sourcerights.meta") {
                   2470:         if (open(my $fh,">$sourcerights.meta")) {
                   2471:             my $author=$env{'environment.firstname'}.' '.
                   2472:                        $env{'environment.middlename'}.' '.
                   2473:                        $env{'environment.lastname'}.' '.
                   2474:                        $env{'environment.generation'};
                   2475:             $author =~ s/\s+$//;
                   2476:             print $fh <<"END";
                   2477: 
                   2478: <abstract></abstract>
                   2479: <author>$author</author>
                   2480: <authorspace>$cnum:$cdom</authorspace>
                   2481: <copyright>private</copyright>
                   2482: <creationdate>$now</creationdate>
                   2483: <customdistributionfile></customdistributionfile>
                   2484: <dependencies></dependencies>
                   2485: <domain>$cdom</domain>
                   2486: <highestgradelevel>0</highestgradelevel>
                   2487: <keywords></keywords>
1.1445    raeburn  2488: <language>notset</language>
1.1426    raeburn  2489: <lastrevisiondate>$now</lastrevisiondate>
                   2490: <lowestgradelevel>0</lowestgradelevel>
                   2491: <mime>rights</mime>
                   2492: <modifyinguser>$env{'user.name'}:$env{'user.domain'}</modifyinguser>
                   2493: <notes></notes>
                   2494: <obsolete></obsolete>
                   2495: <obsoletereplacement></obsoletereplacement>
                   2496: <owner>$cnum:$cdom</owner>
                   2497: <rule>deny:::course,allow:$cid::course</rule>
                   2498: <sourceavail></sourceavail>
                   2499: <standards></standards>
                   2500: <subject></subject>
                   2501: <title>Course Authoring Rights</title>
                   2502: END
                   2503:             close($fh);
                   2504:         }
                   2505:     }
                   2506:     return;
                   2507: }
                   2508: 
1.565     albertel 2509: =pod
                   2510: 
1.1420    raeburn  2511: =item * &iframe_wrapper_headjs()
                   2512: 
1.1425    raeburn  2513: emits javascript containing two global vars to facilitate handling of resizing
                   2514: by code in iframe_wrapper_resizejs() used when an iframe is present in a page
                   2515: with standard LON-CAPA menus.
                   2516: 
                   2517: =cut
                   2518: 
1.1420    raeburn  2519: #
                   2520: # Where iframe is in use, if window.onload() executes before the custom resize function
                   2521: # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
                   2522: # are used to ensure document.ready() triggers a call to resize, so the iframe contents
                   2523: # do not obscure the Functions menu.
                   2524: #
                   2525: 
                   2526: sub iframe_wrapper_headjs {
                   2527:     return <<"ENDJS";
                   2528: <script type="text/javascript">
                   2529: // <![CDATA[
                   2530: var LCnotready = 0;
                   2531: var LCresizedef = 0;
                   2532: // ]]>
                   2533: </script>
                   2534: 
                   2535: ENDJS
                   2536: 
                   2537: }
                   2538: 
                   2539: =pod
                   2540: 
                   2541: =item * &iframe_wrapper_resizejs()
                   2542: 
1.1425    raeburn  2543: emits javascript used to handle resizing for a page containing
                   2544: an iframe, to ensure that the iframe does not obscure any
                   2545: standard LON-CAPA menu items.
                   2546: 
                   2547: =back
                   2548: 
                   2549: =cut
                   2550: 
1.1420    raeburn  2551: #
                   2552: # jQuery to use when iframe is in use and a page resize occurs.
                   2553: # This script will ensure that the iframe does not obscure any
                   2554: # standard LON-CAPA inline menus (primary, secondary, and/or
                   2555: # breadcrumbs and Functions menus. Expects javascript from
                   2556: # &iframe_wrapper_headjs() to be in head portion of the web page,
                   2557: # e.g., by inclusion in second arg passed to &start_page().
                   2558: #
                   2559: 
                   2560: sub iframe_wrapper_resizejs {
                   2561:     my $offset = 5;
                   2562:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
                   2563:     if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
                   2564:         $offset = 0;
                   2565:     }
                   2566:     return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
                   2567:     \$(document).ready( function() {
                   2568:         \$(window).unbind('resize').resize(function(){
                   2569:             var header = null;
                   2570:             var offset = $offset;
                   2571:             var height = 0;
                   2572:             var hdrtop = 0;
1.1421    raeburn  2573:             if (\$('div.LC_menus_content:first').length) {
                   2574:                 if (\$('div.LC_menus_content:first').hasClass ("shown")) {
                   2575:                     header = \$('div.LC_menus_content:first');
1.1423    raeburn  2576:                     offset = 12;
1.1421    raeburn  2577:                 }
                   2578:             } else if (\$('div.LC_head_subbox:first').length) {
1.1420    raeburn  2579:                 header = \$('div.LC_head_subbox:first');
                   2580:                 offset = 9;
                   2581:             } else {
                   2582:                 if (\$('#LC_breadcrumbs').length) {
                   2583:                     header = \$('#LC_breadcrumbs');
                   2584:                 }
                   2585:             }
                   2586:             if (header != null && header.length) {
                   2587:                 height = header.height();
                   2588:                 hdrtop = header.position().top;
                   2589:             }
                   2590:             var pos = height + hdrtop + offset;
                   2591:             \$('.LC_iframecontainer').css('top', pos);
                   2592:         });
                   2593:         LCresizedef = 1;
                   2594:         if (LCnotready == 1) {
                   2595:             LCnotready = 0;
                   2596:             \$(window).trigger('resize');
                   2597:         }
                   2598:     });
                   2599:     window.onload = function(){
                   2600:          if (LCresizedef) {
                   2601:              LCnotready = 0;
                   2602:              \$(window).trigger('resize');
                   2603:          } else {
                   2604:              LCnotready = 1;
                   2605:          }
                   2606:     };
                   2607: SCRIPT
                   2608: 
                   2609: }
                   2610: 
                   2611: =pod
                   2612: 
1.256     matthew  2613: =head1 Excel and CSV file utility routines
                   2614: 
                   2615: =cut
                   2616: 
                   2617: ###############################################################
                   2618: ###############################################################
                   2619: 
                   2620: =pod
                   2621: 
1.1162    raeburn  2622: =over 4
                   2623: 
1.648     raeburn  2624: =item * &csv_translate($text) 
1.37      matthew  2625: 
1.185     www      2626: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2627: format.
                   2628: 
                   2629: =cut
                   2630: 
1.180     matthew  2631: ###############################################################
                   2632: ###############################################################
1.37      matthew  2633: sub csv_translate {
                   2634:     my $text = shift;
                   2635:     $text =~ s/\"/\"\"/g;
1.209     albertel 2636:     $text =~ s/\n/ /g;
1.37      matthew  2637:     return $text;
                   2638: }
1.180     matthew  2639: 
                   2640: ###############################################################
                   2641: ###############################################################
                   2642: 
                   2643: =pod
                   2644: 
1.648     raeburn  2645: =item * &define_excel_formats()
1.180     matthew  2646: 
                   2647: Define some commonly used Excel cell formats.
                   2648: 
                   2649: Currently supported formats:
                   2650: 
                   2651: =over 4
                   2652: 
                   2653: =item header
                   2654: 
                   2655: =item bold
                   2656: 
                   2657: =item h1
                   2658: 
                   2659: =item h2
                   2660: 
                   2661: =item h3
                   2662: 
1.256     matthew  2663: =item h4
                   2664: 
                   2665: =item i
                   2666: 
1.180     matthew  2667: =item date
                   2668: 
                   2669: =back
                   2670: 
                   2671: Inputs: $workbook
                   2672: 
                   2673: Returns: $format, a hash reference.
                   2674: 
1.1057    foxr     2675: 
1.180     matthew  2676: =cut
                   2677: 
                   2678: ###############################################################
                   2679: ###############################################################
                   2680: sub define_excel_formats {
                   2681:     my ($workbook) = @_;
                   2682:     my $format;
                   2683:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2684:                                                 bottom    => 1,
                   2685:                                                 align     => 'center');
                   2686:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2687:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2688:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2689:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2690:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2691:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2692:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2693:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2694:     return $format;
                   2695: }
                   2696: 
                   2697: ###############################################################
                   2698: ###############################################################
1.113     bowersj2 2699: 
                   2700: =pod
                   2701: 
1.648     raeburn  2702: =item * &create_workbook()
1.255     matthew  2703: 
                   2704: Create an Excel worksheet.  If it fails, output message on the
                   2705: request object and return undefs.
                   2706: 
                   2707: Inputs: Apache request object
                   2708: 
                   2709: Returns (undef) on failure, 
                   2710:     Excel worksheet object, scalar with filename, and formats 
                   2711:     from &Apache::loncommon::define_excel_formats on success
                   2712: 
                   2713: =cut
                   2714: 
                   2715: ###############################################################
                   2716: ###############################################################
                   2717: sub create_workbook {
                   2718:     my ($r) = @_;
                   2719:         #
                   2720:     # Create the excel spreadsheet
                   2721:     my $filename = '/prtspool/'.
1.258     albertel 2722:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2723:         time.'_'.rand(1000000000).'.xls';
                   2724:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2725:     if (! defined($workbook)) {
                   2726:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2727:         $r->print(
                   2728:             '<p class="LC_error">'
                   2729:            .&mt('Problems occurred in creating the new Excel file.')
                   2730:            .' '.&mt('This error has been logged.')
                   2731:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2732:            .'</p>'
                   2733:         );
1.255     matthew  2734:         return (undef);
                   2735:     }
                   2736:     #
1.1014    foxr     2737:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2738:     #
                   2739:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2740:     return ($workbook,$filename,$format);
                   2741: }
                   2742: 
                   2743: ###############################################################
                   2744: ###############################################################
                   2745: 
                   2746: =pod
                   2747: 
1.648     raeburn  2748: =item * &create_text_file()
1.113     bowersj2 2749: 
1.542     raeburn  2750: Create a file to write to and eventually make available to the user.
1.256     matthew  2751: If file creation fails, outputs an error message on the request object and 
                   2752: return undefs.
1.113     bowersj2 2753: 
1.256     matthew  2754: Inputs: Apache request object, and file suffix
1.113     bowersj2 2755: 
1.256     matthew  2756: Returns (undef) on failure, 
                   2757:     Filehandle and filename on success.
1.113     bowersj2 2758: 
                   2759: =cut
                   2760: 
1.256     matthew  2761: ###############################################################
                   2762: ###############################################################
                   2763: sub create_text_file {
                   2764:     my ($r,$suffix) = @_;
                   2765:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2766:     my $fh;
                   2767:     my $filename = '/prtspool/'.
1.258     albertel 2768:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2769:         time.'_'.rand(1000000000).'.'.$suffix;
                   2770:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2771:     if (! defined($fh)) {
                   2772:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2773:         $r->print(
                   2774:             '<p class="LC_error">'
                   2775:            .&mt('Problems occurred in creating the output file.')
                   2776:            .' '.&mt('This error has been logged.')
                   2777:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2778:            .'</p>'
                   2779:         );
1.113     bowersj2 2780:     }
1.256     matthew  2781:     return ($fh,$filename)
1.113     bowersj2 2782: }
                   2783: 
                   2784: 
1.256     matthew  2785: =pod 
1.113     bowersj2 2786: 
                   2787: =back
                   2788: 
                   2789: =cut
1.37      matthew  2790: 
                   2791: ###############################################################
1.33      matthew  2792: ##        Home server <option> list generating code          ##
                   2793: ###############################################################
1.35      matthew  2794: 
1.169     www      2795: # ------------------------------------------
                   2796: 
                   2797: sub domain_select {
1.1289    raeburn  2798:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2799:     my @possdoms;
                   2800:     if (ref($incdoms) eq 'ARRAY') {
                   2801:         @possdoms = @{$incdoms};
                   2802:     } else {
                   2803:         @possdoms = &Apache::lonnet::all_domains();
                   2804:     }
                   2805: 
1.169     www      2806:     my %domains=map { 
1.514     albertel 2807: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2808:     } @possdoms;
                   2809: 
                   2810:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2811:         foreach my $dom (@{$excdoms}) {
                   2812:             delete($domains{$dom});
                   2813:         }
                   2814:     }
                   2815: 
1.169     www      2816:     if ($multiple) {
                   2817: 	$domains{''}=&mt('Any domain');
1.550     albertel 2818: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2819: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2820:     } else {
1.550     albertel 2821: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2822: 	return &select_form($name,$value,\%domains);
1.169     www      2823:     }
                   2824: }
                   2825: 
1.282     albertel 2826: #-------------------------------------------
                   2827: 
                   2828: =pod
                   2829: 
1.519     raeburn  2830: =head1 Routines for form select boxes
                   2831: 
                   2832: =over 4
                   2833: 
1.648     raeburn  2834: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2835: 
                   2836: Returns a string containing a <select> element int multiple mode
                   2837: 
                   2838: 
                   2839: Args:
                   2840:   $name - name of the <select> element
1.506     raeburn  2841:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2842:   $size - number of rows long the select element is
1.283     albertel 2843:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2844:           (shown text should already have been &mt())
1.506     raeburn  2845:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2846: 
1.282     albertel 2847: =cut
                   2848: 
                   2849: #-------------------------------------------
1.169     www      2850: sub multiple_select_form {
1.284     albertel 2851:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2852:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2853:     my $output='';
1.191     matthew  2854:     if (! defined($size)) {
                   2855:         $size = 4;
1.283     albertel 2856:         if (scalar(keys(%$hash))<4) {
                   2857:             $size = scalar(keys(%$hash));
1.191     matthew  2858:         }
                   2859:     }
1.734     bisitz   2860:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2861:     my @order;
1.506     raeburn  2862:     if (ref($order) eq 'ARRAY')  {
                   2863:         @order = @{$order};
                   2864:     } else {
                   2865:         @order = sort(keys(%$hash));
1.501     banghart 2866:     }
                   2867:     if (exists($$hash{'select_form_order'})) {
                   2868:         @order = @{$$hash{'select_form_order'}};
                   2869:     }
                   2870:         
1.284     albertel 2871:     foreach my $key (@order) {
1.356     albertel 2872:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2873:         $output.='selected="selected" ' if ($selected{$key});
                   2874:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2875:     }
                   2876:     $output.="</select>\n";
                   2877:     return $output;
                   2878: }
                   2879: 
1.88      www      2880: #-------------------------------------------
                   2881: 
                   2882: =pod
                   2883: 
1.1254    raeburn  2884: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2885: 
                   2886: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2887: allow a user to select options from a ref to a hash containing:
                   2888: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2889: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2890: An optional arg -- $readonly -- if true will cause the select form
                   2891: to be disabled, e.g., for the case where an instructor has a section-
                   2892: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2893: 
1.88      www      2894: See lonrights.pm for an example invocation and use.
                   2895: 
                   2896: =cut
                   2897: 
                   2898: #-------------------------------------------
                   2899: sub select_form {
1.1228    raeburn  2900:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2901:     return unless (ref($hashref) eq 'HASH');
                   2902:     if ($onchange) {
                   2903:         $onchange = ' onchange="'.$onchange.'"';
                   2904:     }
1.1228    raeburn  2905:     my $disabled;
                   2906:     if ($readonly) {
                   2907:         $disabled = ' disabled="disabled"';
                   2908:     }
                   2909:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2910:     my @keys;
1.970     raeburn  2911:     if (exists($hashref->{'select_form_order'})) {
                   2912: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2913:     } else {
1.970     raeburn  2914: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2915:     }
1.356     albertel 2916:     foreach my $key (@keys) {
                   2917:         $selectform.=
                   2918: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2919:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2920:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2921:     }
                   2922:     $selectform.="</select>";
                   2923:     return $selectform;
                   2924: }
                   2925: 
1.475     www      2926: # For display filters
                   2927: 
                   2928: sub display_filter {
1.1074    raeburn  2929:     my ($context) = @_;
1.475     www      2930:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2931:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2932:     my $phraseinput = 'hidden';
                   2933:     my $includeinput = 'hidden';
                   2934:     my ($checked,$includetypestext);
                   2935:     if ($env{'form.displayfilter'} eq 'containing') {
                   2936:         $phraseinput = 'text'; 
                   2937:         if ($context eq 'parmslog') {
                   2938:             $includeinput = 'checkbox';
                   2939:             if ($env{'form.includetypes'}) {
                   2940:                 $checked = ' checked="checked"';
                   2941:             }
                   2942:             $includetypestext = &mt('Include parameter types');
                   2943:         }
                   2944:     } else {
                   2945:         $includetypestext = '&nbsp;';
                   2946:     }
                   2947:     my ($additional,$secondid,$thirdid);
                   2948:     if ($context eq 'parmslog') {
                   2949:         $additional = 
                   2950:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2951:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2952:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2953:             '</label>';
                   2954:         $secondid = 'includetypes';
                   2955:         $thirdid = 'includetypestext';
                   2956:     }
                   2957:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2958:                                                     '$secondid','$thirdid')";
                   2959:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.1403    raeburn  2960: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
1.475     www      2961: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2962: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2963:            &mt('Filter: [_1]',
1.477     www      2964: 	   &select_form($env{'form.displayfilter'},
                   2965: 			'displayfilter',
1.970     raeburn  2966: 			{'currentfolder' => 'Current folder/page',
1.477     www      2967: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2968: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2969: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2970:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2971:                          '" />'.$additional;
                   2972: }
                   2973: 
                   2974: sub display_filter_js {
                   2975:     my $includetext = &mt('Include parameter types');
                   2976:     return <<"ENDJS";
                   2977:   
                   2978: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2979:     var firstType = 'hidden';
                   2980:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2981:         firstType = 'text';
                   2982:     }
                   2983:     firstObject = document.getElementById(firstid);
                   2984:     if (typeof(firstObject) == 'object') {
                   2985:         if (firstObject.type != firstType) {
                   2986:             changeInputType(firstObject,firstType);
                   2987:         }
                   2988:     }
                   2989:     if (context == 'parmslog') {
                   2990:         var secondType = 'hidden';
                   2991:         if (firstType == 'text') {
                   2992:             secondType = 'checkbox';
                   2993:         }
                   2994:         secondObject = document.getElementById(secondid);  
                   2995:         if (typeof(secondObject) == 'object') {
                   2996:             if (secondObject.type != secondType) {
                   2997:                 changeInputType(secondObject,secondType);
                   2998:             }
                   2999:         }
                   3000:         var textItem = document.getElementById(thirdid);
                   3001:         var currtext = textItem.innerHTML;
                   3002:         var newtext;
                   3003:         if (firstType == 'text') {
                   3004:             newtext = '$includetext';
                   3005:         } else {
                   3006:             newtext = '&nbsp;';
                   3007:         }
                   3008:         if (currtext != newtext) {
                   3009:             textItem.innerHTML = newtext;
                   3010:         }
                   3011:     }
                   3012:     return;
                   3013: }
                   3014: 
                   3015: function changeInputType(oldObject,newType) {
                   3016:     var newObject = document.createElement('input');
                   3017:     newObject.type = newType;
                   3018:     if (oldObject.size) {
                   3019:         newObject.size = oldObject.size;
                   3020:     }
                   3021:     if (oldObject.value) {
                   3022:         newObject.value = oldObject.value;
                   3023:     }
                   3024:     if (oldObject.name) {
                   3025:         newObject.name = oldObject.name;
                   3026:     }
                   3027:     if (oldObject.id) {
                   3028:         newObject.id = oldObject.id;
                   3029:     }
                   3030:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   3031:     return;
                   3032: }
                   3033: 
                   3034: ENDJS
1.475     www      3035: }
                   3036: 
1.167     www      3037: sub gradeleveldescription {
                   3038:     my $gradelevel=shift;
                   3039:     my %gradelevels=(0 => 'Not specified',
                   3040: 		     1 => 'Grade 1',
                   3041: 		     2 => 'Grade 2',
                   3042: 		     3 => 'Grade 3',
                   3043: 		     4 => 'Grade 4',
                   3044: 		     5 => 'Grade 5',
                   3045: 		     6 => 'Grade 6',
                   3046: 		     7 => 'Grade 7',
                   3047: 		     8 => 'Grade 8',
                   3048: 		     9 => 'Grade 9',
                   3049: 		     10 => 'Grade 10',
                   3050: 		     11 => 'Grade 11',
                   3051: 		     12 => 'Grade 12',
                   3052: 		     13 => 'Grade 13',
                   3053: 		     14 => '100 Level',
                   3054: 		     15 => '200 Level',
                   3055: 		     16 => '300 Level',
                   3056: 		     17 => '400 Level',
                   3057: 		     18 => 'Graduate Level');
                   3058:     return &mt($gradelevels{$gradelevel});
                   3059: }
                   3060: 
1.163     www      3061: sub select_level_form {
                   3062:     my ($deflevel,$name)=@_;
                   3063:     unless ($deflevel) { $deflevel=0; }
1.167     www      3064:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   3065:     for (my $i=0; $i<=18; $i++) {
                   3066:         $selectform.="<option value=\"$i\" ".
1.253     albertel 3067:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      3068:                 ">".&gradeleveldescription($i)."</option>\n";
                   3069:     }
                   3070:     $selectform.="</select>";
                   3071:     return $selectform;
1.163     www      3072: }
1.167     www      3073: 
1.35      matthew  3074: #-------------------------------------------
                   3075: 
1.45      matthew  3076: =pod
                   3077: 
1.1453    raeburn  3078: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled,$id)
1.35      matthew  3079: 
                   3080: Returns a string containing a <select name='$name' size='1'> form to 
                   3081: allow a user to select the domain to preform an operation in.  
                   3082: See loncreateuser.pm for an example invocation and use.
                   3083: 
1.90      www      3084: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   3085: selected");
                   3086: 
1.743     raeburn  3087: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   3088: 
1.910     raeburn  3089: 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.
                   3090: 
1.1121    raeburn  3091: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   3092: 
                   3093: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  3094: 
1.1256    raeburn  3095: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   3096: 
1.1453    raeburn  3097: The option $id argument is the value (if any) to set as the (unique) id attribute for the select tag.
                   3098: 
1.35      matthew  3099: =cut
                   3100: 
                   3101: #-------------------------------------------
1.34      matthew  3102: sub select_dom_form {
1.1453    raeburn  3103:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled,$id) = @_;
1.872     raeburn  3104:     if ($onchange) {
1.874     raeburn  3105:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  3106:     }
1.1256    raeburn  3107:     if ($disabled) {
                   3108:         $disabled = ' disabled="disabled"';
                   3109:     }
1.1453    raeburn  3110:     if ($id ne '') {
                   3111:         $id = ' id="'.$id.'"';
                   3112:     }
1.1121    raeburn  3113:     my (@domains,%exclude);
1.910     raeburn  3114:     if (ref($incdoms) eq 'ARRAY') {
                   3115:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   3116:     } else {
                   3117:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   3118:     }
1.90      www      3119:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  3120:     if (ref($excdoms) eq 'ARRAY') {
                   3121:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   3122:     }
1.1453    raeburn  3123:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled$id>\n";
1.356     albertel 3124:     foreach my $dom (@domains) {
1.1121    raeburn  3125:         next if ($exclude{$dom});
1.356     albertel 3126:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  3127:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   3128:         if ($showdomdesc) {
                   3129:             if ($dom ne '') {
                   3130:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   3131:                 if ($domdesc ne '') {
                   3132:                     $selectdomain .= ' ('.$domdesc.')';
                   3133:                 }
                   3134:             } 
                   3135:         }
                   3136:         $selectdomain .= "</option>\n";
1.34      matthew  3137:     }
                   3138:     $selectdomain.="</select>";
                   3139:     return $selectdomain;
                   3140: }
                   3141: 
1.35      matthew  3142: #-------------------------------------------
                   3143: 
1.45      matthew  3144: =pod
                   3145: 
1.648     raeburn  3146: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  3147: 
1.586     raeburn  3148: input: 4 arguments (two required, two optional) - 
                   3149:     $domain - domain of new user
                   3150:     $name - name of form element
                   3151:     $default - Value of 'default' causes a default item to be first 
                   3152:                             option, and selected by default. 
                   3153:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   3154:                             if 1 server found, or default, if 0 found.
1.594     raeburn  3155: output: returns 2 items: 
1.586     raeburn  3156: (a) form element which contains either:
                   3157:    (i) <select name="$name">
                   3158:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   3159:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   3160:        </select>
                   3161:        form item if there are multiple library servers in $domain, or
                   3162:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   3163:        if there is only one library server in $domain.
                   3164: 
                   3165: (b) number of library servers found.
                   3166: 
                   3167: See loncreateuser.pm for example of use.
1.35      matthew  3168: 
                   3169: =cut
                   3170: 
                   3171: #-------------------------------------------
1.586     raeburn  3172: sub home_server_form_item {
                   3173:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 3174:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  3175:     my $result;
                   3176:     my $numlib = keys(%servers);
                   3177:     if ($numlib > 1) {
                   3178:         $result .= '<select name="'.$name.'" />'."\n";
                   3179:         if ($default) {
1.804     bisitz   3180:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  3181:                        '</option>'."\n";
                   3182:         }
                   3183:         foreach my $hostid (sort(keys(%servers))) {
                   3184:             $result.= '<option value="'.$hostid.'">'.
                   3185: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   3186:         }
                   3187:         $result .= '</select>'."\n";
                   3188:     } elsif ($numlib == 1) {
                   3189:         my $hostid;
                   3190:         foreach my $item (keys(%servers)) {
                   3191:             $hostid = $item;
                   3192:         }
                   3193:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   3194:                    $hostid.'" />';
                   3195:                    if (!$hide) {
                   3196:                        $result .= $hostid.' '.$servers{$hostid};
                   3197:                    }
                   3198:                    $result .= "\n";
                   3199:     } elsif ($default) {
                   3200:         $result .= '<input type="hidden" name="'.$name.
                   3201:                    '" value="default" />';
                   3202:                    if (!$hide) {
                   3203:                        $result .= &mt('default');
                   3204:                    }
                   3205:                    $result .= "\n";
1.33      matthew  3206:     }
1.586     raeburn  3207:     return ($result,$numlib);
1.33      matthew  3208: }
1.112     bowersj2 3209: 
                   3210: =pod
                   3211: 
1.534     albertel 3212: =back 
                   3213: 
1.112     bowersj2 3214: =cut
1.87      matthew  3215: 
                   3216: ###############################################################
1.112     bowersj2 3217: ##                  Decoding User Agent                      ##
1.87      matthew  3218: ###############################################################
                   3219: 
                   3220: =pod
                   3221: 
1.112     bowersj2 3222: =head1 Decoding the User Agent
                   3223: 
                   3224: =over 4
                   3225: 
                   3226: =item * &decode_user_agent()
1.87      matthew  3227: 
                   3228: Inputs: $r
                   3229: 
                   3230: Outputs:
                   3231: 
                   3232: =over 4
                   3233: 
1.112     bowersj2 3234: =item * $httpbrowser
1.87      matthew  3235: 
1.112     bowersj2 3236: =item * $clientbrowser
1.87      matthew  3237: 
1.112     bowersj2 3238: =item * $clientversion
1.87      matthew  3239: 
1.112     bowersj2 3240: =item * $clientmathml
1.87      matthew  3241: 
1.112     bowersj2 3242: =item * $clientunicode
1.87      matthew  3243: 
1.112     bowersj2 3244: =item * $clientos
1.87      matthew  3245: 
1.1137    raeburn  3246: =item * $clientmobile
                   3247: 
1.1141    raeburn  3248: =item * $clientinfo
                   3249: 
1.1194    raeburn  3250: =item * $clientosversion
                   3251: 
1.87      matthew  3252: =back
                   3253: 
1.157     matthew  3254: =back 
                   3255: 
1.87      matthew  3256: =cut
                   3257: 
                   3258: ###############################################################
                   3259: ###############################################################
                   3260: sub decode_user_agent {
1.247     albertel 3261:     my ($r)=@_;
1.87      matthew  3262:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   3263:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   3264:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 3265:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  3266:     my $clientbrowser='unknown';
                   3267:     my $clientversion='0';
                   3268:     my $clientmathml='';
                   3269:     my $clientunicode='0';
1.1137    raeburn  3270:     my $clientmobile=0;
1.1194    raeburn  3271:     my $clientosversion='';
1.87      matthew  3272:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  3273:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  3274: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   3275: 	    $clientbrowser=$bname;
                   3276:             $httpbrowser=~/$vreg/i;
                   3277: 	    $clientversion=$1;
                   3278:             $clientmathml=($clientversion>=$minv);
                   3279:             $clientunicode=($clientversion>=$univ);
                   3280: 	}
                   3281:     }
                   3282:     my $clientos='unknown';
1.1141    raeburn  3283:     my $clientinfo;
1.87      matthew  3284:     if (($httpbrowser=~/linux/i) ||
                   3285:         ($httpbrowser=~/unix/i) ||
                   3286:         ($httpbrowser=~/ux/i) ||
                   3287:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   3288:     if (($httpbrowser=~/vax/i) ||
                   3289:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   3290:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   3291:     if (($httpbrowser=~/mac/i) ||
                   3292:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  3293:     if ($httpbrowser=~/win/i) {
                   3294:         $clientos='win';
                   3295:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   3296:             $clientosversion = $1;
                   3297:         }
                   3298:     }
1.87      matthew  3299:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3300:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3301:         $clientmobile=lc($1);
                   3302:     }
1.1141    raeburn  3303:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3304:         $clientinfo = 'firefox-'.$1;
                   3305:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3306:         $clientinfo = 'chromeframe-'.$1;
                   3307:     }
1.87      matthew  3308:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3309:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3310:             $clientosversion);
1.87      matthew  3311: }
                   3312: 
1.32      matthew  3313: ###############################################################
                   3314: ##    Authentication changing form generation subroutines    ##
                   3315: ###############################################################
                   3316: ##
                   3317: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3318: ## hash, and have reasonable default values.
                   3319: ##
                   3320: ##    formname = the name given in the <form> tag.
1.35      matthew  3321: #-------------------------------------------
                   3322: 
1.45      matthew  3323: =pod
                   3324: 
1.112     bowersj2 3325: =head1 Authentication Routines
                   3326: 
                   3327: =over 4
                   3328: 
1.648     raeburn  3329: =item * &authform_xxxxxx()
1.35      matthew  3330: 
                   3331: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3332: handle some of the conveniences required for authentication forms.  
                   3333: This is not an optimal method, but it works.  
                   3334: 
                   3335: =over 4
                   3336: 
1.112     bowersj2 3337: =item * authform_header
1.35      matthew  3338: 
1.112     bowersj2 3339: =item * authform_authorwarning
1.35      matthew  3340: 
1.112     bowersj2 3341: =item * authform_nochange
1.35      matthew  3342: 
1.112     bowersj2 3343: =item * authform_kerberos
1.35      matthew  3344: 
1.112     bowersj2 3345: =item * authform_internal
1.35      matthew  3346: 
1.112     bowersj2 3347: =item * authform_filesystem
1.35      matthew  3348: 
1.1310    raeburn  3349: =item * authform_lti
                   3350: 
1.35      matthew  3351: =back
                   3352: 
1.648     raeburn  3353: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3354: 
1.35      matthew  3355: =cut
                   3356: 
                   3357: #-------------------------------------------
1.32      matthew  3358: sub authform_header{  
                   3359:     my %in = (
                   3360:         formname => 'cu',
1.80      albertel 3361:         kerb_def_dom => '',
1.32      matthew  3362:         @_,
                   3363:     );
                   3364:     $in{'formname'} = 'document.' . $in{'formname'};
                   3365:     my $result='';
1.80      albertel 3366: 
                   3367: #---------------------------------------------- Code for upper case translation
                   3368:     my $Javascript_toUpperCase;
                   3369:     unless ($in{kerb_def_dom}) {
                   3370:         $Javascript_toUpperCase =<<"END";
                   3371:         switch (choice) {
                   3372:            case 'krb': currentform.elements[choicearg].value =
                   3373:                currentform.elements[choicearg].value.toUpperCase();
                   3374:                break;
                   3375:            default:
                   3376:         }
                   3377: END
                   3378:     } else {
                   3379:         $Javascript_toUpperCase = "";
                   3380:     }
                   3381: 
1.165     raeburn  3382:     my $radioval = "'nochange'";
1.591     raeburn  3383:     if (defined($in{'curr_authtype'})) {
                   3384:         if ($in{'curr_authtype'} ne '') {
                   3385:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3386:         }
1.174     matthew  3387:     }
1.165     raeburn  3388:     my $argfield = 'null';
1.591     raeburn  3389:     if (defined($in{'mode'})) {
1.165     raeburn  3390:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3391:             if (defined($in{'curr_autharg'})) {
                   3392:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3393:                     $argfield = "'$in{'curr_autharg'}'";
                   3394:                 }
                   3395:             }
                   3396:         }
                   3397:     }
                   3398: 
1.32      matthew  3399:     $result.=<<"END";
                   3400: var current = new Object();
1.165     raeburn  3401: current.radiovalue = $radioval;
                   3402: current.argfield = $argfield;
1.32      matthew  3403: 
                   3404: function changed_radio(choice,currentform) {
                   3405:     var choicearg = choice + 'arg';
                   3406:     // If a radio button in changed, we need to change the argfield
                   3407:     if (current.radiovalue != choice) {
                   3408:         current.radiovalue = choice;
                   3409:         if (current.argfield != null) {
                   3410:             currentform.elements[current.argfield].value = '';
                   3411:         }
                   3412:         if (choice == 'nochange') {
                   3413:             current.argfield = null;
                   3414:         } else {
                   3415:             current.argfield = choicearg;
                   3416:             switch(choice) {
                   3417:                 case 'krb': 
                   3418:                     currentform.elements[current.argfield].value = 
                   3419:                         "$in{'kerb_def_dom'}";
                   3420:                 break;
                   3421:               default:
                   3422:                 break;
                   3423:             }
                   3424:         }
                   3425:     }
                   3426:     return;
                   3427: }
1.22      www      3428: 
1.32      matthew  3429: function changed_text(choice,currentform) {
                   3430:     var choicearg = choice + 'arg';
                   3431:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3432:         $Javascript_toUpperCase
1.32      matthew  3433:         // clear old field
                   3434:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3435:             currentform.elements[current.argfield].value = '';
                   3436:         }
                   3437:         current.argfield = choicearg;
                   3438:     }
                   3439:     set_auth_radio_buttons(choice,currentform);
                   3440:     return;
1.20      www      3441: }
1.32      matthew  3442: 
                   3443: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3444:     var numauthchoices = currentform.login.length;
                   3445:     if (typeof numauthchoices  == "undefined") {
                   3446:         return;
                   3447:     } 
1.32      matthew  3448:     var i=0;
1.986     raeburn  3449:     while (i < numauthchoices) {
1.32      matthew  3450:         if (currentform.login[i].value == newvalue) { break; }
                   3451:         i++;
                   3452:     }
1.986     raeburn  3453:     if (i == numauthchoices) {
1.32      matthew  3454:         return;
                   3455:     }
                   3456:     current.radiovalue = newvalue;
                   3457:     currentform.login[i].checked = true;
                   3458:     return;
                   3459: }
                   3460: END
                   3461:     return $result;
                   3462: }
                   3463: 
1.1106    raeburn  3464: sub authform_authorwarning {
1.32      matthew  3465:     my $result='';
1.144     matthew  3466:     $result='<i>'.
                   3467:         &mt('As a general rule, only authors or co-authors should be '.
                   3468:             'filesystem authenticated '.
                   3469:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3470:     return $result;
                   3471: }
                   3472: 
1.1106    raeburn  3473: sub authform_nochange {
1.32      matthew  3474:     my %in = (
                   3475:               formname => 'document.cu',
                   3476:               kerb_def_dom => 'MSU.EDU',
                   3477:               @_,
                   3478:           );
1.1106    raeburn  3479:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3480:     my $result;
1.1104    raeburn  3481:     if (!$authnum) {
1.1105    raeburn  3482:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3483:     } else {
                   3484:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3485:                   '<input type="radio" name="login" value="nochange" '.
                   3486:                   'checked="checked" onclick="'.
1.281     albertel 3487:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3488: 	    '</label>';
1.586     raeburn  3489:     }
1.32      matthew  3490:     return $result;
                   3491: }
                   3492: 
1.591     raeburn  3493: sub authform_kerberos {
1.32      matthew  3494:     my %in = (
                   3495:               formname => 'document.cu',
                   3496:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3497:               kerb_def_auth => 'krb4',
1.32      matthew  3498:               @_,
                   3499:               );
1.586     raeburn  3500:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3501:         $autharg,$jscall,$disabled);
1.1106    raeburn  3502:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3503:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3504:        $check5 = ' checked="checked"';
1.80      albertel 3505:     } else {
1.772     bisitz   3506:        $check4 = ' checked="checked"';
1.80      albertel 3507:     }
1.1259    raeburn  3508:     if ($in{'readonly'}) {
                   3509:         $disabled = ' disabled="disabled"';
                   3510:     }
1.165     raeburn  3511:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3512:     if (defined($in{'curr_authtype'})) {
                   3513:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3514:             $krbcheck = ' checked="checked"';
1.623     raeburn  3515:             if (defined($in{'mode'})) {
                   3516:                 if ($in{'mode'} eq 'modifyuser') {
                   3517:                     $krbcheck = '';
                   3518:                 }
                   3519:             }
1.591     raeburn  3520:             if (defined($in{'curr_kerb_ver'})) {
                   3521:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3522:                     $check5 = ' checked="checked"';
1.591     raeburn  3523:                     $check4 = '';
                   3524:                 } else {
1.772     bisitz   3525:                     $check4 = ' checked="checked"';
1.591     raeburn  3526:                     $check5 = '';
                   3527:                 }
1.586     raeburn  3528:             }
1.591     raeburn  3529:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3530:                 $krbarg = $in{'curr_autharg'};
                   3531:             }
1.586     raeburn  3532:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3533:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3534:                     $result = 
                   3535:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3536:         $in{'curr_autharg'},$krbver);
                   3537:                 } else {
                   3538:                     $result =
                   3539:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3540:                 }
                   3541:                 return $result; 
                   3542:             }
                   3543:         }
                   3544:     } else {
                   3545:         if ($authnum == 1) {
1.784     bisitz   3546:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3547:         }
                   3548:     }
1.586     raeburn  3549:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3550:         return;
1.587     raeburn  3551:     } elsif ($authtype eq '') {
1.591     raeburn  3552:         if (defined($in{'mode'})) {
1.587     raeburn  3553:             if ($in{'mode'} eq 'modifycourse') {
                   3554:                 if ($authnum == 1) {
1.1259    raeburn  3555:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3556:                 }
                   3557:             }
                   3558:         }
1.586     raeburn  3559:     }
                   3560:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3561:     if ($authtype eq '') {
                   3562:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3563:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3564:                     $krbcheck.$disabled.' />';
1.586     raeburn  3565:     }
                   3566:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3567:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3568:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3569:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3570:          $in{'curr_authtype'} eq 'krb4')) {
                   3571:         $result .= &mt
1.144     matthew  3572:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3573:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3574:          '<label>'.$authtype,
1.281     albertel 3575:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3576:              'value="'.$krbarg.'" '.
1.1259    raeburn  3577:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3578:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3579:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3580: 	 '</label>');
1.586     raeburn  3581:     } elsif ($can_assign{'krb4'}) {
                   3582:         $result .= &mt
                   3583:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3584:          '[_3] Version 4 [_4]',
                   3585:          '<label>'.$authtype,
                   3586:          '</label><input type="text" size="10" name="krbarg" '.
                   3587:              'value="'.$krbarg.'" '.
1.1259    raeburn  3588:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3589:          '<label><input type="hidden" name="krbver" value="4" />',
                   3590:          '</label>');
                   3591:     } elsif ($can_assign{'krb5'}) {
                   3592:         $result .= &mt
                   3593:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3594:          '[_3] Version 5 [_4]',
                   3595:          '<label>'.$authtype,
                   3596:          '</label><input type="text" size="10" name="krbarg" '.
                   3597:              'value="'.$krbarg.'" '.
1.1259    raeburn  3598:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3599:          '<label><input type="hidden" name="krbver" value="5" />',
                   3600:          '</label>');
                   3601:     }
1.32      matthew  3602:     return $result;
                   3603: }
                   3604: 
1.1106    raeburn  3605: sub authform_internal {
1.586     raeburn  3606:     my %in = (
1.32      matthew  3607:                 formname => 'document.cu',
                   3608:                 kerb_def_dom => 'MSU.EDU',
                   3609:                 @_,
                   3610:                 );
1.1259    raeburn  3611:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3612:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3613:     if ($in{'readonly'}) {
                   3614:         $disabled = ' disabled="disabled"';
                   3615:     }
1.591     raeburn  3616:     if (defined($in{'curr_authtype'})) {
                   3617:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3618:             if ($can_assign{'int'}) {
1.772     bisitz   3619:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3620:                 if (defined($in{'mode'})) {
                   3621:                     if ($in{'mode'} eq 'modifyuser') {
                   3622:                         $intcheck = '';
                   3623:                     }
                   3624:                 }
1.591     raeburn  3625:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3626:                     $intarg = $in{'curr_autharg'};
                   3627:                 }
                   3628:             } else {
                   3629:                 $result = &mt('Currently internally authenticated.');
                   3630:                 return $result;
1.165     raeburn  3631:             }
                   3632:         }
1.586     raeburn  3633:     } else {
                   3634:         if ($authnum == 1) {
1.784     bisitz   3635:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3636:         }
                   3637:     }
                   3638:     if (!$can_assign{'int'}) {
                   3639:         return;
1.587     raeburn  3640:     } elsif ($authtype eq '') {
1.591     raeburn  3641:         if (defined($in{'mode'})) {
1.587     raeburn  3642:             if ($in{'mode'} eq 'modifycourse') {
                   3643:                 if ($authnum == 1) {
1.1259    raeburn  3644:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3645:                 }
                   3646:             }
                   3647:         }
1.165     raeburn  3648:     }
1.586     raeburn  3649:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3650:     if ($authtype eq '') {
                   3651:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3652:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3653:     }
1.605     bisitz   3654:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3655:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3656:     $result = &mt
1.144     matthew  3657:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3658:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3659:     $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  3660:     return $result;
                   3661: }
                   3662: 
1.1104    raeburn  3663: sub authform_local {
1.32      matthew  3664:     my %in = (
                   3665:               formname => 'document.cu',
                   3666:               kerb_def_dom => 'MSU.EDU',
                   3667:               @_,
                   3668:               );
1.1259    raeburn  3669:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3670:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3671:     if ($in{'readonly'}) {
                   3672:         $disabled = ' disabled="disabled"';
                   3673:     } 
1.591     raeburn  3674:     if (defined($in{'curr_authtype'})) {
                   3675:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3676:             if ($can_assign{'loc'}) {
1.772     bisitz   3677:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3678:                 if (defined($in{'mode'})) {
                   3679:                     if ($in{'mode'} eq 'modifyuser') {
                   3680:                         $loccheck = '';
                   3681:                     }
                   3682:                 }
1.591     raeburn  3683:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3684:                     $locarg = $in{'curr_autharg'};
                   3685:                 }
                   3686:             } else {
                   3687:                 $result = &mt('Currently using local (institutional) authentication.');
                   3688:                 return $result;
1.165     raeburn  3689:             }
                   3690:         }
1.586     raeburn  3691:     } else {
                   3692:         if ($authnum == 1) {
1.784     bisitz   3693:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3694:         }
                   3695:     }
                   3696:     if (!$can_assign{'loc'}) {
                   3697:         return;
1.587     raeburn  3698:     } elsif ($authtype eq '') {
1.591     raeburn  3699:         if (defined($in{'mode'})) {
1.587     raeburn  3700:             if ($in{'mode'} eq 'modifycourse') {
                   3701:                 if ($authnum == 1) {
1.1259    raeburn  3702:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3703:                 }
                   3704:             }
                   3705:         }
1.165     raeburn  3706:     }
1.586     raeburn  3707:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3708:     if ($authtype eq '') {
                   3709:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3710:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3711:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3712:     }
                   3713:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3714:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3715:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3716:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3717:     return $result;
                   3718: }
                   3719: 
1.1106    raeburn  3720: sub authform_filesystem {
1.32      matthew  3721:     my %in = (
                   3722:               formname => 'document.cu',
                   3723:               kerb_def_dom => 'MSU.EDU',
                   3724:               @_,
                   3725:               );
1.1259    raeburn  3726:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3727:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3728:     if ($in{'readonly'}) {
                   3729:         $disabled = ' disabled="disabled"';
                   3730:     }
1.591     raeburn  3731:     if (defined($in{'curr_authtype'})) {
                   3732:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3733:             if ($can_assign{'fsys'}) {
1.772     bisitz   3734:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3735:                 if (defined($in{'mode'})) {
                   3736:                     if ($in{'mode'} eq 'modifyuser') {
                   3737:                         $fsyscheck = '';
                   3738:                     }
                   3739:                 }
1.586     raeburn  3740:             } else {
                   3741:                 $result = &mt('Currently Filesystem Authenticated.');
                   3742:                 return $result;
1.1259    raeburn  3743:             }
1.586     raeburn  3744:         }
                   3745:     } else {
                   3746:         if ($authnum == 1) {
1.784     bisitz   3747:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3748:         }
                   3749:     }
                   3750:     if (!$can_assign{'fsys'}) {
                   3751:         return;
1.587     raeburn  3752:     } elsif ($authtype eq '') {
1.591     raeburn  3753:         if (defined($in{'mode'})) {
1.587     raeburn  3754:             if ($in{'mode'} eq 'modifycourse') {
                   3755:                 if ($authnum == 1) {
1.1259    raeburn  3756:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3757:                 }
                   3758:             }
                   3759:         }
1.586     raeburn  3760:     }
                   3761:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3762:     if ($authtype eq '') {
                   3763:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3764:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3765:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3766:     }
1.1310    raeburn  3767:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3768:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3769:     $result = &mt
1.144     matthew  3770:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3771:          '<label>'.$authtype,'</label>'.$autharg);
                   3772:     return $result;
                   3773: }
                   3774: 
                   3775: sub authform_lti {
                   3776:     my %in = (
                   3777:               formname => 'document.cu',
                   3778:               kerb_def_dom => 'MSU.EDU',
                   3779:               @_,
                   3780:               );
                   3781:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3782:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3783:     if ($in{'readonly'}) {
                   3784:         $disabled = ' disabled="disabled"';
                   3785:     }
                   3786:     if (defined($in{'curr_authtype'})) {
                   3787:         if ($in{'curr_authtype'} eq 'lti') {
                   3788:             if ($can_assign{'lti'}) {
                   3789:                 $lticheck = 'checked="checked" ';
                   3790:                 if (defined($in{'mode'})) {
                   3791:                     if ($in{'mode'} eq 'modifyuser') {
                   3792:                         $lticheck = '';
                   3793:                     }
                   3794:                 }
                   3795:             } else {
                   3796:                 $result = &mt('Currently LTI Authenticated.');
                   3797:                 return $result;
                   3798:             }
                   3799:         }
                   3800:     } else {
                   3801:         if ($authnum == 1) {
                   3802:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3803:         }
                   3804:     }
                   3805:     if (!$can_assign{'lti'}) {
                   3806:         return;
                   3807:     } elsif ($authtype eq '') {
                   3808:         if (defined($in{'mode'})) {
                   3809:             if ($in{'mode'} eq 'modifycourse') {
                   3810:                 if ($authnum == 1) {
                   3811:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3812:                 }
                   3813:             }
                   3814:         }
                   3815:     }
                   3816:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3817:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3818:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3819:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3820:                     $jscall.'"'.$disabled.' />';
                   3821:     }
                   3822:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3823:     if ($authtype) {
                   3824:         $result = &mt('[_1] LTI Authenticated',
                   3825:                       '<label>'.$authtype.'</label>'.$autharg);
                   3826:     } else {
                   3827:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3828:                   $autharg;
                   3829:     }
1.32      matthew  3830:     return $result;
                   3831: }
                   3832: 
1.586     raeburn  3833: sub get_assignable_auth {
                   3834:     my ($dom) = @_;
                   3835:     if ($dom eq '') {
                   3836:         $dom = $env{'request.role.domain'};
                   3837:     }
                   3838:     my %can_assign = (
                   3839:                           krb4 => 1,
                   3840:                           krb5 => 1,
                   3841:                           int  => 1,
                   3842:                           loc  => 1,
1.1310    raeburn  3843:                           lti  => 1,
1.586     raeburn  3844:                      );
                   3845:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3846:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3847:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3848:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3849:             my $context;
                   3850:             if ($env{'request.role'} =~ /^au/) {
                   3851:                 $context = 'author';
1.1259    raeburn  3852:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3853:                 $context = 'domain';
                   3854:             } elsif ($env{'request.course.id'}) {
                   3855:                 $context = 'course';
                   3856:             }
                   3857:             if ($context) {
                   3858:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3859:                    %can_assign = %{$authhash->{$context}}; 
                   3860:                 }
                   3861:             }
                   3862:         }
                   3863:     }
                   3864:     my $authnum = 0;
                   3865:     foreach my $key (keys(%can_assign)) {
                   3866:         if ($can_assign{$key}) {
                   3867:             $authnum ++;
                   3868:         }
                   3869:     }
                   3870:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3871:         $authnum --;
                   3872:     }
                   3873:     return ($authnum,%can_assign);
                   3874: }
                   3875: 
1.1331    raeburn  3876: sub check_passwd_rules {
                   3877:     my ($domain,$plainpass) = @_;
                   3878:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3879:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3880:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3881:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3882:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3883:             if ($passwdconf{'min'} > $min) {
                   3884:                 $min = $passwdconf{'min'};
                   3885:             }
1.1331    raeburn  3886:         }
                   3887:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3888:             $max = $passwdconf{'max'};
                   3889:         }
                   3890:         @chars = @{$passwdconf{'chars'}};
                   3891:     }
                   3892:     if (($min) && (length($plainpass) < $min)) {
                   3893:         push(@brokerule,'min');
                   3894:     }
                   3895:     if (($max) && (length($plainpass) > $max)) {
                   3896:         push(@brokerule,'max');
                   3897:     }
                   3898:     if (@chars) {
                   3899:         my %rules;
                   3900:         map { $rules{$_} = 1; } @chars;
                   3901:         if ($rules{'uc'}) {
                   3902:             unless ($plainpass =~ /[A-Z]/) {
                   3903:                 push(@brokerule,'uc');
                   3904:             }
                   3905:         }
                   3906:         if ($rules{'lc'}) {
1.1332    raeburn  3907:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3908:                 push(@brokerule,'lc');
                   3909:             }
                   3910:         }
                   3911:         if ($rules{'num'}) {
                   3912:             unless ($plainpass =~ /\d/) {
                   3913:                 push(@brokerule,'num');
                   3914:             }
                   3915:         }
                   3916:         if ($rules{'spec'}) {
                   3917:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3918:                 push(@brokerule,'spec');
                   3919:             }
                   3920:         }
                   3921:     }
                   3922:     if (@brokerule) {
                   3923:         my %rulenames = &Apache::lonlocal::texthash(
                   3924:             uc   => 'At least one upper case letter',
                   3925:             lc   => 'At least one lower case letter',
                   3926:             num  => 'At least one number',
                   3927:             spec => 'At least one non-alphanumeric',
                   3928:         );
                   3929:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3930:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3931:         $rulenames{'num'} .= ': 0123456789';
                   3932:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3933:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3934:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3935:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3936:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3937:             if (grep(/^$rule$/,@brokerule)) {
                   3938:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3939:             }
                   3940:         }
                   3941:         $warning .= '</ul>';
                   3942:     }
1.1332    raeburn  3943:     if (wantarray) {
                   3944:         return @brokerule;
                   3945:     }
1.1331    raeburn  3946:     return $warning;
                   3947: }
                   3948: 
1.1376    raeburn  3949: sub passwd_validation_js {
1.1377    raeburn  3950:     my ($currpasswdval,$domain,$context,$id) = @_;
                   3951:     my (%passwdconf,$alertmsg);
                   3952:     if ($context eq 'linkprot') {
                   3953:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3954:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3955:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3956:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3957:             }
                   3958:         }
                   3959:         if ($id eq 'add') {
                   3960:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3961:         } elsif ($id =~ /^\d+$/) {
                   3962:             my $pos = $id+1;
                   3963:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3964:         } else {
                   3965:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3966:         }
1.1434    raeburn  3967:     } elsif ($context eq 'ltitools') {
                   3968:         my %domconfig = &Apache::lonnet::get_dom('configuration',['toolsec'],$domain);
                   3969:         if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   3970:             if (ref($domconfig{'toolsec'}{'rules'}) eq 'HASH') {
                   3971:                 %passwdconf = %{$domconfig{'toolsec'}{'rules'}};
                   3972:             }
                   3973:         }
                   3974:         if ($id eq 'add') {
                   3975:             $alertmsg = &mt('Secret for added external tool did not satisfy requirement(s):').'\n\n';
                   3976:         } elsif ($id =~ /^\d+$/) {
                   3977:             my $pos = $id+1;
                   3978:             $alertmsg = &mt('Secret for external tool [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3979:         } else {
                   3980:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3981:         }
1.1377    raeburn  3982:     } else {
                   3983:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3984:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3985:     }
1.1376    raeburn  3986:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3987:     $numrules = 0;
                   3988:     $min = $Apache::lonnet::passwdmin;
                   3989:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3990:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3991:             if ($passwdconf{'min'} > $min) {
                   3992:                 $min = $passwdconf{'min'};
                   3993:             }
                   3994:         }
                   3995:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3996:             $max = $passwdconf{'max'};
                   3997:             $numrules ++;
                   3998:         }
                   3999:         @chars = @{$passwdconf{'chars'}};
                   4000:         if (@chars) {
                   4001:             $numrules ++;
                   4002:         }
                   4003:     }
                   4004:     if ($min > 0) {
                   4005:         $numrules ++;
                   4006:     }
                   4007:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   4008:         if ($min) {
                   4009:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   4010:         }
                   4011:         if ($max) {
                   4012:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   4013:         }
                   4014:         my (@charalerts,@charrules);
                   4015:         if (@chars) {
                   4016:             if (grep(/^uc$/,@chars)) {
                   4017:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   4018:                 push(@charrules,'uc');
                   4019:             }
                   4020:             if (grep(/^lc$/,@chars)) {
                   4021:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   4022:                 push(@charrules,'lc');
                   4023:             }
                   4024:             if (grep(/^num$/,@chars)) {
                   4025:                 push(@charalerts,&mt('contain at least one number'));
                   4026:                 push(@charrules,'num');
                   4027:             }
                   4028:             if (grep(/^spec$/,@chars)) {
                   4029:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   4030:                 push(@charrules,'spec');
                   4031:             }
                   4032:         }
                   4033:         $intargjs = qq|            var rulesmsg = '';\n|.
                   4034:                     qq|            var currpwval = $currpasswdval;\n|;
                   4035:             if ($min) {
                   4036:                 $intargjs .= qq|
                   4037:             if (currpwval.length < $min) {
                   4038:                 rulesmsg += ' - $alert{min}';
                   4039:             }
                   4040: |;
                   4041:             }
                   4042:             if ($max) {
                   4043:                 $intargjs .= qq|
                   4044:             if (currpwval.length > $max) {
                   4045:                 rulesmsg += ' - $alert{max}';
                   4046:             }
                   4047: |;
                   4048:             }
                   4049:             if (@chars > 0) {
                   4050:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   4051:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   4052:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   4053:                              qq|            var charrules = new Array($charrulestr);\n|.
                   4054:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   4055:                 my %rules;
                   4056:                 map { $rules{$_} = 1; } @chars;
                   4057:                 if ($rules{'uc'}) {
                   4058:                     $intargjs .= qq|
                   4059:             var ucRegExp = /[A-Z]/;
                   4060:             if (!ucRegExp.test(currpwval)) {
                   4061:                 brokerules.push('uc');
                   4062:             }
                   4063: |;
                   4064:                 }
                   4065:                 if ($rules{'lc'}) {
                   4066:                     $intargjs .= qq|
                   4067:             var lcRegExp = /[a-z]/;
                   4068:             if (!lcRegExp.test(currpwval)) {
                   4069:                 brokerules.push('lc');
                   4070:             }
                   4071: |;
                   4072:                 }
                   4073:                 if ($rules{'num'}) {
                   4074:                      $intargjs .= qq|
                   4075:             var numRegExp = /[0-9]/;
                   4076:             if (!numRegExp.test(currpwval)) {
                   4077:                 brokerules.push('num');
                   4078:             }
                   4079: |;
                   4080:                 }
                   4081:                 if ($rules{'spec'}) {
                   4082:                      $intargjs .= q|
                   4083:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   4084:             if (!specRegExp.test(currpwval)) {
                   4085:                 brokerules.push('spec');
                   4086:             }
                   4087: |;
                   4088:                 }
                   4089:                 $intargjs .= qq|
                   4090:             if (brokerules.length > 0) {
                   4091:                 for (var i=0; i<brokerules.length; i++) {
                   4092:                     for (var j=0; j<charrules.length; j++) {
                   4093:                         if (brokerules[i] == charrules[j]) {
                   4094:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   4095:                             break;
                   4096:                         }
                   4097:                     }
                   4098:                 }
                   4099:             }
                   4100: |;
                   4101:             }
                   4102:             $intargjs .= qq|
                   4103:             if (rulesmsg != '') {
                   4104:                 rulesmsg = '$alertmsg'+rulesmsg;
                   4105:                 alert(rulesmsg);
                   4106:                 return false;
                   4107:             }
                   4108: |;
                   4109:     }
                   4110:     return ($numrules,$intargjs);
                   4111: }
                   4112: 
1.80      albertel 4113: ###############################################################
                   4114: ##    Get Kerberos Defaults for Domain                 ##
                   4115: ###############################################################
                   4116: ##
                   4117: ## Returns default kerberos version and an associated argument
                   4118: ## as listed in file domain.tab. If not listed, provides
                   4119: ## appropriate default domain and kerberos version.
                   4120: ##
                   4121: #-------------------------------------------
                   4122: 
                   4123: =pod
                   4124: 
1.648     raeburn  4125: =item * &get_kerberos_defaults()
1.80      albertel 4126: 
                   4127: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  4128: version and domain. If not found, it defaults to version 4 and the 
                   4129: domain of the server.
1.80      albertel 4130: 
1.648     raeburn  4131: =over 4
                   4132: 
1.80      albertel 4133: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   4134: 
1.648     raeburn  4135: =back
                   4136: 
                   4137: =back
                   4138: 
1.80      albertel 4139: =cut
                   4140: 
                   4141: #-------------------------------------------
                   4142: sub get_kerberos_defaults {
                   4143:     my $domain=shift;
1.641     raeburn  4144:     my ($krbdef,$krbdefdom);
                   4145:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   4146:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   4147:         $krbdef = $domdefaults{'auth_def'};
                   4148:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   4149:     } else {
1.80      albertel 4150:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   4151:         my $krbdefdom=$1;
                   4152:         $krbdefdom=~tr/a-z/A-Z/;
                   4153:         $krbdef = "krb4";
                   4154:     }
                   4155:     return ($krbdef,$krbdefdom);
                   4156: }
1.112     bowersj2 4157: 
1.32      matthew  4158: 
1.46      matthew  4159: ###############################################################
                   4160: ##                Thesaurus Functions                        ##
                   4161: ###############################################################
1.20      www      4162: 
1.46      matthew  4163: =pod
1.20      www      4164: 
1.112     bowersj2 4165: =head1 Thesaurus Functions
                   4166: 
                   4167: =over 4
                   4168: 
1.648     raeburn  4169: =item * &initialize_keywords()
1.46      matthew  4170: 
                   4171: Initializes the package variable %Keywords if it is empty.  Uses the
                   4172: package variable $thesaurus_db_file.
                   4173: 
                   4174: =cut
                   4175: 
                   4176: ###################################################
                   4177: 
                   4178: sub initialize_keywords {
                   4179:     return 1 if (scalar keys(%Keywords));
                   4180:     # If we are here, %Keywords is empty, so fill it up
                   4181:     #   Make sure the file we need exists...
                   4182:     if (! -e $thesaurus_db_file) {
                   4183:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   4184:                                  " failed because it does not exist");
                   4185:         return 0;
                   4186:     }
                   4187:     #   Set up the hash as a database
                   4188:     my %thesaurus_db;
                   4189:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4190:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4191:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   4192:                                  $thesaurus_db_file);
                   4193:         return 0;
                   4194:     } 
                   4195:     #  Get the average number of appearances of a word.
                   4196:     my $avecount = $thesaurus_db{'average.count'};
                   4197:     #  Put keywords (those that appear > average) into %Keywords
                   4198:     while (my ($word,$data)=each (%thesaurus_db)) {
                   4199:         my ($count,undef) = split /:/,$data;
                   4200:         $Keywords{$word}++ if ($count > $avecount);
                   4201:     }
                   4202:     untie %thesaurus_db;
                   4203:     # Remove special values from %Keywords.
1.356     albertel 4204:     foreach my $value ('total.count','average.count') {
                   4205:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  4206:   }
1.46      matthew  4207:     return 1;
                   4208: }
                   4209: 
                   4210: ###################################################
                   4211: 
                   4212: =pod
                   4213: 
1.648     raeburn  4214: =item * &keyword($word)
1.46      matthew  4215: 
                   4216: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   4217: than the average number of times in the thesaurus database.  Calls 
                   4218: &initialize_keywords
                   4219: 
                   4220: =cut
                   4221: 
                   4222: ###################################################
1.20      www      4223: 
                   4224: sub keyword {
1.46      matthew  4225:     return if (!&initialize_keywords());
                   4226:     my $word=lc(shift());
                   4227:     $word=~s/\W//g;
                   4228:     return exists($Keywords{$word});
1.20      www      4229: }
1.46      matthew  4230: 
                   4231: ###############################################################
                   4232: 
                   4233: =pod 
1.20      www      4234: 
1.648     raeburn  4235: =item * &get_related_words()
1.46      matthew  4236: 
1.160     matthew  4237: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  4238: an array of words.  If the keyword is not in the thesaurus, an empty array
                   4239: will be returned.  The order of the words returned is determined by the
                   4240: database which holds them.
                   4241: 
                   4242: Uses global $thesaurus_db_file.
                   4243: 
1.1057    foxr     4244: 
1.46      matthew  4245: =cut
                   4246: 
                   4247: ###############################################################
                   4248: sub get_related_words {
                   4249:     my $keyword = shift;
                   4250:     my %thesaurus_db;
                   4251:     if (! -e $thesaurus_db_file) {
                   4252:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   4253:                                  "failed because the file does not exist");
                   4254:         return ();
                   4255:     }
                   4256:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4257:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4258:         return ();
                   4259:     } 
                   4260:     my @Words=();
1.429     www      4261:     my $count=0;
1.46      matthew  4262:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 4263: 	# The first element is the number of times
                   4264: 	# the word appears.  We do not need it now.
1.429     www      4265: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   4266: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   4267: 	my $threshold=$mostfrequentcount/10;
                   4268:         foreach my $possibleword (@RelatedWords) {
                   4269:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   4270:             if ($wordcount>$threshold) {
                   4271: 		push(@Words,$word);
                   4272:                 $count++;
                   4273:                 if ($count>10) { last; }
                   4274: 	    }
1.20      www      4275:         }
                   4276:     }
1.46      matthew  4277:     untie %thesaurus_db;
                   4278:     return @Words;
1.14      harris41 4279: }
1.1090    foxr     4280: ###############################################################
                   4281: #
                   4282: #  Spell checking
                   4283: #
                   4284: 
                   4285: =pod
                   4286: 
1.1142    raeburn  4287: =back
                   4288: 
1.1090    foxr     4289: =head1 Spell checking
                   4290: 
                   4291: =over 4
                   4292: 
                   4293: =item * &check_spelling($wordlist $language)
                   4294: 
                   4295: Takes a string containing words and feeds it to an external
                   4296: spellcheck program via a pipeline. Returns a string containing
                   4297: them mis-spelled words.
                   4298: 
                   4299: Parameters:
                   4300: 
                   4301: =over 4
                   4302: 
                   4303: =item - $wordlist
                   4304: 
                   4305: String that will be fed into the spellcheck program.
                   4306: 
                   4307: =item - $language
                   4308: 
                   4309: Language string that specifies the language for which the spell
                   4310: check will be performed.
                   4311: 
                   4312: =back
                   4313: 
                   4314: =back
                   4315: 
                   4316: Note: This sub assumes that aspell is installed.
                   4317: 
                   4318: 
                   4319: =cut
                   4320: 
1.46      matthew  4321: 
1.1090    foxr     4322: sub check_spelling {
                   4323:     my ($wordlist, $language) = @_;
1.1091    foxr     4324:     my @misspellings;
                   4325:     
                   4326:     # Generate the speller and set the langauge.
                   4327:     # if explicitly selected:
1.1090    foxr     4328: 
1.1091    foxr     4329:     my $speller = Text::Aspell->new;
1.1090    foxr     4330:     if ($language) {
1.1091    foxr     4331: 	$speller->set_option('lang', $language);
1.1090    foxr     4332:     }
                   4333: 
1.1091    foxr     4334:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4335: 
1.1091    foxr     4336:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4337: 
1.1091    foxr     4338:     foreach my $word (@words) {
                   4339: 	if(! $speller->check($word)) {
                   4340: 	    push(@misspellings, $word);
1.1090    foxr     4341: 	}
                   4342:     }
1.1091    foxr     4343:     return join(' ', @misspellings);
                   4344:     
1.1090    foxr     4345: }
                   4346: 
1.61      www      4347: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4348: =pod
                   4349: 
1.112     bowersj2 4350: =head1 User Name Functions
                   4351: 
                   4352: =over 4
                   4353: 
1.648     raeburn  4354: =item * &plainname($uname,$udom,$first)
1.81      albertel 4355: 
1.112     bowersj2 4356: Takes a users logon name and returns it as a string in
1.226     albertel 4357: "first middle last generation" form 
                   4358: if $first is set to 'lastname' then it returns it as
                   4359: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4360: 
                   4361: =cut
1.61      www      4362: 
1.295     www      4363: 
1.81      albertel 4364: ###############################################################
1.61      www      4365: sub plainname {
1.226     albertel 4366:     my ($uname,$udom,$first)=@_;
1.537     albertel 4367:     return if (!defined($uname) || !defined($udom));
1.295     www      4368:     my %names=&getnames($uname,$udom);
1.226     albertel 4369:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4370: 					  $names{'middlename'},
                   4371: 					  $names{'lastname'},
                   4372: 					  $names{'generation'},$first);
                   4373:     $name=~s/^\s+//;
1.62      www      4374:     $name=~s/\s+$//;
                   4375:     $name=~s/\s+/ /g;
1.353     albertel 4376:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4377:     return $name;
1.61      www      4378: }
1.66      www      4379: 
                   4380: # -------------------------------------------------------------------- Nickname
1.81      albertel 4381: =pod
                   4382: 
1.648     raeburn  4383: =item * &nickname($uname,$udom)
1.81      albertel 4384: 
                   4385: Gets a users name and returns it as a string as
                   4386: 
                   4387: "&quot;nickname&quot;"
1.66      www      4388: 
1.81      albertel 4389: if the user has a nickname or
                   4390: 
                   4391: "first middle last generation"
                   4392: 
                   4393: if the user does not
                   4394: 
                   4395: =cut
1.66      www      4396: 
                   4397: sub nickname {
                   4398:     my ($uname,$udom)=@_;
1.537     albertel 4399:     return if (!defined($uname) || !defined($udom));
1.295     www      4400:     my %names=&getnames($uname,$udom);
1.68      albertel 4401:     my $name=$names{'nickname'};
1.66      www      4402:     if ($name) {
                   4403:        $name='&quot;'.$name.'&quot;'; 
                   4404:     } else {
                   4405:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4406: 	     $names{'lastname'}.' '.$names{'generation'};
                   4407:        $name=~s/\s+$//;
                   4408:        $name=~s/\s+/ /g;
                   4409:     }
                   4410:     return $name;
                   4411: }
                   4412: 
1.295     www      4413: sub getnames {
                   4414:     my ($uname,$udom)=@_;
1.537     albertel 4415:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4416:     if ($udom eq 'public' && $uname eq 'public') {
                   4417: 	return ('lastname' => &mt('Public'));
                   4418:     }
1.295     www      4419:     my $id=$uname.':'.$udom;
                   4420:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4421:     if ($cached) {
                   4422: 	return %{$names};
                   4423:     } else {
                   4424: 	my %loadnames=&Apache::lonnet::get('environment',
                   4425:                     ['firstname','middlename','lastname','generation','nickname'],
                   4426: 					 $udom,$uname);
                   4427: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4428: 	return %loadnames;
                   4429:     }
                   4430: }
1.61      www      4431: 
1.542     raeburn  4432: # -------------------------------------------------------------------- getemails
1.648     raeburn  4433: 
1.542     raeburn  4434: =pod
                   4435: 
1.648     raeburn  4436: =item * &getemails($uname,$udom)
1.542     raeburn  4437: 
                   4438: Gets a user's email information and returns it as a hash with keys:
                   4439: notification, critnotification, permanentemail
                   4440: 
                   4441: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4442: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4443:  
1.648     raeburn  4444: 
1.542     raeburn  4445: =cut
                   4446: 
1.648     raeburn  4447: 
1.466     albertel 4448: sub getemails {
                   4449:     my ($uname,$udom)=@_;
                   4450:     if ($udom eq 'public' && $uname eq 'public') {
                   4451: 	return;
                   4452:     }
1.467     www      4453:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4454:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4455:     my $id=$uname.':'.$udom;
                   4456:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4457:     if ($cached) {
                   4458: 	return %{$names};
                   4459:     } else {
                   4460: 	my %loadnames=&Apache::lonnet::get('environment',
                   4461:                     			   ['notification','critnotification',
                   4462: 					    'permanentemail'],
                   4463: 					   $udom,$uname);
                   4464: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4465: 	return %loadnames;
                   4466:     }
                   4467: }
                   4468: 
1.551     albertel 4469: sub flush_email_cache {
                   4470:     my ($uname,$udom)=@_;
                   4471:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4472:     if (!$uname) { $uname=$env{'user.name'};   }
                   4473:     return if ($udom eq 'public' && $uname eq 'public');
                   4474:     my $id=$uname.':'.$udom;
                   4475:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4476: }
                   4477: 
1.728     raeburn  4478: # -------------------------------------------------------------------- getlangs
                   4479: 
                   4480: =pod
                   4481: 
                   4482: =item * &getlangs($uname,$udom)
                   4483: 
                   4484: Gets a user's language preference and returns it as a hash with key:
                   4485: language.
                   4486: 
                   4487: =cut
                   4488: 
                   4489: 
                   4490: sub getlangs {
                   4491:     my ($uname,$udom) = @_;
                   4492:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4493:     if (!$uname) { $uname=$env{'user.name'};   }
                   4494:     my $id=$uname.':'.$udom;
                   4495:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4496:     if ($cached) {
                   4497:         return %{$langs};
                   4498:     } else {
                   4499:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4500:                                            $udom,$uname);
                   4501:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4502:         return %loadlangs;
                   4503:     }
                   4504: }
                   4505: 
                   4506: sub flush_langs_cache {
                   4507:     my ($uname,$udom)=@_;
                   4508:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4509:     if (!$uname) { $uname=$env{'user.name'};   }
                   4510:     return if ($udom eq 'public' && $uname eq 'public');
                   4511:     my $id=$uname.':'.$udom;
                   4512:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4513: }
                   4514: 
1.61      www      4515: # ------------------------------------------------------------------ Screenname
1.81      albertel 4516: 
                   4517: =pod
                   4518: 
1.648     raeburn  4519: =item * &screenname($uname,$udom)
1.81      albertel 4520: 
                   4521: Gets a users screenname and returns it as a string
                   4522: 
                   4523: =cut
1.61      www      4524: 
                   4525: sub screenname {
                   4526:     my ($uname,$udom)=@_;
1.258     albertel 4527:     if ($uname eq $env{'user.name'} &&
                   4528: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4529:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4530:     return $names{'screenname'};
1.62      www      4531: }
                   4532: 
1.212     albertel 4533: 
1.802     bisitz   4534: # ------------------------------------------------------------- Confirm Wrapper
                   4535: =pod
                   4536: 
1.1142    raeburn  4537: =item * &confirmwrapper($message)
1.802     bisitz   4538: 
                   4539: Wrap messages about completion of operation in box
                   4540: 
                   4541: =cut
                   4542: 
                   4543: sub confirmwrapper {
                   4544:     my ($message)=@_;
                   4545:     if ($message) {
                   4546:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4547:                .$message."\n"
                   4548:                .'</div>'."\n";
                   4549:     } else {
                   4550:         return $message;
                   4551:     }
                   4552: }
                   4553: 
1.62      www      4554: # ------------------------------------------------------------- Message Wrapper
                   4555: 
                   4556: sub messagewrapper {
1.369     www      4557:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4558:     return 
1.441     albertel 4559:         '<a href="/adm/email?compose=individual&amp;'.
                   4560:         'recname='.$username.'&amp;recdom='.$domain.
                   4561: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4562:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4563: }
1.802     bisitz   4564: 
1.74      www      4565: # --------------------------------------------------------------- Notes Wrapper
                   4566: 
                   4567: sub noteswrapper {
                   4568:     my ($link,$un,$do)=@_;
                   4569:     return 
1.896     amueller 4570: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4571: }
1.802     bisitz   4572: 
1.62      www      4573: # ------------------------------------------------------------- Aboutme Wrapper
                   4574: 
                   4575: sub aboutmewrapper {
1.1070    raeburn  4576:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4577:     if (!defined($username)  && !defined($domain)) {
                   4578:         return;
                   4579:     }
1.1096    raeburn  4580:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4581: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4582: }
                   4583: 
                   4584: # ------------------------------------------------------------ Syllabus Wrapper
                   4585: 
                   4586: sub syllabuswrapper {
1.707     bisitz   4587:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4588:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4589: }
1.14      harris41 4590: 
1.1397    raeburn  4591: # -----------------------------------------------------------------------------
                   4592: 
1.1396    raeburn  4593: sub aboutme_on {
                   4594:     my ($uname,$udom)=@_;
                   4595:     unless ($uname) { $uname=$env{'user.name'}; }
                   4596:     unless ($udom)  { $udom=$env{'user.domain'}; }
                   4597:     return if ($udom eq 'public' && $uname eq 'public');
                   4598:     my $hashkey=$uname.':'.$udom;
                   4599:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   4600:     if ($cached) {
                   4601:         return $aboutme;
                   4602:     }
                   4603:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   4604:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   4605:     return $aboutme;
                   4606: }
                   4607: 
                   4608: sub devalidate_aboutme_cache {
                   4609:     my ($uname,$udom)=@_;
                   4610:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4611:     if (!$uname) { $uname=$env{'user.name'};   }
                   4612:     return if ($udom eq 'public' && $uname eq 'public');
                   4613:     my $id=$uname.':'.$udom;
                   4614:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   4615: }
                   4616: 
1.208     matthew  4617: sub track_student_link {
1.887     raeburn  4618:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4619:     my $link ="/adm/trackstudent?";
1.208     matthew  4620:     my $title = 'View recent activity';
                   4621:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4622:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4623:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4624:         $title .= ' of this student';
1.268     albertel 4625:     } 
1.208     matthew  4626:     if (defined($target) && $target !~ /^\s*$/) {
                   4627:         $target = qq{target="$target"};
                   4628:     } else {
                   4629:         $target = '';
                   4630:     }
1.268     albertel 4631:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4632:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4633:     $title = &mt($title);
                   4634:     $linktext = &mt($linktext);
1.448     albertel 4635:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4636: 	&help_open_topic('View_recent_activity');
1.208     matthew  4637: }
                   4638: 
1.781     raeburn  4639: sub slot_reservations_link {
                   4640:     my ($linktext,$sname,$sdom,$target) = @_;
                   4641:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4642:     my $title = 'View slot reservation history';
                   4643:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4644:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4645:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4646:         $title .= ' of this student';
                   4647:     }
                   4648:     if (defined($target) && $target !~ /^\s*$/) {
                   4649:         $target = qq{target="$target"};
                   4650:     } else {
                   4651:         $target = '';
                   4652:     }
                   4653:     $title = &mt($title);
                   4654:     $linktext = &mt($linktext);
                   4655:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4656: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4657: 
                   4658: }
                   4659: 
1.508     www      4660: # ===================================================== Display a student photo
                   4661: 
                   4662: 
1.509     albertel 4663: sub student_image_tag {
1.508     www      4664:     my ($domain,$user)=@_;
                   4665:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4666:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4667: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4668:     } else {
                   4669: 	return '';
                   4670:     }
                   4671: }
                   4672: 
1.112     bowersj2 4673: =pod
                   4674: 
                   4675: =back
                   4676: 
                   4677: =head1 Access .tab File Data
                   4678: 
                   4679: =over 4
                   4680: 
1.648     raeburn  4681: =item * &languageids() 
1.112     bowersj2 4682: 
                   4683: returns list of all language ids
                   4684: 
                   4685: =cut
                   4686: 
1.14      harris41 4687: sub languageids {
1.16      harris41 4688:     return sort(keys(%language));
1.14      harris41 4689: }
                   4690: 
1.112     bowersj2 4691: =pod
                   4692: 
1.648     raeburn  4693: =item * &languagedescription() 
1.112     bowersj2 4694: 
                   4695: returns description of a specified language id
                   4696: 
                   4697: =cut
                   4698: 
1.14      harris41 4699: sub languagedescription {
1.125     www      4700:     my $code=shift;
                   4701:     return  ($supported_language{$code}?'* ':'').
                   4702:             $language{$code}.
1.126     www      4703: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4704: }
                   4705: 
1.1048    foxr     4706: =pod
                   4707: 
                   4708: =item * &plainlanguagedescription
                   4709: 
                   4710: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4711: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4712: 
                   4713: =cut
                   4714: 
1.145     www      4715: sub plainlanguagedescription {
                   4716:     my $code=shift;
                   4717:     return $language{$code};
                   4718: }
                   4719: 
1.1048    foxr     4720: =pod
                   4721: 
                   4722: =item * &supportedlanguagecode
                   4723: 
                   4724: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4725: code.
                   4726: 
                   4727: =cut
                   4728: 
1.145     www      4729: sub supportedlanguagecode {
                   4730:     my $code=shift;
                   4731:     return $supported_language{$code};
1.97      www      4732: }
                   4733: 
1.112     bowersj2 4734: =pod
                   4735: 
1.1048    foxr     4736: =item * &latexlanguage()
                   4737: 
                   4738: Given a language key code returns the correspondnig language to use
                   4739: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4740: is no supported hyphenation for the language code.
                   4741: 
                   4742: =cut
                   4743: 
                   4744: sub latexlanguage {
                   4745:     my $code = shift;
                   4746:     return $latex_language{$code};
                   4747: }
                   4748: 
                   4749: =pod
                   4750: 
                   4751: =item * &latexhyphenation()
                   4752: 
                   4753: Same as above but what's supplied is the language as it might be stored
                   4754: in the metadata.
                   4755: 
                   4756: =cut
                   4757: 
                   4758: sub latexhyphenation {
                   4759:     my $key = shift;
                   4760:     return $latex_language_bykey{$key};
                   4761: }
                   4762: 
                   4763: =pod
                   4764: 
1.648     raeburn  4765: =item * &copyrightids() 
1.112     bowersj2 4766: 
                   4767: returns list of all copyrights
                   4768: 
                   4769: =cut
                   4770: 
                   4771: sub copyrightids {
                   4772:     return sort(keys(%cprtag));
                   4773: }
                   4774: 
                   4775: =pod
                   4776: 
1.648     raeburn  4777: =item * &copyrightdescription() 
1.112     bowersj2 4778: 
                   4779: returns description of a specified copyright id
                   4780: 
                   4781: =cut
                   4782: 
                   4783: sub copyrightdescription {
1.166     www      4784:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4785: }
1.197     matthew  4786: 
                   4787: =pod
                   4788: 
1.648     raeburn  4789: =item * &source_copyrightids() 
1.192     taceyjo1 4790: 
                   4791: returns list of all source copyrights
                   4792: 
                   4793: =cut
                   4794: 
                   4795: sub source_copyrightids {
                   4796:     return sort(keys(%scprtag));
                   4797: }
                   4798: 
                   4799: =pod
                   4800: 
1.648     raeburn  4801: =item * &source_copyrightdescription() 
1.192     taceyjo1 4802: 
                   4803: returns description of a specified source copyright id
                   4804: 
                   4805: =cut
                   4806: 
                   4807: sub source_copyrightdescription {
                   4808:     return &mt($scprtag{shift(@_)});
                   4809: }
1.112     bowersj2 4810: 
                   4811: =pod
                   4812: 
1.648     raeburn  4813: =item * &filecategories() 
1.112     bowersj2 4814: 
                   4815: returns list of all file categories
                   4816: 
                   4817: =cut
                   4818: 
                   4819: sub filecategories {
                   4820:     return sort(keys(%category_extensions));
                   4821: }
                   4822: 
                   4823: =pod
                   4824: 
1.648     raeburn  4825: =item * &filecategorytypes() 
1.112     bowersj2 4826: 
                   4827: returns list of file types belonging to a given file
                   4828: category
                   4829: 
                   4830: =cut
                   4831: 
                   4832: sub filecategorytypes {
1.356     albertel 4833:     my ($cat) = @_;
1.1248    raeburn  4834:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4835:         return @{$category_extensions{lc($cat)}};
                   4836:     } else {
                   4837:         return ();
                   4838:     }
1.112     bowersj2 4839: }
                   4840: 
                   4841: =pod
                   4842: 
1.648     raeburn  4843: =item * &fileembstyle() 
1.112     bowersj2 4844: 
                   4845: returns embedding style for a specified file type
                   4846: 
                   4847: =cut
                   4848: 
                   4849: sub fileembstyle {
                   4850:     return $fe{lc(shift(@_))};
1.169     www      4851: }
                   4852: 
1.351     www      4853: sub filemimetype {
                   4854:     return $fm{lc(shift(@_))};
                   4855: }
                   4856: 
1.169     www      4857: 
                   4858: sub filecategoryselect {
                   4859:     my ($name,$value)=@_;
1.189     matthew  4860:     return &select_form($value,$name,
1.970     raeburn  4861:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4862: }
                   4863: 
                   4864: =pod
                   4865: 
1.648     raeburn  4866: =item * &filedescription() 
1.112     bowersj2 4867: 
                   4868: returns description for a specified file type
                   4869: 
                   4870: =cut
                   4871: 
                   4872: sub filedescription {
1.188     matthew  4873:     my $file_description = $fd{lc(shift())};
                   4874:     $file_description =~ s:([\[\]]):~$1:g;
                   4875:     return &mt($file_description);
1.112     bowersj2 4876: }
                   4877: 
                   4878: =pod
                   4879: 
1.648     raeburn  4880: =item * &filedescriptionex() 
1.112     bowersj2 4881: 
                   4882: returns description for a specified file type with
                   4883: extra formatting
                   4884: 
                   4885: =cut
                   4886: 
                   4887: sub filedescriptionex {
                   4888:     my $ex=shift;
1.188     matthew  4889:     my $file_description = $fd{lc($ex)};
                   4890:     $file_description =~ s:([\[\]]):~$1:g;
                   4891:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4892: }
                   4893: 
                   4894: # End of .tab access
                   4895: =pod
                   4896: 
                   4897: =back
                   4898: 
                   4899: =cut
                   4900: 
                   4901: # ------------------------------------------------------------------ File Types
                   4902: sub fileextensions {
                   4903:     return sort(keys(%fe));
                   4904: }
                   4905: 
1.97      www      4906: # ----------------------------------------------------------- Display Languages
                   4907: # returns a hash with all desired display languages
                   4908: #
                   4909: 
                   4910: sub display_languages {
                   4911:     my %languages=();
1.695     raeburn  4912:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4913: 	$languages{$lang}=1;
1.97      www      4914:     }
                   4915:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4916:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4917: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4918: 	    $languages{$lang}=1;
1.97      www      4919:         }
                   4920:     }
                   4921:     return %languages;
1.14      harris41 4922: }
                   4923: 
1.582     albertel 4924: sub languages {
                   4925:     my ($possible_langs) = @_;
1.695     raeburn  4926:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4927:     if (!ref($possible_langs)) {
                   4928: 	if( wantarray ) {
                   4929: 	    return @preferred_langs;
                   4930: 	} else {
                   4931: 	    return $preferred_langs[0];
                   4932: 	}
                   4933:     }
                   4934:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4935:     my @preferred_possibilities;
                   4936:     foreach my $preferred_lang (@preferred_langs) {
                   4937: 	if (exists($possibilities{$preferred_lang})) {
                   4938: 	    push(@preferred_possibilities, $preferred_lang);
                   4939: 	}
                   4940:     }
                   4941:     if( wantarray ) {
                   4942: 	return @preferred_possibilities;
                   4943:     }
                   4944:     return $preferred_possibilities[0];
                   4945: }
                   4946: 
1.742     raeburn  4947: sub user_lang {
                   4948:     my ($touname,$toudom,$fromcid) = @_;
                   4949:     my @userlangs;
                   4950:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4951:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4952:                     $env{'course.'.$fromcid.'.languages'}));
                   4953:     } else {
                   4954:         my %langhash = &getlangs($touname,$toudom);
                   4955:         if ($langhash{'languages'} ne '') {
                   4956:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4957:         } else {
                   4958:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4959:             if ($domdefs{'lang_def'} ne '') {
                   4960:                 @userlangs = ($domdefs{'lang_def'});
                   4961:             }
                   4962:         }
                   4963:     }
                   4964:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4965:     my $user_lh = Apache::localize->get_handle(@languages);
                   4966:     return $user_lh;
                   4967: }
                   4968: 
                   4969: 
1.112     bowersj2 4970: ###############################################################
                   4971: ##               Student Answer Attempts                     ##
                   4972: ###############################################################
                   4973: 
                   4974: =pod
                   4975: 
                   4976: =head1 Alternate Problem Views
                   4977: 
                   4978: =over 4
                   4979: 
1.648     raeburn  4980: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4981:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4982: 
                   4983: Return string with previous attempt on problem. Arguments:
                   4984: 
                   4985: =over 4
                   4986: 
                   4987: =item * $symb: Problem, including path
                   4988: 
                   4989: =item * $username: username of the desired student
                   4990: 
                   4991: =item * $domain: domain of the desired student
1.14      harris41 4992: 
1.112     bowersj2 4993: =item * $course: Course ID
1.14      harris41 4994: 
1.112     bowersj2 4995: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4996:     something
1.14      harris41 4997: 
1.112     bowersj2 4998: =item * $regexp: if string matches this regexp, the string will be
                   4999:     sent to $gradesub
1.14      harris41 5000: 
1.112     bowersj2 5001: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 5002: 
1.1199    raeburn  5003: =item * $usec: section of the desired student
                   5004: 
                   5005: =item * $identifier: counter for student (multiple students one problem) or 
                   5006:     problem (one student; whole sequence).
                   5007: 
1.112     bowersj2 5008: =back
1.14      harris41 5009: 
1.112     bowersj2 5010: The output string is a table containing all desired attempts, if any.
1.16      harris41 5011: 
1.112     bowersj2 5012: =cut
1.1       albertel 5013: 
                   5014: sub get_previous_attempt {
1.1199    raeburn  5015:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 5016:   my $prevattempts='';
1.43      ng       5017:   no strict 'refs';
1.1       albertel 5018:   if ($symb) {
1.3       albertel 5019:     my (%returnhash)=
                   5020:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 5021:     if ($returnhash{'version'}) {
                   5022:       my %lasthash=();
                   5023:       my $version;
                   5024:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  5025:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   5026:             if ($key =~ /\.rawrndseed$/) {
                   5027:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   5028:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   5029:             } else {
                   5030:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   5031:             }
1.19      harris41 5032:         }
1.1       albertel 5033:       }
1.596     albertel 5034:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   5035:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  5036:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  5037:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 5038:       foreach my $key (sort(keys(%lasthash))) {
                   5039: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       5040: 	if ($#parts > 0) {
1.31      albertel 5041: 	  my $data=$parts[-1];
1.989     raeburn  5042:           next if ($data eq 'foilorder');
1.31      albertel 5043: 	  pop(@parts);
1.1010    www      5044:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  5045:           if ($data eq 'type') {
                   5046:               unless ($showsurv) {
                   5047:                   my $id = join(',',@parts);
                   5048:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  5049:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   5050:                       $lasthidden{$ign.'.'.$id} = 1;
                   5051:                   }
1.945     raeburn  5052:               }
1.1199    raeburn  5053:               if ($identifier ne '') {
                   5054:                   my $id = join(',',@parts);
                   5055:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   5056:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   5057:                       $hidestatus{$ign.'.'.$id} = 1;
                   5058:                   }
                   5059:               }
                   5060:           } elsif ($data eq 'regrader') {
                   5061:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  5062:                   my $id = join(',',@parts);
                   5063:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  5064:               }
1.1010    www      5065:           } 
1.31      albertel 5066: 	} else {
1.41      ng       5067: 	  if ($#parts == 0) {
                   5068: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   5069: 	  } else {
                   5070: 	    $prevattempts.='<th>'.$ign.'</th>';
                   5071: 	  }
1.31      albertel 5072: 	}
1.16      harris41 5073:       }
1.596     albertel 5074:       $prevattempts.=&end_data_table_header_row();
1.40      ng       5075:       if ($getattempt eq '') {
1.1199    raeburn  5076:         my (%solved,%resets,%probstatus);
1.1200    raeburn  5077:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   5078:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   5079:                 foreach my $id (keys(%regraded)) {
                   5080:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   5081:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   5082:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   5083:                         push(@{$resets{$id}},$version);
1.1199    raeburn  5084:                     }
                   5085:                 }
                   5086:             }
1.1200    raeburn  5087:         }
                   5088: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  5089:             my (@hidden,@unsolved);
1.945     raeburn  5090:             if (%typeparts) {
                   5091:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  5092:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   5093:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  5094:                         push(@hidden,$id);
1.1199    raeburn  5095:                     } elsif ($identifier ne '') {
                   5096:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   5097:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   5098:                                 ($hidestatus{$id})) {
1.1200    raeburn  5099:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  5100:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   5101:                                 push(@{$solved{$id}},$version);
                   5102:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   5103:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   5104:                                 my $skip;
                   5105:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   5106:                                     foreach my $reset (@{$resets{$id}}) {
                   5107:                                         if ($reset > $solved{$id}[-1]) {
                   5108:                                             $skip=1;
                   5109:                                             last;
                   5110:                                         }
                   5111:                                     }
                   5112:                                 }
                   5113:                                 unless ($skip) {
                   5114:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   5115:                                     push(@unsolved,$partslist);
                   5116:                                 }
                   5117:                             }
                   5118:                         }
1.945     raeburn  5119:                     }
                   5120:                 }
                   5121:             }
                   5122:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  5123:                            '<td>'.&mt('Transaction [_1]',$version);
                   5124:             if (@unsolved) {
                   5125:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   5126:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   5127:                                  &mt('Hide').'</label></span>';
                   5128:             }
                   5129:             $prevattempts .= '</td>';
1.945     raeburn  5130:             if (@hidden) {
                   5131:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5132:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  5133:                     my $hide;
                   5134:                     foreach my $id (@hidden) {
                   5135:                         if ($key =~ /^\Q$id\E/) {
                   5136:                             $hide = 1;
                   5137:                             last;
                   5138:                         }
                   5139:                     }
                   5140:                     if ($hide) {
                   5141:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5142:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5143:                             my $value = &format_previous_attempt_value($key,
                   5144:                                              $returnhash{$version.':'.$key});
1.1173    kruse    5145:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5146:                         } else {
                   5147:                             $prevattempts.='<td>&nbsp;</td>';
                   5148:                         }
                   5149:                     } else {
                   5150:                         if ($key =~ /\./) {
1.1212    raeburn  5151:                             my $value = $returnhash{$version.':'.$key};
                   5152:                             if ($key =~ /\.rndseed$/) {
                   5153:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5154:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5155:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5156:                                 }
                   5157:                             }
                   5158:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5159:                                            '&nbsp;</td>';
1.945     raeburn  5160:                         } else {
                   5161:                             $prevattempts.='<td>&nbsp;</td>';
                   5162:                         }
                   5163:                     }
                   5164:                 }
                   5165:             } else {
                   5166: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5167:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  5168:                     my $value = $returnhash{$version.':'.$key};
                   5169:                     if ($key =~ /\.rndseed$/) {
                   5170:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5171:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5172:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5173:                         }
                   5174:                     }
                   5175:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5176:                                    '&nbsp;</td>';
1.945     raeburn  5177: 	        }
                   5178:             }
                   5179: 	    $prevattempts.=&end_data_table_row();
1.40      ng       5180: 	 }
1.1       albertel 5181:       }
1.945     raeburn  5182:       my @currhidden = keys(%lasthidden);
1.596     albertel 5183:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 5184:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5185:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  5186:           if (%typeparts) {
                   5187:               my $hidden;
                   5188:               foreach my $id (@currhidden) {
                   5189:                   if ($key =~ /^\Q$id\E/) {
                   5190:                       $hidden = 1;
                   5191:                       last;
                   5192:                   }
                   5193:               }
                   5194:               if ($hidden) {
                   5195:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5196:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5197:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5198:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5199:                           $value = &$gradesub($value);
                   5200:                       }
1.1173    kruse    5201:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  5202:                   } else {
                   5203:                       $prevattempts.='<td>&nbsp;</td>';
                   5204:                   }
                   5205:               } else {
                   5206:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5207:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5208:                       $value = &$gradesub($value);
                   5209:                   }
1.1173    kruse    5210:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5211:               }
                   5212:           } else {
                   5213: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5214: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5215:                   $value = &$gradesub($value);
                   5216:               }
1.1173    kruse    5217: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5218:           }
1.16      harris41 5219:       }
1.596     albertel 5220:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 5221:     } else {
1.1305    raeburn  5222:       my $msg;
                   5223:       if ($symb =~ /ext\.tool$/) {
                   5224:           $msg = &mt('No grade passed back.');
                   5225:       } else {
                   5226:           $msg = &mt('Nothing submitted - no attempts.');
                   5227:       }
1.596     albertel 5228:       $prevattempts=
                   5229: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  5230: 	  '<td>'.$msg.'</td>'.
1.596     albertel 5231: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5232:     }
                   5233:   } else {
1.596     albertel 5234:     $prevattempts=
                   5235: 	  &start_data_table().&start_data_table_row().
                   5236: 	  '<td>'.&mt('No data.').'</td>'.
                   5237: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5238:   }
1.10      albertel 5239: }
                   5240: 
1.581     albertel 5241: sub format_previous_attempt_value {
                   5242:     my ($key,$value) = @_;
1.1011    www      5243:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    5244:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 5245:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    5246:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  5247:     } elsif ($key =~ /answerstring$/) {
                   5248:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    5249:         my @answer = %answers;
                   5250:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  5251:         my @anskeys = sort(keys(%answers));
                   5252:         if (@anskeys == 1) {
                   5253:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  5254:             if ($answer =~ m{\0}) {
                   5255:                 $answer =~ s{\0}{,}g;
1.988     raeburn  5256:             }
                   5257:             my $tag_internal_answer_name = 'INTERNAL';
                   5258:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   5259:                 $value = $answer; 
                   5260:             } else {
                   5261:                 $value = $anskeys[0].'='.$answer;
                   5262:             }
                   5263:         } else {
                   5264:             foreach my $ans (@anskeys) {
                   5265:                 my $answer = $answers{$ans};
1.1001    raeburn  5266:                 if ($answer =~ m{\0}) {
                   5267:                     $answer =~ s{\0}{,}g;
1.988     raeburn  5268:                 }
                   5269:                 $value .=  $ans.'='.$answer.'<br />';;
                   5270:             } 
                   5271:         }
1.581     albertel 5272:     } else {
1.1173    kruse    5273:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 5274:     }
                   5275:     return $value;
                   5276: }
                   5277: 
                   5278: 
1.107     albertel 5279: sub relative_to_absolute {
                   5280:     my ($url,$output)=@_;
                   5281:     my $parser=HTML::TokeParser->new(\$output);
                   5282:     my $token;
                   5283:     my $thisdir=$url;
                   5284:     my @rlinks=();
                   5285:     while ($token=$parser->get_token) {
                   5286: 	if ($token->[0] eq 'S') {
                   5287: 	    if ($token->[1] eq 'a') {
                   5288: 		if ($token->[2]->{'href'}) {
                   5289: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   5290: 		}
                   5291: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   5292: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   5293: 	    } elsif ($token->[1] eq 'base') {
                   5294: 		$thisdir=$token->[2]->{'href'};
                   5295: 	    }
                   5296: 	}
                   5297:     }
                   5298:     $thisdir=~s-/[^/]*$--;
1.356     albertel 5299:     foreach my $link (@rlinks) {
1.726     raeburn  5300: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 5301: 		($link=~/^\//) ||
                   5302: 		($link=~/^javascript:/i) ||
                   5303: 		($link=~/^mailto:/i) ||
                   5304: 		($link=~/^\#/)) {
                   5305: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   5306: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 5307: 	}
                   5308:     }
                   5309: # -------------------------------------------------- Deal with Applet codebases
                   5310:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   5311:     return $output;
                   5312: }
                   5313: 
1.112     bowersj2 5314: =pod
                   5315: 
1.648     raeburn  5316: =item * &get_student_view()
1.112     bowersj2 5317: 
                   5318: show a snapshot of what student was looking at
                   5319: 
                   5320: =cut
                   5321: 
1.10      albertel 5322: sub get_student_view {
1.186     albertel 5323:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      5324:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5325:   my (%form);
1.10      albertel 5326:   my @elements=('symb','courseid','domain','username');
                   5327:   foreach my $element (@elements) {
1.186     albertel 5328:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5329:   }
1.186     albertel 5330:   if (defined($moreenv)) {
                   5331:       %form=(%form,%{$moreenv});
                   5332:   }
1.236     albertel 5333:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 5334:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  5335:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   5336:       $feedurl =~ s{^/adm/wrapper}{};
                   5337:   }
1.650     www      5338:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5339:   $userview=~s/\<body[^\>]*\>//gi;
                   5340:   $userview=~s/\<\/body\>//gi;
                   5341:   $userview=~s/\<html\>//gi;
                   5342:   $userview=~s/\<\/html\>//gi;
                   5343:   $userview=~s/\<head\>//gi;
                   5344:   $userview=~s/\<\/head\>//gi;
                   5345:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5346:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5347:   if (wantarray) {
                   5348:      return ($userview,$response);
                   5349:   } else {
                   5350:      return $userview;
                   5351:   }
                   5352: }
                   5353: 
                   5354: sub get_student_view_with_retries {
                   5355:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5356: 
                   5357:     my $ok = 0;                 # True if we got a good response.
                   5358:     my $content;
                   5359:     my $response;
                   5360: 
                   5361:     # Try to get the student_view done. within the retries count:
                   5362:     
                   5363:     do {
                   5364:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5365:          $ok      = $response->is_success;
                   5366:          if (!$ok) {
                   5367:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5368:          }
                   5369:          $retries--;
                   5370:     } while (!$ok && ($retries > 0));
                   5371:     
                   5372:     if (!$ok) {
                   5373:        $content = '';          # On error return an empty content.
                   5374:     }
1.651     www      5375:     if (wantarray) {
                   5376:        return ($content, $response);
                   5377:     } else {
                   5378:        return $content;
                   5379:     }
1.11      albertel 5380: }
                   5381: 
1.1349    raeburn  5382: sub css_links {
                   5383:     my ($currsymb,$level) = @_;
                   5384:     my ($links,@symbs,%cssrefs,%httpref);
                   5385:     if ($level eq 'map') {
                   5386:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5387:         if (ref($navmap)) {
                   5388:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5389:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5390:             foreach my $res (@resources) {
                   5391:                 if (ref($res) && $res->symb()) {
                   5392:                     push(@symbs,$res->symb());
                   5393:                 }
                   5394:             }
                   5395:         }
                   5396:     } else {
                   5397:         @symbs = ($currsymb);
                   5398:     }
                   5399:     foreach my $symb (@symbs) {
                   5400:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5401:         if ($css_href =~ /\S/) {
                   5402:             unless ($css_href =~ m{https?://}) {
                   5403:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5404:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5405:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5406:                 unless ($css_href =~ m{^/}) {
                   5407:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5408:                 }
                   5409:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5410:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5411:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5412:                         my $thisurl = $proburl;
                   5413:                         if ($env{'httpref.'.$proburl}) {
                   5414:                             $thisurl = $env{'httpref.'.$proburl};
                   5415:                         }
                   5416:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5417:                     }
                   5418:                 }
                   5419:             }
                   5420:             $cssrefs{$css_href} = 1;
                   5421:         }
                   5422:     }
                   5423:     if (keys(%httpref)) {
                   5424:         &Apache::lonnet::appenv(\%httpref);
                   5425:     }
                   5426:     if (keys(%cssrefs)) {
                   5427:         foreach my $css_href (keys(%cssrefs)) {
                   5428:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5429:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5430:         }
                   5431:     }
                   5432:     return $links;
                   5433: }
                   5434: 
1.112     bowersj2 5435: =pod
                   5436: 
1.648     raeburn  5437: =item * &get_student_answers() 
1.112     bowersj2 5438: 
                   5439: show a snapshot of how student was answering problem
                   5440: 
                   5441: =cut
                   5442: 
1.11      albertel 5443: sub get_student_answers {
1.100     sakharuk 5444:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5445:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5446:   my (%moreenv);
1.11      albertel 5447:   my @elements=('symb','courseid','domain','username');
                   5448:   foreach my $element (@elements) {
1.186     albertel 5449:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5450:   }
1.186     albertel 5451:   $moreenv{'grade_target'}='answer';
                   5452:   %moreenv=(%form,%moreenv);
1.497     raeburn  5453:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5454:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5455:   return $userview;
1.1       albertel 5456: }
1.116     albertel 5457: 
                   5458: =pod
                   5459: 
                   5460: =item * &submlink()
                   5461: 
1.242     albertel 5462: Inputs: $text $uname $udom $symb $target
1.116     albertel 5463: 
                   5464: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5465: 
                   5466: =cut
                   5467: 
                   5468: ###############################################
                   5469: sub submlink {
1.242     albertel 5470:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5471:     if (!($uname && $udom)) {
                   5472: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5473: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5474: 	if (!$symb) { $symb=$cursymb; }
                   5475:     }
1.254     matthew  5476:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5477:     $symb=&escape($symb);
1.960     bisitz   5478:     if ($target) { $target=" target=\"$target\""; }
                   5479:     return
                   5480:         '<a href="/adm/grades?command=submission'.
                   5481:         '&amp;symb='.$symb.
                   5482:         '&amp;student='.$uname.
                   5483:         '&amp;userdom='.$udom.'"'.
                   5484:         $target.'>'.$text.'</a>';
1.242     albertel 5485: }
                   5486: ##############################################
                   5487: 
                   5488: =pod
                   5489: 
                   5490: =item * &pgrdlink()
                   5491: 
                   5492: Inputs: $text $uname $udom $symb $target
                   5493: 
                   5494: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5495: 
                   5496: =cut
                   5497: 
                   5498: ###############################################
                   5499: sub pgrdlink {
                   5500:     my $link=&submlink(@_);
                   5501:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5502:     return $link;
                   5503: }
                   5504: ##############################################
                   5505: 
                   5506: =pod
                   5507: 
                   5508: =item * &pprmlink()
                   5509: 
                   5510: Inputs: $text $uname $udom $symb $target
                   5511: 
                   5512: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5513: student and a specific resource
1.242     albertel 5514: 
                   5515: =cut
                   5516: 
                   5517: ###############################################
                   5518: sub pprmlink {
                   5519:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5520:     if (!($uname && $udom)) {
                   5521: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5522: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5523: 	if (!$symb) { $symb=$cursymb; }
                   5524:     }
1.254     matthew  5525:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5526:     $symb=&escape($symb);
1.242     albertel 5527:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5528:     return '<a href="/adm/parmset?command=set&amp;'.
                   5529: 	'symb='.$symb.'&amp;uname='.$uname.
                   5530: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5531: }
                   5532: ##############################################
1.37      matthew  5533: 
1.112     bowersj2 5534: =pod
                   5535: 
                   5536: =back
                   5537: 
                   5538: =cut
                   5539: 
1.37      matthew  5540: ###############################################
1.51      www      5541: 
                   5542: 
                   5543: sub timehash {
1.687     raeburn  5544:     my ($thistime) = @_;
                   5545:     my $timezone = &Apache::lonlocal::gettimezone();
                   5546:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5547:                      ->set_time_zone($timezone);
                   5548:     my $wday = $dt->day_of_week();
                   5549:     if ($wday == 7) { $wday = 0; }
                   5550:     return ( 'second' => $dt->second(),
                   5551:              'minute' => $dt->minute(),
                   5552:              'hour'   => $dt->hour(),
                   5553:              'day'     => $dt->day_of_month(),
                   5554:              'month'   => $dt->month(),
                   5555:              'year'    => $dt->year(),
                   5556:              'weekday' => $wday,
                   5557:              'dayyear' => $dt->day_of_year(),
                   5558:              'dlsav'   => $dt->is_dst() );
1.51      www      5559: }
                   5560: 
1.370     www      5561: sub utc_string {
                   5562:     my ($date)=@_;
1.371     www      5563:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5564: }
                   5565: 
1.51      www      5566: sub maketime {
                   5567:     my %th=@_;
1.687     raeburn  5568:     my ($epoch_time,$timezone,$dt);
                   5569:     $timezone = &Apache::lonlocal::gettimezone();
                   5570:     eval {
                   5571:         $dt = DateTime->new( year   => $th{'year'},
                   5572:                              month  => $th{'month'},
                   5573:                              day    => $th{'day'},
                   5574:                              hour   => $th{'hour'},
                   5575:                              minute => $th{'minute'},
                   5576:                              second => $th{'second'},
                   5577:                              time_zone => $timezone,
                   5578:                          );
                   5579:     };
                   5580:     if (!$@) {
                   5581:         $epoch_time = $dt->epoch;
                   5582:         if ($epoch_time) {
                   5583:             return $epoch_time;
                   5584:         }
                   5585:     }
1.51      www      5586:     return POSIX::mktime(
                   5587:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5588:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5589: }
                   5590: 
                   5591: #########################################
1.51      www      5592: 
                   5593: sub findallcourses {
1.482     raeburn  5594:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5595:     my %roles;
                   5596:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5597:     my %courses;
1.51      www      5598:     my $now=time;
1.482     raeburn  5599:     if (!defined($uname)) {
                   5600:         $uname = $env{'user.name'};
                   5601:     }
                   5602:     if (!defined($udom)) {
                   5603:         $udom = $env{'user.domain'};
                   5604:     }
                   5605:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5606:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5607:         if (!%roles) {
                   5608:             %roles = (
                   5609:                        cc => 1,
1.907     raeburn  5610:                        co => 1,
1.482     raeburn  5611:                        in => 1,
                   5612:                        ep => 1,
                   5613:                        ta => 1,
                   5614:                        cr => 1,
                   5615:                        st => 1,
                   5616:              );
                   5617:         }
                   5618:         foreach my $entry (keys(%roleshash)) {
                   5619:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5620:             if ($trole =~ /^cr/) { 
                   5621:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5622:             } else {
                   5623:                 next if (!exists($roles{$trole}));
                   5624:             }
                   5625:             if ($tend) {
                   5626:                 next if ($tend < $now);
                   5627:             }
                   5628:             if ($tstart) {
                   5629:                 next if ($tstart > $now);
                   5630:             }
1.1058    raeburn  5631:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5632:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5633:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5634:             if ($secpart eq '') {
                   5635:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5636:                 $sec = 'none';
1.1058    raeburn  5637:                 $value .= $cnum.'/';
1.482     raeburn  5638:             } else {
                   5639:                 $cnum = $cnumpart;
                   5640:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5641:                 $value .= $cnum.'/'.$sec;
                   5642:             }
                   5643:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5644:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5645:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5646:                 }
                   5647:             } else {
                   5648:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5649:             }
1.482     raeburn  5650:         }
                   5651:     } else {
                   5652:         foreach my $key (keys(%env)) {
1.483     albertel 5653: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5654:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5655: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5656: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5657: 	        next if (%roles && !exists($roles{$role}));
                   5658: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5659:                 my $active=1;
                   5660:                 if ($starttime) {
                   5661: 		    if ($now<$starttime) { $active=0; }
                   5662:                 }
                   5663:                 if ($endtime) {
                   5664:                     if ($now>$endtime) { $active=0; }
                   5665:                 }
                   5666:                 if ($active) {
1.1058    raeburn  5667:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5668:                     if ($sec eq '') {
                   5669:                         $sec = 'none';
1.1058    raeburn  5670:                     } else {
                   5671:                         $value .= $sec;
                   5672:                     }
                   5673:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5674:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5675:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5676:                         }
                   5677:                     } else {
                   5678:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5679:                     }
1.474     raeburn  5680:                 }
                   5681:             }
1.51      www      5682:         }
                   5683:     }
1.474     raeburn  5684:     return %courses;
1.51      www      5685: }
1.37      matthew  5686: 
1.54      www      5687: ###############################################
1.474     raeburn  5688: 
                   5689: sub blockcheck {
1.1372    raeburn  5690:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5691:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5692:         my ($has_evb,$check_ipaccess);
                   5693:         my $dom = $env{'user.domain'};
                   5694:         if ($env{'request.course.id'}) {
                   5695:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5696:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5697:             my $checkrole = "cm./$cdom/$cnum";
                   5698:             my $sec = $env{'request.course.sec'};
                   5699:             if ($sec ne '') {
                   5700:                 $checkrole .= "/$sec";
                   5701:             }
                   5702:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5703:                 ($env{'request.role'} !~ /^st/)) {
                   5704:                 $has_evb = 1;
                   5705:             }
                   5706:             unless ($has_evb) {
                   5707:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
1.1444    raeburn  5708:                     ($activity eq 'index') || ($activity eq 'boards') || ($activity eq 'groups') || 
                   5709:                     ($activity eq 'chat')) {
1.1372    raeburn  5710:                     if ($udom eq $cdom) {
                   5711:                         $check_ipaccess = 1;
                   5712:                     }
                   5713:                 }
                   5714:             }
1.1375    raeburn  5715:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5716:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5717:             my $checkrole;
                   5718:             if ($env{'request.role.domain'} eq '') {
                   5719:                 $checkrole = "cm./$env{'user.domain'}/";
                   5720:             } else {
                   5721:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5722:             }
                   5723:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5724:                 $has_evb = 1;
                   5725:             }
1.1372    raeburn  5726:         }
                   5727:         unless ($has_evb || $check_ipaccess) {
                   5728:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5729:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5730:                 $dom = $udom;
                   5731:             }
                   5732:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5733:                 $check_ipaccess = 1;
                   5734:             } else {
                   5735:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5736:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5737:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5738:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5739:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5740:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5741:                         $check_ipaccess = 1;
                   5742:                     }
                   5743:                 }
                   5744:             }
                   5745:         }
                   5746:         if ($check_ipaccess) {
                   5747:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5748:             unless (defined($cached)) {
                   5749:                 my %domconfig =
                   5750:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5751:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5752:             }
                   5753:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5754:                 foreach my $id (keys(%{$ipaccessref})) {
                   5755:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5756:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5757:                         if ($range) {
                   5758:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5759:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5760:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5761:                                         return ('','','',$id,$dom);
                   5762:                                         last;
                   5763:                                     }
                   5764:                                 }
                   5765:                             }
                   5766:                         }
                   5767:                     }
                   5768:                 }
                   5769:             }
                   5770:         }
1.1373    raeburn  5771:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5772:             return ();
                   5773:         }
1.1372    raeburn  5774:     }
1.1189    raeburn  5775:     if (defined($udom) && defined($uname)) {
                   5776:         # If uname and udom are for a course, check for blocks in the course.
                   5777:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5778:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5779:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5780:             return ($startblock,$endblock,$triggerblock);
                   5781:         }
                   5782:     } else {
1.490     raeburn  5783:         $udom = $env{'user.domain'};
                   5784:         $uname = $env{'user.name'};
                   5785:     }
                   5786: 
1.502     raeburn  5787:     my $startblock = 0;
                   5788:     my $endblock = 0;
1.1062    raeburn  5789:     my $triggerblock = '';
1.1373    raeburn  5790:     my %live_courses;
                   5791:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5792:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5793:     }
1.474     raeburn  5794: 
1.490     raeburn  5795:     # If uname is for a user, and activity is course-specific, i.e.,
                   5796:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5797: 
1.490     raeburn  5798:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5799:          $activity eq 'groups' || $activity eq 'printout' ||
1.1444    raeburn  5800:          $activity eq 'search' || $activity eq 'index' ||
                   5801:          $activity eq 'reinit' || $activity eq 'alert') &&
1.1189    raeburn  5802:         ($env{'request.course.id'})) {
1.490     raeburn  5803:         foreach my $key (keys(%live_courses)) {
                   5804:             if ($key ne $env{'request.course.id'}) {
                   5805:                 delete($live_courses{$key});
                   5806:             }
                   5807:         }
                   5808:     }
                   5809: 
                   5810:     my $otheruser = 0;
                   5811:     my %own_courses;
                   5812:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5813:         # Resource belongs to user other than current user.
                   5814:         $otheruser = 1;
                   5815:         # Gather courses for current user
                   5816:         %own_courses = 
                   5817:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5818:     }
                   5819: 
                   5820:     # Gather active course roles - course coordinator, instructor, 
                   5821:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5822: 
                   5823:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5824:         my ($cdom,$cnum);
                   5825:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5826:             $cdom = $env{'course.'.$course.'.domain'};
                   5827:             $cnum = $env{'course.'.$course.'.num'};
                   5828:         } else {
1.490     raeburn  5829:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5830:         }
                   5831:         my $no_ownblock = 0;
                   5832:         my $no_userblock = 0;
1.533     raeburn  5833:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5834:             # Check if current user has 'evb' priv for this
                   5835:             if (defined($own_courses{$course})) {
                   5836:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5837:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5838:                     if ($sec ne 'none') {
                   5839:                         $checkrole .= '/'.$sec;
                   5840:                     }
                   5841:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5842:                         $no_ownblock = 1;
                   5843:                         last;
                   5844:                     }
                   5845:                 }
                   5846:             }
                   5847:             # if they have 'evb' priv and are currently not playing student
                   5848:             next if (($no_ownblock) &&
                   5849:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5850:         }
1.474     raeburn  5851:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5852:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5853:             if ($sec ne 'none') {
1.482     raeburn  5854:                 $checkrole .= '/'.$sec;
1.474     raeburn  5855:             }
1.490     raeburn  5856:             if ($otheruser) {
                   5857:                 # Resource belongs to user other than current user.
                   5858:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5859:                 my (%allroles,%userroles);
                   5860:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5861:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5862:                         my ($trole,$tdom,$tnum,$tsec);
                   5863:                         if ($entry =~ /^cr/) {
                   5864:                             ($trole,$tdom,$tnum,$tsec) = 
                   5865:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5866:                         } else {
                   5867:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5868:                         }
                   5869:                         my ($spec,$area,$trest);
                   5870:                         $area = '/'.$tdom.'/'.$tnum;
                   5871:                         $trest = $tnum;
                   5872:                         if ($tsec ne '') {
                   5873:                             $area .= '/'.$tsec;
                   5874:                             $trest .= '/'.$tsec;
                   5875:                         }
                   5876:                         $spec = $trole.'.'.$area;
                   5877:                         if ($trole =~ /^cr/) {
                   5878:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5879:                                                               $tdom,$spec,$trest,$area);
                   5880:                         } else {
                   5881:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5882:                                                                 $tdom,$spec,$trest,$area);
                   5883:                         }
                   5884:                     }
1.1276    raeburn  5885:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5886:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5887:                         if ($1) {
                   5888:                             $no_userblock = 1;
                   5889:                             last;
                   5890:                         }
1.486     raeburn  5891:                     }
                   5892:                 }
1.490     raeburn  5893:             } else {
                   5894:                 # Resource belongs to current user
                   5895:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5896:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5897:                     $no_ownblock = 1;
                   5898:                     last;
                   5899:                 }
1.474     raeburn  5900:             }
                   5901:         }
                   5902:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5903:         next if (($no_ownblock) &&
1.491     albertel 5904:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5905:         next if ($no_userblock);
1.474     raeburn  5906: 
1.1303    raeburn  5907:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5908:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5909: 
1.1062    raeburn  5910:         my ($start,$end,$trigger) = 
1.1347    raeburn  5911:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5912:         if (($start != 0) && 
                   5913:             (($startblock == 0) || ($startblock > $start))) {
                   5914:             $startblock = $start;
1.1062    raeburn  5915:             if ($trigger ne '') {
                   5916:                 $triggerblock = $trigger;
                   5917:             }
1.502     raeburn  5918:         }
                   5919:         if (($end != 0)  &&
                   5920:             (($endblock == 0) || ($endblock < $end))) {
                   5921:             $endblock = $end;
1.1062    raeburn  5922:             if ($trigger ne '') {
                   5923:                 $triggerblock = $trigger;
                   5924:             }
1.502     raeburn  5925:         }
1.490     raeburn  5926:     }
1.1062    raeburn  5927:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5928: }
                   5929: 
                   5930: sub get_blocks {
1.1347    raeburn  5931:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5932:     my $startblock = 0;
                   5933:     my $endblock = 0;
1.1062    raeburn  5934:     my $triggerblock = '';
1.490     raeburn  5935:     my $course = $cdom.'_'.$cnum;
                   5936:     $setters->{$course} = {};
                   5937:     $setters->{$course}{'staff'} = [];
                   5938:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5939:     $setters->{$course}{'triggers'} = [];
                   5940:     my (@blockers,%triggered);
                   5941:     my $now = time;
                   5942:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5943:     if ($activity eq 'docs') {
1.1348    raeburn  5944:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5945:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5946:             $blocked = 1;
                   5947:             $nosymbcache = 1;
1.1348    raeburn  5948:             $noenccheck = 1;
1.1347    raeburn  5949:         }
1.1348    raeburn  5950:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5951:         foreach my $block (@blockers) {
                   5952:             if ($block =~ /^firstaccess____(.+)$/) {
                   5953:                 my $item = $1;
                   5954:                 my $type = 'map';
                   5955:                 my $timersymb = $item;
                   5956:                 if ($item eq 'course') {
                   5957:                     $type = 'course';
                   5958:                 } elsif ($item =~ /___\d+___/) {
                   5959:                     $type = 'resource';
                   5960:                 } else {
                   5961:                     $timersymb = &Apache::lonnet::symbread($item);
                   5962:                 }
                   5963:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5964:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5965:                 $triggered{$block} = {
                   5966:                                        start => $start,
                   5967:                                        end   => $end,
                   5968:                                        type  => $type,
                   5969:                                      };
                   5970:             }
                   5971:         }
                   5972:     } else {
                   5973:         foreach my $block (keys(%commblocks)) {
                   5974:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5975:                 my ($start,$end) = ($1,$2);
                   5976:                 if ($start <= time && $end >= time) {
                   5977:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5978:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5979:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5980:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5981:                                     push(@blockers,$block);
                   5982:                                 }
                   5983:                             }
                   5984:                         }
                   5985:                     }
                   5986:                 }
                   5987:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5988:                 my $item = $1;
                   5989:                 my $timersymb = $item; 
                   5990:                 my $type = 'map';
                   5991:                 if ($item eq 'course') {
                   5992:                     $type = 'course';
                   5993:                 } elsif ($item =~ /___\d+___/) {
                   5994:                     $type = 'resource';
                   5995:                 } else {
                   5996:                     $timersymb = &Apache::lonnet::symbread($item);
                   5997:                 }
                   5998:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5999:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   6000:                 if ($start && $end) {
                   6001:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  6002:                         if (ref($commblocks{$block}) eq 'HASH') {
                   6003:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6004:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   6005:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   6006:                                         push(@blockers,$block);
                   6007:                                         $triggered{$block} = {
                   6008:                                                                start => $start,
                   6009:                                                                end   => $end,
                   6010:                                                                type  => $type,
                   6011:                                                              };
                   6012:                                     }
                   6013:                                 }
                   6014:                             }
1.1062    raeburn  6015:                         }
                   6016:                     }
1.490     raeburn  6017:                 }
1.1062    raeburn  6018:             }
                   6019:         }
                   6020:     }
                   6021:     foreach my $blocker (@blockers) {
                   6022:         my ($staff_name,$staff_dom,$title,$blocks) =
                   6023:             &parse_block_record($commblocks{$blocker});
                   6024:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   6025:         my ($start,$end,$triggertype);
                   6026:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   6027:             ($start,$end) = ($1,$2);
                   6028:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   6029:             $start = $triggered{$blocker}{'start'};
                   6030:             $end = $triggered{$blocker}{'end'};
                   6031:             $triggertype = $triggered{$blocker}{'type'};
                   6032:         }
                   6033:         if ($start) {
                   6034:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   6035:             if ($triggertype) {
                   6036:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   6037:             } else {
                   6038:                 push(@{$$setters{$course}{'triggers'}},0);
                   6039:             }
                   6040:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   6041:                 $startblock = $start;
                   6042:                 if ($triggertype) {
                   6043:                     $triggerblock = $blocker;
1.474     raeburn  6044:                 }
                   6045:             }
1.1062    raeburn  6046:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   6047:                $endblock = $end;
                   6048:                if ($triggertype) {
                   6049:                    $triggerblock = $blocker;
                   6050:                }
                   6051:             }
1.474     raeburn  6052:         }
                   6053:     }
1.1062    raeburn  6054:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  6055: }
                   6056: 
                   6057: sub parse_block_record {
                   6058:     my ($record) = @_;
                   6059:     my ($setuname,$setudom,$title,$blocks);
                   6060:     if (ref($record) eq 'HASH') {
                   6061:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   6062:         $title = &unescape($record->{'event'});
                   6063:         $blocks = $record->{'blocks'};
                   6064:     } else {
                   6065:         my @data = split(/:/,$record,3);
                   6066:         if (scalar(@data) eq 2) {
                   6067:             $title = $data[1];
                   6068:             ($setuname,$setudom) = split(/@/,$data[0]);
                   6069:         } else {
                   6070:             ($setuname,$setudom,$title) = @data;
                   6071:         }
                   6072:         $blocks = { 'com' => 'on' };
                   6073:     }
                   6074:     return ($setuname,$setudom,$title,$blocks);
                   6075: }
                   6076: 
1.854     kalberla 6077: sub blocking_status {
1.1372    raeburn  6078:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  6079:     my %setters;
1.890     droeschl 6080: 
1.1061    raeburn  6081: # check for active blocking
1.1372    raeburn  6082:     if ($clientip eq '') {
                   6083:         $clientip = &Apache::lonnet::get_requestor_ip();
                   6084:     }
                   6085:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   6086:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  6087:     my $blocked = 0;
1.1372    raeburn  6088:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  6089:         $blocked = 1;
                   6090:     }
1.890     droeschl 6091: 
1.1061    raeburn  6092: # caller just wants to know whether a block is active
                   6093:     if (!wantarray) { return $blocked; }
                   6094: 
                   6095: # build a link to a popup window containing the details
                   6096:     my $querystring  = "?activity=$activity";
1.1351    raeburn  6097: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   6098:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  6099:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   6100:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  6101:     } elsif ($activity eq 'docs') {
1.1347    raeburn  6102:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   6103:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   6104:         if ($symb) {
                   6105:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   6106:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   6107:         }
1.1062    raeburn  6108:     }
1.1061    raeburn  6109: 
                   6110:     my $output .= <<'END_MYBLOCK';
                   6111: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   6112:     var options = "width=" + w + ",height=" + h + ",";
                   6113:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   6114:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   6115:     var newWin = window.open(url, wdwName, options);
                   6116:     newWin.focus();
                   6117: }
1.890     droeschl 6118: END_MYBLOCK
1.854     kalberla 6119: 
1.1061    raeburn  6120:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 6121:   
1.1061    raeburn  6122:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  6123:     my $text = &mt('Communication Blocked');
1.1217    raeburn  6124:     my $class = 'LC_comblock';
1.1062    raeburn  6125:     if ($activity eq 'docs') {
                   6126:         $text = &mt('Content Access Blocked');
1.1217    raeburn  6127:         $class = '';
1.1063    raeburn  6128:     } elsif ($activity eq 'printout') {
                   6129:         $text = &mt('Printing Blocked');
1.1232    raeburn  6130:     } elsif ($activity eq 'passwd') {
                   6131:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  6132:     } elsif ($activity eq 'grades') {
                   6133:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  6134:     } elsif ($activity eq 'search') {
                   6135:         $text = &mt('Search Blocked');
1.1444    raeburn  6136:     } elsif ($activity eq 'index') {
                   6137:         $text = &mt('Content Index Blocked');
1.1282    raeburn  6138:     } elsif ($activity eq 'alert') {
                   6139:         $text = &mt('Checking Critical Messages Blocked');
                   6140:     } elsif ($activity eq 'reinit') {
                   6141:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  6142:     } elsif ($activity eq 'about') {
                   6143:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  6144:     } elsif ($activity eq 'wishlist') {
                   6145:         $text = &mt('Access to Stored Links Blocked');
                   6146:     } elsif ($activity eq 'annotate') {
                   6147:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  6148:     }
1.1061    raeburn  6149:     $output .= <<"END_BLOCK";
1.1217    raeburn  6150: <div class='$class'>
1.869     kalberla 6151:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 6152:   title='$text'>
                   6153:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 6154:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 6155:   title='$text'>$text</a>
1.867     kalberla 6156: </div>
                   6157: 
                   6158: END_BLOCK
1.474     raeburn  6159: 
1.1061    raeburn  6160:     return ($blocked, $output);
1.854     kalberla 6161: }
1.490     raeburn  6162: 
1.60      matthew  6163: ###############################################
                   6164: 
1.682     raeburn  6165: sub check_ip_acc {
1.1201    raeburn  6166:     my ($acc,$clientip)=@_;
1.682     raeburn  6167:     &Apache::lonxml::debug("acc is $acc");
                   6168:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   6169:         return 1;
                   6170:     }
1.1339    raeburn  6171:     my ($ip,$allowed);
                   6172:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   6173:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   6174:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   6175:     } else {
1.1350    raeburn  6176:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   6177:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  6178:     }
1.682     raeburn  6179: 
                   6180:     my $name;
1.1219    raeburn  6181:     my %access = (
                   6182:                      allowfrom => 1,
                   6183:                      denyfrom  => 0,
                   6184:                  );
                   6185:     my @allows;
                   6186:     my @denies;
                   6187:     foreach my $item (split(',',$acc)) {
                   6188:         $item =~ s/^\s*//;
                   6189:         $item =~ s/\s*$//;
                   6190:         my $pattern;
                   6191:         if ($item =~ /^\!(.+)$/) {
                   6192:             push(@denies,$1);
                   6193:         } else {
                   6194:             push(@allows,$item);
                   6195:         }
                   6196:    }
                   6197:    my $numdenies = scalar(@denies);
                   6198:    my $numallows = scalar(@allows);
                   6199:    my $count = 0;
                   6200:    foreach my $pattern (@denies,@allows) {
                   6201:         $count ++; 
                   6202:         my $acctype = 'allowfrom';
                   6203:         if ($count <= $numdenies) {
                   6204:             $acctype = 'denyfrom';
                   6205:         }
1.682     raeburn  6206:         if ($pattern =~ /\*$/) {
                   6207:             #35.8.*
                   6208:             $pattern=~s/\*//;
1.1219    raeburn  6209:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6210:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   6211:             #35.8.3.[34-56]
                   6212:             my $low=$2;
                   6213:             my $high=$3;
                   6214:             $pattern=$1;
                   6215:             if ($ip =~ /^\Q$pattern\E/) {
                   6216:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  6217:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  6218:             }
                   6219:         } elsif ($pattern =~ /^\*/) {
                   6220:             #*.msu.edu
                   6221:             $pattern=~s/\*//;
                   6222:             if (!defined($name)) {
                   6223:                 use Socket;
                   6224:                 my $netaddr=inet_aton($ip);
                   6225:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6226:             }
1.1219    raeburn  6227:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  6228:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   6229:             #127.0.0.1
1.1219    raeburn  6230:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6231:         } else {
                   6232:             #some.name.com
                   6233:             if (!defined($name)) {
                   6234:                 use Socket;
                   6235:                 my $netaddr=inet_aton($ip);
                   6236:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6237:             }
1.1219    raeburn  6238:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   6239:         }
                   6240:         if ($allowed =~ /^(0|1)$/) { last; }
                   6241:     }
                   6242:     if ($allowed eq '') {
                   6243:         if ($numdenies && !$numallows) {
                   6244:             $allowed = 1;
                   6245:         } else {
                   6246:             $allowed = 0;
1.682     raeburn  6247:         }
                   6248:     }
                   6249:     return $allowed;
                   6250: }
                   6251: 
                   6252: ###############################################
                   6253: 
1.60      matthew  6254: =pod
                   6255: 
1.112     bowersj2 6256: =head1 Domain Template Functions
                   6257: 
                   6258: =over 4
                   6259: 
                   6260: =item * &determinedomain()
1.60      matthew  6261: 
                   6262: Inputs: $domain (usually will be undef)
                   6263: 
1.63      www      6264: Returns: Determines which domain should be used for designs
1.60      matthew  6265: 
                   6266: =cut
1.54      www      6267: 
1.60      matthew  6268: ###############################################
1.63      www      6269: sub determinedomain {
                   6270:     my $domain=shift;
1.531     albertel 6271:     if (! $domain) {
1.60      matthew  6272:         # Determine domain if we have not been given one
1.893     raeburn  6273:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 6274:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   6275:         if ($env{'request.role.domain'}) { 
                   6276:             $domain=$env{'request.role.domain'}; 
1.60      matthew  6277:         }
                   6278:     }
1.63      www      6279:     return $domain;
                   6280: }
                   6281: ###############################################
1.517     raeburn  6282: 
1.518     albertel 6283: sub devalidate_domconfig_cache {
                   6284:     my ($udom)=@_;
                   6285:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   6286: }
                   6287: 
                   6288: # ---------------------- Get domain configuration for a domain
                   6289: sub get_domainconf {
                   6290:     my ($udom) = @_;
                   6291:     my $cachetime=1800;
                   6292:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   6293:     if (defined($cached)) { return %{$result}; }
                   6294: 
                   6295:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  6296: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  6297:     my (%designhash,%legacy);
1.518     albertel 6298:     if (keys(%domconfig) > 0) {
                   6299:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  6300:             if (keys(%{$domconfig{'login'}})) {
                   6301:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  6302:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  6303:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   6304:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6305:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   6306:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   6307:                                         if ($key eq 'loginvia') {
                   6308:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   6309:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   6310:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   6311:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   6312: 
                   6313:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   6314:                                                 } else {
                   6315:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   6316:                                                 }
1.948     raeburn  6317:                                             }
1.1208    raeburn  6318:                                         } elsif ($key eq 'headtag') {
                   6319:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   6320:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  6321:                                             }
1.946     raeburn  6322:                                         }
1.1208    raeburn  6323:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   6324:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   6325:                                         }
1.946     raeburn  6326:                                     }
                   6327:                                 }
                   6328:                             }
1.1366    raeburn  6329:                         } elsif ($key eq 'saml') {
                   6330:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6331:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6332:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6333:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6334:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6335:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6336:                                         }
                   6337:                                     }
                   6338:                                 }
                   6339:                             }
1.946     raeburn  6340:                         } else {
                   6341:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6342:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6343:                                     $domconfig{'login'}{$key}{$img};
                   6344:                             }
1.699     raeburn  6345:                         }
                   6346:                     } else {
                   6347:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6348:                     }
1.632     raeburn  6349:                 }
                   6350:             } else {
                   6351:                 $legacy{'login'} = 1;
1.518     albertel 6352:             }
1.632     raeburn  6353:         } else {
                   6354:             $legacy{'login'} = 1;
1.518     albertel 6355:         }
                   6356:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6357:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6358:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6359:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6360:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6361:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6362:                         }
1.518     albertel 6363:                     }
                   6364:                 }
1.632     raeburn  6365:             } else {
                   6366:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6367:             }
1.632     raeburn  6368:         } else {
                   6369:             $legacy{'rolecolors'} = 1;
1.518     albertel 6370:         }
1.948     raeburn  6371:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6372:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6373:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6374:             }
                   6375:         }
1.632     raeburn  6376:         if (keys(%legacy) > 0) {
                   6377:             my %legacyhash = &get_legacy_domconf($udom);
                   6378:             foreach my $item (keys(%legacyhash)) {
                   6379:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6380:                     if ($legacy{'login'}) { 
                   6381:                         $designhash{$item} = $legacyhash{$item};
                   6382:                     }
                   6383:                 } else {
                   6384:                     if ($legacy{'rolecolors'}) {
                   6385:                         $designhash{$item} = $legacyhash{$item};
                   6386:                     }
1.518     albertel 6387:                 }
                   6388:             }
                   6389:         }
1.632     raeburn  6390:     } else {
                   6391:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6392:     }
                   6393:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6394: 				  $cachetime);
                   6395:     return %designhash;
                   6396: }
                   6397: 
1.632     raeburn  6398: sub get_legacy_domconf {
                   6399:     my ($udom) = @_;
                   6400:     my %legacyhash;
                   6401:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6402:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6403:     if (-e $designfile) {
1.1317    raeburn  6404:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6405:             while (my $line = <$fh>) {
                   6406:                 next if ($line =~ /^\#/);
                   6407:                 chomp($line);
                   6408:                 my ($key,$val)=(split(/\=/,$line));
                   6409:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6410:             }
                   6411:             close($fh);
                   6412:         }
                   6413:     }
1.1026    raeburn  6414:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6415:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6416:     }
                   6417:     return %legacyhash;
                   6418: }
                   6419: 
1.63      www      6420: =pod
                   6421: 
1.112     bowersj2 6422: =item * &domainlogo()
1.63      www      6423: 
                   6424: Inputs: $domain (usually will be undef)
                   6425: 
                   6426: Returns: A link to a domain logo, if the domain logo exists.
                   6427: If the domain logo does not exist, a description of the domain.
                   6428: 
                   6429: =cut
1.112     bowersj2 6430: 
1.63      www      6431: ###############################################
                   6432: sub domainlogo {
1.517     raeburn  6433:     my $domain = &determinedomain(shift);
1.518     albertel 6434:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6435:     # See if there is a logo
                   6436:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6437:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6438:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6439: 	    if ($imgsrc =~ m{^/res/}) {
                   6440: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6441: 		&Apache::lonnet::repcopy($local_name);
                   6442: 	    }
                   6443: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6444:         }
                   6445:         my $alttext = $domain;
                   6446:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6447:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6448:         }
                   6449:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6450:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6451:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6452:     } else {
1.60      matthew  6453:         return '';
1.59      www      6454:     }
                   6455: }
1.63      www      6456: ##############################################
                   6457: 
                   6458: =pod
                   6459: 
1.112     bowersj2 6460: =item * &designparm()
1.63      www      6461: 
                   6462: Inputs: $which parameter; $domain (usually will be undef)
                   6463: 
                   6464: Returns: value of designparamter $which
                   6465: 
                   6466: =cut
1.112     bowersj2 6467: 
1.397     albertel 6468: 
1.400     albertel 6469: ##############################################
1.397     albertel 6470: sub designparm {
                   6471:     my ($which,$domain)=@_;
                   6472:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6473:         return $env{'environment.color.'.$which};
1.96      www      6474:     }
1.63      www      6475:     $domain=&determinedomain($domain);
1.1016    raeburn  6476:     my %domdesign;
                   6477:     unless ($domain eq 'public') {
                   6478:         %domdesign = &get_domainconf($domain);
                   6479:     }
1.520     raeburn  6480:     my $output;
1.517     raeburn  6481:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6482:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6483:     } else {
1.520     raeburn  6484:         $output = $defaultdesign{$which};
                   6485:     }
                   6486:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6487:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6488:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6489:             if ($output =~ m{^/res/}) {
                   6490:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6491:                 &Apache::lonnet::repcopy($local_name);
                   6492:             }
1.520     raeburn  6493:             $output = &lonhttpdurl($output);
                   6494:         }
1.63      www      6495:     }
1.520     raeburn  6496:     return $output;
1.63      www      6497: }
1.59      www      6498: 
1.822     bisitz   6499: ##############################################
                   6500: =pod
                   6501: 
1.832     bisitz   6502: =item * &authorspace()
                   6503: 
1.1028    raeburn  6504: Inputs: $url (usually will be undef).
1.832     bisitz   6505: 
1.1132    raeburn  6506: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6507:          directory being viewed (or for which action is being taken). 
                   6508:          If $url is provided, and begins /priv/<domain>/<uname>
                   6509:          the path will be that portion of the $context argument.
                   6510:          Otherwise the path will be for the author space of the current
                   6511:          user when the current role is author, or for that of the 
                   6512:          co-author/assistant co-author space when the current role 
                   6513:          is co-author or assistant co-author.
1.832     bisitz   6514: 
                   6515: =cut
                   6516: 
                   6517: sub authorspace {
1.1028    raeburn  6518:     my ($url) = @_;
                   6519:     if ($url ne '') {
                   6520:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6521:            return $1;
                   6522:         }
                   6523:     }
1.832     bisitz   6524:     my $caname = '';
1.1024    www      6525:     my $cadom = '';
1.1028    raeburn  6526:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6527:         ($cadom,$caname) =
1.832     bisitz   6528:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6529:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6530:         $caname = $env{'user.name'};
1.1024    www      6531:         $cadom = $env{'user.domain'};
1.832     bisitz   6532:     }
1.1028    raeburn  6533:     if (($caname ne '') && ($cadom ne '')) {
                   6534:         return "/priv/$cadom/$caname/";
                   6535:     }
                   6536:     return;
1.832     bisitz   6537: }
                   6538: 
                   6539: ##############################################
                   6540: =pod
                   6541: 
1.822     bisitz   6542: =item * &head_subbox()
                   6543: 
                   6544: Inputs: $content (contains HTML code with page functions, etc.)
                   6545: 
                   6546: Returns: HTML div with $content
                   6547:          To be included in page header
                   6548: 
                   6549: =cut
                   6550: 
                   6551: sub head_subbox {
                   6552:     my ($content)=@_;
                   6553:     my $output =
1.993     raeburn  6554:         '<div class="LC_head_subbox">'
1.822     bisitz   6555:        .$content
                   6556:        .'</div>'
                   6557: }
                   6558: 
                   6559: ##############################################
                   6560: =pod
                   6561: 
                   6562: =item * &CSTR_pageheader()
                   6563: 
1.1026    raeburn  6564: Input: (optional) filename from which breadcrumb trail is built.
                   6565:        In most cases no input as needed, as $env{'request.filename'}
                   6566:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6567:        frameset flag
                   6568:        If page header is being requested for use in a frameset, then
                   6569:        the second (option) argument -- frameset will be true, and
                   6570:        the target attribute set for links should be target="_parent".
1.1433    raeburn  6571:        If $title is supplied as the third arg, that will be used to 
1.1407    raeburn  6572:        the left of the breadcrumbs tail for the current path.
1.822     bisitz   6573: 
                   6574: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6575:          To be included on Authoring Space pages
1.822     bisitz   6576: 
                   6577: =cut
                   6578: 
                   6579: sub CSTR_pageheader {
1.1407    raeburn  6580:     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  6581:     if ($trailfile eq '') {
                   6582:         $trailfile = $env{'request.filename'};
                   6583:     }
                   6584: 
                   6585: # this is for resources; directories have customtitle, and crumbs
                   6586: # and select recent are created in lonpubdir.pm
                   6587: 
                   6588:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6589:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6590:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6591:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6592:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6593: 
                   6594:     my $parentpath = '';
                   6595:     my $lastitem = '';
                   6596:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6597:         $parentpath = $1;
                   6598:         $lastitem = $2;
                   6599:     } else {
                   6600:         $lastitem = $thisdisfn;
                   6601:     }
1.921     bisitz   6602: 
1.1406    raeburn  6603:     my $crsauthor;
1.1246    raeburn  6604:     if (($env{'request.course.id'}) &&
                   6605:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6606:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6607:         $crsauthor = 1;
1.1406    raeburn  6608:         if ($title eq '') {
                   6609:             $title = &mt('Course Authoring Space');
                   6610:         }
                   6611:     } elsif ($title eq '') {
1.1246    raeburn  6612:         $title = &mt('Authoring Space');
                   6613:     }
                   6614: 
1.1379    raeburn  6615:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6616:     if ($frameset) {
                   6617:         $target = ' target="_parent"';
                   6618:         $crumbtarget = '_parent';
                   6619:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6620:         $target = '';
                   6621:         $crumbtarget = '';
1.1379    raeburn  6622:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6623:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6624:         $crumbtarget = $env{'request.deeplink.target'};
                   6625:     }
1.1313    raeburn  6626: 
1.921     bisitz   6627:     my $output =
1.1407    raeburn  6628:          '<div>'
1.822     bisitz   6629:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6630:         .'<b>'.$title.'</b> '
1.1314    raeburn  6631:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6632:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6633: 
                   6634:     if ($lastitem) {
                   6635:         $output .=
                   6636:              '<span class="LC_filename">'
                   6637:             .$lastitem
                   6638:             .'</span>';
                   6639:     }
1.1245    raeburn  6640: 
1.1246    raeburn  6641:     if ($crsauthor) {
1.1379    raeburn  6642:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6643:     } else {
                   6644:         $output .=
                   6645:              '<br />'
1.1314    raeburn  6646:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6647:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6648:             .'</form>'
1.1379    raeburn  6649:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6650:     }
1.1407    raeburn  6651:     $output .= '</div>';
1.921     bisitz   6652: 
                   6653:     return $output;
1.822     bisitz   6654: }
                   6655: 
1.1419    raeburn  6656: ##############################################
                   6657: =pod
                   6658: 
                   6659: =item * &nocodemirror()
                   6660: 
                   6661: Input: None
                   6662: 
                   6663: Returns: 1 if CodeMirror is deactivated based on
                   6664:          user's preference, or domain default,
                   6665:          if user indicated use of default.
                   6666: 
                   6667: =cut
                   6668: 
1.1416    raeburn  6669: sub nocodemirror {
                   6670:     my $nocodem = $env{'environment.nocodemirror'};
                   6671:     unless ($nocodem) {
                   6672:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   6673:         if ($domdefs{'nocodemirror'}) {
                   6674:             $nocodem = 'yes';
                   6675:         }
                   6676:     }
1.1417    raeburn  6677:     if ($nocodem eq 'yes') {
                   6678:         return 1;
                   6679:     }
                   6680:     return;
1.1416    raeburn  6681: }
                   6682: 
1.1419    raeburn  6683: ##############################################
                   6684: =pod
                   6685: 
                   6686: =item * &permitted_editors()
                   6687: 
1.1422    raeburn  6688: Input: $uri (optional)
1.1419    raeburn  6689: 
                   6690: Returns: %editors hash in which keys are editors
1.1429    raeburn  6691:          permitted in current Authoring Space,
                   6692:          or in current course for web pages
                   6693:          created in a course.
                   6694: 
1.1419    raeburn  6695:          Value for each key is 1. Possible keys
1.1429    raeburn  6696:          are: edit, xml, and daxe.
                   6697: 
                   6698:          For a regular Authoring Space, if no specific
1.1419    raeburn  6699:          set of editors has been set for the Author
                   6700:          who owns the Authoring Space, then the
                   6701:          domain default will be used.  If no domain
                   6702:          default has been set, then the keys will be
                   6703:          edit and xml.
                   6704: 
1.1429    raeburn  6705:          For a course author, or for web pages created
                   6706:          in a course, if no specific set of editors has
                   6707:          been set for the course, then the domain
                   6708:          course default will be used. If no domain
                   6709:          course default has been set, then the keys
                   6710:          will be edit and xml.
                   6711: 
1.1419    raeburn  6712: =cut
                   6713: 
1.1418    raeburn  6714: sub permitted_editors {
1.1422    raeburn  6715:     my ($uri) = @_;
1.1429    raeburn  6716:     my ($is_author,$is_coauthor,$is_course,$auname,$audom,%editors);
1.1418    raeburn  6717:     if ($env{'request.role'} =~ m{^au\./}) {
                   6718:         $is_author = 1;
                   6719:     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
                   6720:         ($audom,$auname) = ($1,$2);
                   6721:         if (($audom ne '') && ($auname ne '')) {
                   6722:             if (($env{'user.domain'} eq $audom) &&
                   6723:                 ($env{'user.name'} eq $auname)) {
                   6724:                 $is_author = 1;
                   6725:             } else {
                   6726:                 $is_coauthor = 1;
                   6727:             }
                   6728:         }
                   6729:     } elsif ($env{'request.course.id'}) {
1.1429    raeburn  6730:         my ($cdom,$cnum);
                   6731:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6732:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6733:         if (($env{'request.editurl'} =~ m{^/priv/\Q$cdom/$cnum\E/}) ||
1.1430    raeburn  6734:             ($env{'request.editurl'} =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}) ||
                   6735:             ($uri =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/})) {
1.1429    raeburn  6736:             $is_course = 1;
                   6737:         } elsif ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
1.1418    raeburn  6738:             ($audom,$auname) = ($1,$2);
                   6739:         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6740:             ($audom,$auname) = ($1,$2);
1.1422    raeburn  6741:         } elsif (($uri eq '/daxesave') &&
1.1429    raeburn  6742:                  (($env{'form.path'} =~ m{^/daxeopen/priv/\Q$cdom/$cnum\E/}) ||
                   6743:                   ($env{'form.path'} =~ m{^/daxeopen/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}))) {
                   6744:             $is_course = 1;
                   6745:         } elsif (($uri eq '/daxesave') &&
1.1422    raeburn  6746:                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
                   6747:             ($audom,$auname) = ($1,$2);
1.1418    raeburn  6748:         }
1.1429    raeburn  6749:         unless ($is_course) {
                   6750:             if (($audom ne '') && ($auname ne '')) {
                   6751:                 if (($env{'user.domain'} eq $audom) &&
                   6752:                     ($env{'user.name'} eq $auname)) {
                   6753:                     $is_author = 1;
                   6754:                 } else {
                   6755:                     $is_coauthor = 1;
                   6756:                 }
1.1418    raeburn  6757:             }
                   6758:         }
                   6759:     }
                   6760:     if ($is_author) {
                   6761:         if (exists($env{'environment.editors'})) {
                   6762:             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
                   6763:         } else {
                   6764:             %editors = ( edit => 1,
                   6765:                          xml => 1,
                   6766:                        );
                   6767:         }
                   6768:     } elsif ($is_coauthor) {
                   6769:         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
                   6770:             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
                   6771:         } else {
                   6772:             %editors = ( edit => 1,
                   6773:                          xml => 1,
                   6774:                        );
                   6775:         }
1.1429    raeburn  6776:     } elsif ($is_course) {
                   6777:         if (exists($env{'course.'.$env{'request.course.id'}.'.internal.crseditors'})) {
                   6778:             map { $editors{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.crseditors'});
                   6779:         } else {
                   6780:             my %domdefaults = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
                   6781:             if (exists($domdefaults{'crseditors'})) {
                   6782:                 map { $editors{$_} = 1; } split(/,/,$domdefaults{'crseditors'});
                   6783:             } else {
                   6784:                 %editors = ( edit => 1,
                   6785:                              xml => 1,
                   6786:                            );
                   6787:             }
                   6788:         }
1.1418    raeburn  6789:     } else {
                   6790:         %editors = ( edit => 1,
                   6791:                      xml => 1,
                   6792:                    );
                   6793:     }
                   6794:     return %editors;
                   6795: }
                   6796: 
1.60      matthew  6797: ###############################################
                   6798: ###############################################
                   6799: 
                   6800: =pod
                   6801: 
1.112     bowersj2 6802: =back
                   6803: 
1.549     albertel 6804: =head1 HTML Helpers
1.112     bowersj2 6805: 
                   6806: =over 4
                   6807: 
                   6808: =item * &bodytag()
1.60      matthew  6809: 
                   6810: Returns a uniform header for LON-CAPA web pages.
                   6811: 
                   6812: Inputs: 
                   6813: 
1.112     bowersj2 6814: =over 4
                   6815: 
                   6816: =item * $title, A title to be displayed on the page.
                   6817: 
                   6818: =item * $function, the current role (can be undef).
                   6819: 
                   6820: =item * $addentries, extra parameters for the <body> tag.
                   6821: 
                   6822: =item * $bodyonly, if defined, only return the <body> tag.
                   6823: 
                   6824: =item * $domain, if defined, force a given domain.
                   6825: 
                   6826: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6827:             text interface only)
1.60      matthew  6828: 
1.814     bisitz   6829: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6830:                      navigational links
1.317     albertel 6831: 
1.338     albertel 6832: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6833: 
1.460     albertel 6834: =item * $args, optional argument valid values are
                   6835:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6836:             use_absolute     -> for external resource or syllabus, this will
                   6837:                                 contain https://<hostname> if server uses
                   6838:                                 https (as per hosts.tab), but request is for http
                   6839:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6840: 
1.1096    raeburn  6841: =item * $advtoolsref, optional argument, ref to an array containing
                   6842:             inlineremote items to be added in "Functions" menu below
                   6843:             breadcrumbs.
                   6844: 
1.1316    raeburn  6845: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6846:             course, if LON-CAPA is in LTI Provider context. Value is
                   6847:             the scope of use, i.e., launch was for access to a single, a map
                   6848:             or the entire course.
                   6849: 
                   6850: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6851:             context, this will contain the URL for the landing item in
                   6852:             the course, after launch from an LTI Consumer
                   6853: 
1.1318    raeburn  6854: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6855:             context, this will contain a reference to hash of items
                   6856:             to be included in the page header and/or inline menu.
                   6857: 
1.1385    raeburn  6858: =item * $menucoll, optional argument, if specific menu collection is in
                   6859:             effect, either set as the default for the course, or set for
                   6860:             the deeplink paramater for $env{'request.deeplink.login'}
                   6861:             then $menucoll will be the number of that collection. 
                   6862: 
                   6863: =item * $menuref, optional argument, reference to a hash, containing the
                   6864:             menu options included for the menu in effect, based on the
                   6865:             configuration for the numbered menu collection in use.  
                   6866: 
                   6867: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6868:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6869:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6870:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6871:             being called a second time.
                   6872: 
1.112     bowersj2 6873: =back
                   6874: 
1.60      matthew  6875: Returns: A uniform header for LON-CAPA web pages.  
                   6876: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6877: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6878: other decorations will be returned.
                   6879: 
                   6880: =cut
                   6881: 
1.54      www      6882: sub bodytag {
1.831     bisitz   6883:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6884:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6885:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6886: 
1.954     raeburn  6887:     my $public;
                   6888:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6889:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6890:         $public = 1;
                   6891:     }
1.460     albertel 6892:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6893:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6894:     my $hostname = $args->{'hostname'};
1.339     albertel 6895: 
1.183     matthew  6896:     $function = &get_users_function() if (!$function);
1.339     albertel 6897:     my $font =   &designparm($function.'.font',$domain);
                   6898:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6899: 
1.803     bisitz   6900:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6901: 		   'bgcolor' => $pgbg,
1.339     albertel 6902: 		   'text'    => $font,
                   6903:                    'alink'   => &designparm($function.'.alink',$domain),
                   6904: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6905: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6906:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6907: 
1.63      www      6908:  # role and realm
1.1178    raeburn  6909:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6910:     if ($realm) {
                   6911:         $realm = '/'.$realm;
                   6912:     }
1.1357    raeburn  6913:     if ($role eq 'ca') {
1.479     albertel 6914:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6915:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6916:     } 
1.55      www      6917: # realm
1.1357    raeburn  6918:     my ($cid,$sec);
1.258     albertel 6919:     if ($env{'request.course.id'}) {
1.1357    raeburn  6920:         $cid = $env{'request.course.id'};
                   6921:         if ($env{'request.course.sec'}) {
                   6922:             $sec = $env{'request.course.sec'};
                   6923:         }
                   6924:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6925:         if (&Apache::lonnet::is_course($1,$2)) {
                   6926:             $cid = $1.'_'.$2;
                   6927:             $sec = $3;
                   6928:         }
                   6929:     }
                   6930:     if ($cid) {
1.378     raeburn  6931:         if ($env{'request.role'} !~ /^cr/) {
                   6932:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6933:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6934:             if ($env{'request.role.desc'}) {
                   6935:                 $role = $env{'request.role.desc'};
                   6936:             } else {
                   6937:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6938:             }
1.1257    raeburn  6939:         } else {
                   6940:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6941:         }
1.1357    raeburn  6942:         if ($sec) {
                   6943:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6944:         }   
1.1357    raeburn  6945: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6946:     } else {
                   6947:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6948:     }
1.433     albertel 6949: 
1.438     albertel 6950:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6951: 
1.101     www      6952: # construct main body tag
1.359     albertel 6953:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6954: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6955: 
1.1131    raeburn  6956:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6957: 
1.1130    raeburn  6958:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6959:         return $bodytag;
1.1130    raeburn  6960:     }
1.359     albertel 6961: 
1.954     raeburn  6962:     if ($public) {
1.433     albertel 6963: 	undef($role);
                   6964:     }
1.1318    raeburn  6965: 
1.1359    raeburn  6966:     my $showcrstitle = 1;
1.1357    raeburn  6967:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6968:         if (ref($ltimenu) eq 'HASH') {
                   6969:             unless ($ltimenu->{'role'}) {
                   6970:                 undef($role);
                   6971:             }
                   6972:             unless ($ltimenu->{'coursetitle'}) {
1.1359    raeburn  6973:                 $showcrstitle = 0;
                   6974:             }
                   6975:         }
                   6976:     } elsif (($cid) && ($menucoll)) {
                   6977:         if (ref($menuref) eq 'HASH') {
                   6978:             unless ($menuref->{'role'}) {
                   6979:                 undef($role);
                   6980:             }
                   6981:             unless ($menuref->{'crs'}) {
                   6982:                 $showcrstitle = 0;
1.1318    raeburn  6983:             }
                   6984:         }
                   6985:     }
                   6986: 
1.762     bisitz   6987:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6988:     #
                   6989:     # Extra info if you are the DC
                   6990:     my $dc_info = '';
1.1359    raeburn  6991:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6992:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6993:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6994:         $dc_info =~ s/\s+$//;
1.359     albertel 6995:     }
                   6996: 
1.1237    raeburn  6997:     my $crstype;
1.1357    raeburn  6998:     if ($cid) {
                   6999:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  7000:     } elsif ($args->{'crstype'}) {
                   7001:         $crstype = $args->{'crstype'};
                   7002:     }
                   7003:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   7004:         undef($role);
                   7005:     } else {
1.1242    raeburn  7006:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  7007:     }
1.853     droeschl 7008: 
1.903     droeschl 7009:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   7010: 
                   7011:         #    if ($env{'request.state'} eq 'construct') {
                   7012:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   7013:         #    }
                   7014: 
1.1440    raeburn  7015:         my $need_endlcint;
                   7016:         unless ($args->{'switchserver'}) {
                   7017:             $bodytag .= Apache::lonhtmlcommon::scripttag(
                   7018:                 Apache::lonmenu::utilityfunctions($httphost), 'start');
                   7019:             $need_endlcint = 1;
                   7020:         }
1.359     albertel 7021: 
1.1427    raeburn  7022:         my $collapsible;
1.1423    raeburn  7023:         if ($args->{'collapsible_header'} ne '') {
1.1427    raeburn  7024:             $collapsible = 1;
                   7025:             my ($menustate,$tiptext,$divclass);
                   7026:             if ($args->{'start_collapsed'}) {
                   7027:                 $menustate = 'collapsed';
                   7028:                 $tiptext = 'display';
                   7029:                 $divclass = 'hidden';
                   7030:             } else {
                   7031:                 $menustate = 'expanded';
                   7032:                 $tiptext = 'hide';
                   7033:                 $divclass = 'shown';
                   7034:             }
                   7035:             my $alttext = &mt('menu state: '.$menustate);
                   7036:             my $tooltip = &mt($tiptext.' standard menus');
1.1421    raeburn  7037:             $bodytag .= <<"END";
                   7038: <div id="LC_expandingContainer" style="display:inline;">
                   7039: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
1.1427    raeburn  7040: <a href="#" style="text-decoration:none;"><img class="LC_collapsible_indicator" alt="$alttext" title="$tooltip" src="/res/adm/pages/$menustate.png" style="border:0;margin:0;padding:0;max-width:100%;height:auto" /></a></div>
                   7041: <div class="LC_menus_content $divclass">
1.1421    raeburn  7042: END
                   7043:         }
1.1318    raeburn  7044:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  7045:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  7046:                                                               $args->{'links_disabled'},
1.1421    raeburn  7047:                                                               $args->{'links_target'},
1.1427    raeburn  7048:                                                               $collapsible);
1.1454    raeburn  7049:             my $labeltext = &HTML::Entities::encode(&mt('Primary links'));
1.1318    raeburn  7050:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   7051:                 if ($dc_info) {
                   7052:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   7053:                 }
1.1456    raeburn  7054:                 $bodytag .= qq|<div id="LC_nav_bar" role="navigation" aria-label="$labeltext">$left $role</div>|;
1.1454    raeburn  7055:                 unless (($realm eq '') && ($dc_info eq '')) {
                   7056:                     $bodytag .= qq|<div id="LC_realm" role="complementary"><em>$realm</em> $dc_info</div>|;
                   7057:                 }
1.1440    raeburn  7058:                 if ($need_endlcint) {
                   7059:                     $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7060:                 }
1.1318    raeburn  7061:                 return $bodytag;
                   7062:             }
1.894     droeschl 7063: 
1.1457  ! raeburn  7064:             $bodytag .= '<div class="LC_landmark" style="margin: 3px 0 0 0;" role="navigation" aria-label="'.$labeltext.'">';
1.1318    raeburn  7065:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   7066:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   7067:             }
1.916     droeschl 7068: 
1.1454    raeburn  7069:             $bodytag .= $right.'</div>';
1.852     droeschl 7070: 
1.1318    raeburn  7071:             if ($dc_info) {
                   7072:                 $dc_info = &dc_courseid_toggle($dc_info);
                   7073:             }
1.1454    raeburn  7074:             unless (($realm eq '') && ($dc_info eq '')) {
1.1457  ! raeburn  7075:                 $bodytag .= qq|<div id="LC_realm" role="complementary">$realm $dc_info</div>|;
1.1454    raeburn  7076:             }
1.1457  ! raeburn  7077:             $bodytag .= qq|<div style="clear: both; margin: 5px 0 0 0;"></div>|;
1.917     raeburn  7078:         }
1.916     droeschl 7079: 
1.1169    raeburn  7080:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  7081:         if ($args->{'no_secondary_menu'}) {
1.1440    raeburn  7082:             if ($need_endlcint) {
                   7083:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7084:             }
1.1168    raeburn  7085:             return $bodytag;
                   7086:         }
1.1169    raeburn  7087:         #don't show menus for public users
1.954     raeburn  7088:         if (!$public){
1.1318    raeburn  7089:             unless ($args->{'no_inline_menu'}) {
                   7090:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  7091:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  7092:                                                             $menucoll,$menuref,
1.1380    raeburn  7093:                                                             $args->{'links_disabled'},
                   7094:                                                             $args->{'links_target'});
1.1318    raeburn  7095:             }
1.903     droeschl 7096:             $bodytag .= Apache::lonmenu::serverform();
1.1440    raeburn  7097:             if ($need_endlcint) {
                   7098:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7099:             }
1.920     raeburn  7100:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 7101:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  7102:                                 $args->{'bread_crumbs'},'','',$hostname,
                   7103:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7104:             } elsif ($forcereg) {
                   7105:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  7106:                                 $args->{'group'},$args->{'hide_buttons'},
                   7107:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7108:             } else {
                   7109:                 $bodytag .= 
                   7110:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   7111:                                                         $forcereg,$args->{'group'},
                   7112:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  7113:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  7114:             }
1.1440    raeburn  7115:         } else {
                   7116:             # this is to separate menu from content when there's no secondary
1.1441    raeburn  7117:             # menu. Especially needed for publicly accessible resources.
1.903     droeschl 7118:             $bodytag .= '<hr style="clear:both" />';
1.1440    raeburn  7119:             if ($need_endlcint) {
                   7120:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7121:             }
1.235     raeburn  7122:         }
1.1423    raeburn  7123:         if ($args->{'collapsible_header'} ne '') {
                   7124:             $bodytag .= $args->{'collapsible_header'}.
                   7125:                         '<div id="LC_collapsible_separator"></div>'.
1.1421    raeburn  7126:                         '</div></div>';
                   7127:         }
1.235     raeburn  7128:         return $bodytag;
1.182     matthew  7129: }
                   7130: 
1.917     raeburn  7131: sub dc_courseid_toggle {
                   7132:     my ($dc_info) = @_;
1.980     raeburn  7133:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  7134:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  7135:            &mt('(More ...)').'</a></span>'.
                   7136:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   7137: }
                   7138: 
1.330     albertel 7139: sub make_attr_string {
                   7140:     my ($register,$attr_ref) = @_;
                   7141: 
                   7142:     if ($attr_ref && !ref($attr_ref)) {
                   7143: 	die("addentries Must be a hash ref ".
                   7144: 	    join(':',caller(1))." ".
                   7145: 	    join(':',caller(0))." ");
                   7146:     }
                   7147: 
                   7148:     if ($register) {
1.339     albertel 7149: 	my ($on_load,$on_unload);
                   7150: 	foreach my $key (keys(%{$attr_ref})) {
                   7151: 	    if      (lc($key) eq 'onload') {
                   7152: 		$on_load.=$attr_ref->{$key}.';';
                   7153: 		delete($attr_ref->{$key});
                   7154: 
                   7155: 	    } elsif (lc($key) eq 'onunload') {
                   7156: 		$on_unload.=$attr_ref->{$key}.';';
                   7157: 		delete($attr_ref->{$key});
                   7158: 	    }
                   7159: 	}
1.953     droeschl 7160: 	$attr_ref->{'onload'}  = $on_load;
                   7161: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 7162:     }
1.339     albertel 7163: 
1.330     albertel 7164:     my $attr_string;
1.1159    raeburn  7165:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 7166: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   7167:     }
                   7168:     return $attr_string;
                   7169: }
                   7170: 
                   7171: 
1.182     matthew  7172: ###############################################
1.251     albertel 7173: ###############################################
                   7174: 
                   7175: =pod
                   7176: 
                   7177: =item * &endbodytag()
                   7178: 
                   7179: Returns a uniform footer for LON-CAPA web pages.
                   7180: 
1.635     raeburn  7181: Inputs: 1 - optional reference to an args hash
                   7182: If in the hash, key for noredirectlink has a value which evaluates to true,
                   7183: a 'Continue' link is not displayed if the page contains an
                   7184: internal redirect in the <head></head> section,
                   7185: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 7186: 
                   7187: =cut
                   7188: 
                   7189: sub endbodytag {
1.635     raeburn  7190:     my ($args) = @_;
1.1080    raeburn  7191:     my $endbodytag;
                   7192:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   7193:         $endbodytag='</body>';
                   7194:     }
1.315     albertel 7195:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  7196:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  7197:             my ($endbodyjs,$idattr);
                   7198:             if ($env{'internal.head.to_opener'}) {
                   7199:                 my $linkid = 'LC_continue_link';
                   7200:                 $idattr = ' id="'.$linkid.'"';
                   7201:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   7202:                 $endbodyjs=<<ENDJS;
                   7203: <script type="text/javascript">
                   7204: // <![CDATA[
                   7205: function ebFunction(evt) {
                   7206:     evt.preventDefault();
                   7207:     var dest = '$redirect_for_js';
                   7208:     if (window.opener != null && !window.opener.closed) {
                   7209:         window.opener.location.href=dest;
                   7210:         window.close();
                   7211:     } else {
                   7212:         window.location.href=dest;
                   7213:     }
                   7214:     return false;
                   7215: }
                   7216: 
                   7217: \$(document).ready(function () {
                   7218:   if (document.getElementById('$linkid')) {
                   7219:     var clickelem = document.getElementById('$linkid');
                   7220:     clickelem.addEventListener('click',ebFunction,false);
                   7221:   }
                   7222: });
                   7223: // ]]>
                   7224: </script>
                   7225: ENDJS
                   7226:             }
1.635     raeburn  7227: 	    $endbodytag=
1.1386    raeburn  7228: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  7229: 	        &mt('Continue').'</a>'.
                   7230: 	        $endbodytag;
                   7231:         }
1.315     albertel 7232:     }
1.1411    raeburn  7233:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   7234:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   7235:     }
1.251     albertel 7236:     return $endbodytag;
                   7237: }
                   7238: 
1.352     albertel 7239: =pod
                   7240: 
                   7241: =item * &standard_css()
                   7242: 
                   7243: Returns a style sheet
                   7244: 
                   7245: Inputs: (all optional)
                   7246:             domain         -> force to color decorate a page for a specific
                   7247:                                domain
                   7248:             function       -> force usage of a specific rolish color scheme
                   7249:             bgcolor        -> override the default page bgcolor
                   7250: 
                   7251: =cut
                   7252: 
1.343     albertel 7253: sub standard_css {
1.345     albertel 7254:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 7255:     $function  = &get_users_function() if (!$function);
                   7256:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   7257:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 7258:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 7259: #second colour for later usage
1.345     albertel 7260:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 7261:     my $pgbg_or_bgcolor =
                   7262: 	         $bgcolor ||
1.352     albertel 7263: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 7264:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 7265:     my $alink  = &designparm($function.'.alink', $domain);
                   7266:     my $vlink  = &designparm($function.'.vlink', $domain);
                   7267:     my $link   = &designparm($function.'.link',  $domain);
                   7268: 
1.602     albertel 7269:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 7270:     my $mono                 = 'monospace';
1.850     bisitz   7271:     my $data_table_head      = $sidebg;
                   7272:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   7273:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 7274:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 7275:     my $data_table_highlight = '#FFFF00';
1.352     albertel 7276:     my $mail_new             = '#FFBB77';
                   7277:     my $mail_new_hover       = '#DD9955';
                   7278:     my $mail_read            = '#BBBB77';
                   7279:     my $mail_read_hover      = '#999944';
                   7280:     my $mail_replied         = '#AAAA88';
                   7281:     my $mail_replied_hover   = '#888855';
                   7282:     my $mail_other           = '#99BBBB';
                   7283:     my $mail_other_hover     = '#669999';
1.391     albertel 7284:     my $table_header         = '#DDDDDD';
1.489     raeburn  7285:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   7286:     my $lg_border_color      = '#C8C8C8';
1.952     onken    7287:     my $button_hover         = '#BF2317';
1.392     albertel 7288: 
1.608     albertel 7289:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   7290:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   7291:                                              : '0 3px 0 4px';
1.448     albertel 7292: 
1.523     albertel 7293: 
1.343     albertel 7294:     return <<END;
1.947     droeschl 7295: 
                   7296: /* needed for iframe to allow 100% height in FF */
                   7297: body, html { 
                   7298:     margin: 0;
                   7299:     padding: 0 0.5%;
                   7300:     height: 99%; /* to avoid scrollbars */
                   7301: }
                   7302: 
1.795     www      7303: body {
1.911     bisitz   7304:   font-family: $sans;
                   7305:   line-height:130%;
                   7306:   font-size:0.83em;
                   7307:   color:$font;
1.1436    raeburn  7308:   background-color: $pgbg_or_bgcolor;
1.795     www      7309: }
                   7310: 
1.959     onken    7311: a:focus,
                   7312: a:focus img {
1.795     www      7313:   color: red;
                   7314: }
1.698     harmsja  7315: 
1.911     bisitz   7316: form, .inline {
                   7317:   display: inline;
1.795     www      7318: }
1.721     harmsja  7319: 
1.1453    raeburn  7320: .LC_landmark {
                   7321:   margin: 0;
                   7322:   padding: 0;
                   7323:   border: none;
                   7324: }
                   7325: 
1.1443    raeburn  7326: .LC_visually_hidden:not(:focus):not(:active) {
                   7327:     clip-path: inset(50%);
                   7328:     height: 1px;
                   7329:     overflow: hidden;
                   7330:     position: absolute;
                   7331:     white-space: nowrap;
                   7332:     width: 1px;
                   7333:     display: inline;
                   7334: }
                   7335: 
1.1453    raeburn  7336: .LC_heading_2 {
                   7337:   font-size: 1.17em;
                   7338: }
                   7339: 
1.1421    raeburn  7340: .LC_menus_content.shown{
1.1428    raeburn  7341:   display: block;
1.1421    raeburn  7342: }
                   7343: 
                   7344: .LC_menus_content.hidden {
                   7345:   display: none;
                   7346: }
                   7347: 
1.795     www      7348: .LC_right {
1.911     bisitz   7349:   text-align:right;
1.795     www      7350: }
                   7351: 
1.1449    raeburn  7352: .LC_center {
                   7353:   text-align:center;
                   7354: }
                   7355: 
1.795     www      7356: .LC_middle {
1.911     bisitz   7357:   vertical-align:middle;
1.795     www      7358: }
1.721     harmsja  7359: 
1.1130    raeburn  7360: .LC_floatleft {
                   7361:   float: left;
                   7362: }
                   7363: 
                   7364: .LC_floatright {
                   7365:   float: right;
                   7366: }
                   7367: 
1.911     bisitz   7368: .LC_400Box {
                   7369:   width:400px;
                   7370: }
1.721     harmsja  7371: 
1.1421    raeburn  7372: #LC_collapsible_separator {
                   7373:     border: 1px solid black;
                   7374:     width: 99.9%;
                   7375:     height: 0px;
                   7376: }
                   7377: 
1.947     droeschl 7378: .LC_iframecontainer {
                   7379:     width: 98%;
                   7380:     margin: 0;
                   7381:     position: fixed;
                   7382:     top: 8.5em;
                   7383:     bottom: 0;
                   7384: }
                   7385: 
                   7386: .LC_iframecontainer iframe{
                   7387:     border: none;
                   7388:     width: 100%;
                   7389:     height: 100%;
                   7390: }
                   7391: 
1.778     bisitz   7392: .LC_filename {
                   7393:   font-family: $mono;
                   7394:   white-space:pre;
1.921     bisitz   7395:   font-size: 120%;
1.778     bisitz   7396: }
                   7397: 
                   7398: .LC_fileicon {
                   7399:   border: none;
                   7400:   height: 1.3em;
                   7401:   vertical-align: text-bottom;
                   7402:   margin-right: 0.3em;
                   7403:   text-decoration:none;
                   7404: }
                   7405: 
1.1008    www      7406: .LC_setting {
                   7407:   text-decoration:underline;
                   7408: }
                   7409: 
1.350     albertel 7410: .LC_error {
                   7411:   color: red;
                   7412: }
1.795     www      7413: 
1.1097    bisitz   7414: .LC_warning {
                   7415:   color: darkorange;
                   7416: }
                   7417: 
1.457     albertel 7418: .LC_diff_removed {
1.733     bisitz   7419:   color: red;
1.394     albertel 7420: }
1.532     albertel 7421: 
                   7422: .LC_info,
1.457     albertel 7423: .LC_success,
                   7424: .LC_diff_added {
1.350     albertel 7425:   color: green;
                   7426: }
1.795     www      7427: 
1.802     bisitz   7428: div.LC_confirm_box {
                   7429:   background-color: #FAFAFA;
                   7430:   border: 1px solid $lg_border_color;
                   7431:   margin-right: 0;
                   7432:   padding: 5px;
                   7433: }
                   7434: 
                   7435: div.LC_confirm_box .LC_error img,
                   7436: div.LC_confirm_box .LC_success img {
                   7437:   vertical-align: middle;
                   7438: }
                   7439: 
1.1242    raeburn  7440: .LC_maxwidth {
                   7441:   max-width: 100%;
                   7442:   height: auto;
                   7443: }
                   7444: 
1.1243    raeburn  7445: .LC_textsize_mobile {
                   7446:   \@media only screen and (max-device-width: 480px) {
                   7447:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   7448:   }
                   7449: }
                   7450: 
1.440     albertel 7451: .LC_icon {
1.771     droeschl 7452:   border: none;
1.790     droeschl 7453:   vertical-align: middle;
1.771     droeschl 7454: }
                   7455: 
1.543     albertel 7456: .LC_docs_spacer {
                   7457:   width: 25px;
                   7458:   height: 1px;
1.771     droeschl 7459:   border: none;
1.543     albertel 7460: }
1.346     albertel 7461: 
1.532     albertel 7462: .LC_internal_info {
1.735     bisitz   7463:   color: #999999;
1.532     albertel 7464: }
                   7465: 
1.794     www      7466: .LC_discussion {
1.1050    www      7467:   background: $data_table_dark;
1.911     bisitz   7468:   border: 1px solid black;
                   7469:   margin: 2px;
1.794     www      7470: }
                   7471: 
                   7472: .LC_disc_action_left {
1.1050    www      7473:   background: $sidebg;
1.911     bisitz   7474:   text-align: left;
1.1050    www      7475:   padding: 4px;
                   7476:   margin: 2px;
1.794     www      7477: }
                   7478: 
                   7479: .LC_disc_action_right {
1.1050    www      7480:   background: $sidebg;
1.911     bisitz   7481:   text-align: right;
1.1050    www      7482:   padding: 4px;
                   7483:   margin: 2px;
1.794     www      7484: }
                   7485: 
                   7486: .LC_disc_new_item {
1.911     bisitz   7487:   background: white;
                   7488:   border: 2px solid red;
1.1050    www      7489:   margin: 4px;
                   7490:   padding: 4px;
1.794     www      7491: }
                   7492: 
                   7493: .LC_disc_old_item {
1.911     bisitz   7494:   background: white;
1.1050    www      7495:   margin: 4px;
                   7496:   padding: 4px;
1.794     www      7497: }
                   7498: 
1.458     albertel 7499: table.LC_pastsubmission {
                   7500:   border: 1px solid black;
                   7501:   margin: 2px;
                   7502: }
                   7503: 
1.924     bisitz   7504: table#LC_menubuttons {
1.345     albertel 7505:   width: 100%;
                   7506:   background: $pgbg;
1.392     albertel 7507:   border: 2px;
1.402     albertel 7508:   border-collapse: separate;
1.803     bisitz   7509:   padding: 0;
1.345     albertel 7510: }
1.392     albertel 7511: 
1.801     tempelho 7512: table#LC_title_bar a {
                   7513:   color: $fontmenu;
                   7514: }
1.836     bisitz   7515: 
1.807     droeschl 7516: table#LC_title_bar {
1.819     tempelho 7517:   clear: both;
1.836     bisitz   7518:   display: none;
1.807     droeschl 7519: }
                   7520: 
1.795     www      7521: table#LC_title_bar,
1.933     droeschl 7522: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 7523: table#LC_title_bar.LC_with_remote {
1.359     albertel 7524:   width: 100%;
1.392     albertel 7525:   border-color: $pgbg;
                   7526:   border-style: solid;
                   7527:   border-width: $border;
1.379     albertel 7528:   background: $pgbg;
1.801     tempelho 7529:   color: $fontmenu;
1.392     albertel 7530:   border-collapse: collapse;
1.803     bisitz   7531:   padding: 0;
1.819     tempelho 7532:   margin: 0;
1.359     albertel 7533: }
1.795     www      7534: 
1.933     droeschl 7535: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 7536:     margin: 0;
                   7537:     padding: 0;
1.933     droeschl 7538:     position: relative;
                   7539:     list-style: none;
1.913     droeschl 7540: }
1.933     droeschl 7541: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 7542:     display: inline;
                   7543: }
1.933     droeschl 7544: 
                   7545: .LC_breadcrumb_tools_navigation {
1.913     droeschl 7546:     padding: 0;
1.933     droeschl 7547:     margin: 0;
                   7548:     float: left;
1.913     droeschl 7549: }
1.933     droeschl 7550: .LC_breadcrumb_tools_tools {
                   7551:     padding: 0;
                   7552:     margin: 0;
1.913     droeschl 7553:     float: right;
                   7554: }
                   7555: 
1.1240    raeburn  7556: .LC_placement_prog {
                   7557:     padding-right: 20px;
                   7558:     font-weight: bold;
                   7559:     font-size: 90%;
                   7560: }
                   7561: 
1.359     albertel 7562: table#LC_title_bar td {
                   7563:   background: $tabbg;
                   7564: }
1.795     www      7565: 
1.911     bisitz   7566: table#LC_menubuttons img {
1.803     bisitz   7567:   border: none;
1.346     albertel 7568: }
1.795     www      7569: 
1.842     droeschl 7570: .LC_breadcrumbs_component {
1.911     bisitz   7571:   float: right;
                   7572:   margin: 0 1em;
1.357     albertel 7573: }
1.842     droeschl 7574: .LC_breadcrumbs_component img {
1.911     bisitz   7575:   vertical-align: middle;
1.777     tempelho 7576: }
1.795     www      7577: 
1.1243    raeburn  7578: .LC_breadcrumbs_hoverable {
                   7579:   background: $sidebg;
                   7580: }
                   7581: 
1.383     albertel 7582: td.LC_table_cell_checkbox {
                   7583:   text-align: center;
                   7584: }
1.795     www      7585: 
                   7586: .LC_fontsize_small {
1.911     bisitz   7587:   font-size: 70%;
1.705     tempelho 7588: }
                   7589: 
1.844     bisitz   7590: #LC_breadcrumbs {
1.911     bisitz   7591:   clear:both;
                   7592:   background: $sidebg;
                   7593:   border-bottom: 1px solid $lg_border_color;
                   7594:   line-height: 2.5em;
1.933     droeschl 7595:   overflow: hidden;
1.911     bisitz   7596:   margin: 0;
                   7597:   padding: 0;
1.995     raeburn  7598:   text-align: left;
1.819     tempelho 7599: }
1.862     bisitz   7600: 
1.1098    bisitz   7601: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7602:   clear:both;
                   7603:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7604:   border: 1px solid $sidebg;
1.1098    bisitz   7605:   margin: 0 0 10px 0;
1.966     bisitz   7606:   padding: 3px;
1.995     raeburn  7607:   text-align: left;
1.822     bisitz   7608: }
                   7609: 
1.795     www      7610: .LC_fontsize_medium {
1.911     bisitz   7611:   font-size: 85%;
1.705     tempelho 7612: }
                   7613: 
1.795     www      7614: .LC_fontsize_large {
1.911     bisitz   7615:   font-size: 120%;
1.705     tempelho 7616: }
                   7617: 
1.346     albertel 7618: .LC_menubuttons_inline_text {
                   7619:   color: $font;
1.698     harmsja  7620:   font-size: 90%;
1.701     harmsja  7621:   padding-left:3px;
1.346     albertel 7622: }
                   7623: 
1.934     droeschl 7624: .LC_menubuttons_inline_text img{
                   7625:   vertical-align: middle;
                   7626: }
                   7627: 
1.1051    www      7628: li.LC_menubuttons_inline_text img {
1.951     onken    7629:   cursor:pointer;
1.1002    droeschl 7630:   text-decoration: none;
1.951     onken    7631: }
                   7632: 
1.526     www      7633: .LC_menubuttons_link {
                   7634:   text-decoration: none;
                   7635: }
1.795     www      7636: 
1.522     albertel 7637: .LC_menubuttons_category {
1.521     www      7638:   color: $font;
1.526     www      7639:   background: $pgbg;
1.521     www      7640:   font-size: larger;
                   7641:   font-weight: bold;
                   7642: }
                   7643: 
1.346     albertel 7644: td.LC_menubuttons_text {
1.911     bisitz   7645:   color: $font;
1.346     albertel 7646: }
1.706     harmsja  7647: 
1.346     albertel 7648: .LC_current_location {
                   7649:   background: $tabbg;
                   7650: }
1.795     www      7651: 
1.1286    raeburn  7652: td.LC_zero_height {
                   7653:   line-height: 0; 
                   7654:   cellpadding: 0;
                   7655: }
                   7656: 
1.938     bisitz   7657: table.LC_data_table {
1.347     albertel 7658:   border: 1px solid #000000;
1.402     albertel 7659:   border-collapse: separate;
1.426     albertel 7660:   border-spacing: 1px;
1.610     albertel 7661:   background: $pgbg;
1.347     albertel 7662: }
1.795     www      7663: 
1.422     albertel 7664: .LC_data_table_dense {
                   7665:   font-size: small;
                   7666: }
1.795     www      7667: 
1.507     raeburn  7668: table.LC_nested_outer {
                   7669:   border: 1px solid #000000;
1.589     raeburn  7670:   border-collapse: collapse;
1.803     bisitz   7671:   border-spacing: 0;
1.507     raeburn  7672:   width: 100%;
                   7673: }
1.795     www      7674: 
1.879     raeburn  7675: table.LC_innerpickbox,
1.507     raeburn  7676: table.LC_nested {
1.803     bisitz   7677:   border: none;
1.589     raeburn  7678:   border-collapse: collapse;
1.803     bisitz   7679:   border-spacing: 0;
1.507     raeburn  7680:   width: 100%;
                   7681: }
1.795     www      7682: 
1.911     bisitz   7683: table.LC_data_table tr th,
                   7684: table.LC_calendar tr th,
1.879     raeburn  7685: table.LC_prior_tries tr th,
                   7686: table.LC_innerpickbox tr th {
1.349     albertel 7687:   font-weight: bold;
                   7688:   background-color: $data_table_head;
1.801     tempelho 7689:   color:$fontmenu;
1.701     harmsja  7690:   font-size:90%;
1.347     albertel 7691: }
1.795     www      7692: 
1.879     raeburn  7693: table.LC_innerpickbox tr th,
                   7694: table.LC_innerpickbox tr td {
                   7695:   vertical-align: top;
                   7696: }
                   7697: 
1.711     raeburn  7698: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7699:   background-color: #CCCCCC;
1.711     raeburn  7700:   font-weight: bold;
                   7701:   text-align: left;
                   7702: }
1.795     www      7703: 
1.912     bisitz   7704: table.LC_data_table tr.LC_odd_row > td {
                   7705:   background-color: $data_table_light;
                   7706:   padding: 2px;
                   7707:   vertical-align: top;
                   7708: }
                   7709: 
1.809     bisitz   7710: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7711:   background-color: $data_table_light;
1.912     bisitz   7712:   vertical-align: top;
                   7713: }
                   7714: 
                   7715: table.LC_data_table tr.LC_even_row > td {
                   7716:   background-color: $data_table_dark;
1.425     albertel 7717:   padding: 2px;
1.900     bisitz   7718:   vertical-align: top;
1.347     albertel 7719: }
1.795     www      7720: 
1.809     bisitz   7721: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7722:   background-color: $data_table_dark;
1.900     bisitz   7723:   vertical-align: top;
1.347     albertel 7724: }
1.795     www      7725: 
1.425     albertel 7726: table.LC_data_table tr.LC_data_table_highlight td {
                   7727:   background-color: $data_table_darker;
                   7728: }
1.795     www      7729: 
1.639     raeburn  7730: table.LC_data_table tr td.LC_leftcol_header {
                   7731:   background-color: $data_table_head;
                   7732:   font-weight: bold;
                   7733: }
1.795     www      7734: 
1.451     albertel 7735: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7736: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7737:   font-weight: bold;
                   7738:   font-style: italic;
                   7739:   text-align: center;
                   7740:   padding: 8px;
1.347     albertel 7741: }
1.795     www      7742: 
1.1114    raeburn  7743: table.LC_data_table tr.LC_empty_row td,
                   7744: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7745:   background-color: $sidebg;
                   7746: }
                   7747: 
                   7748: table.LC_nested tr.LC_empty_row td {
                   7749:   background-color: #FFFFFF;
                   7750: }
                   7751: 
1.890     droeschl 7752: table.LC_caption {
                   7753: }
                   7754: 
1.507     raeburn  7755: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7756:   padding: 4ex
                   7757: }
1.795     www      7758: 
1.507     raeburn  7759: table.LC_nested_outer tr th {
                   7760:   font-weight: bold;
1.801     tempelho 7761:   color:$fontmenu;
1.507     raeburn  7762:   background-color: $data_table_head;
1.701     harmsja  7763:   font-size: small;
1.507     raeburn  7764:   border-bottom: 1px solid #000000;
                   7765: }
1.795     www      7766: 
1.507     raeburn  7767: table.LC_nested_outer tr td.LC_subheader {
                   7768:   background-color: $data_table_head;
                   7769:   font-weight: bold;
                   7770:   font-size: small;
                   7771:   border-bottom: 1px solid #000000;
                   7772:   text-align: right;
1.451     albertel 7773: }
1.795     www      7774: 
1.507     raeburn  7775: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7776:   background-color: #CCCCCC;
1.451     albertel 7777:   font-weight: bold;
                   7778:   font-size: small;
1.507     raeburn  7779:   text-align: center;
                   7780: }
1.795     www      7781: 
1.589     raeburn  7782: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7783: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7784:   text-align: left;
1.451     albertel 7785: }
1.795     www      7786: 
1.507     raeburn  7787: table.LC_nested td {
1.735     bisitz   7788:   background-color: #FFFFFF;
1.451     albertel 7789:   font-size: small;
1.507     raeburn  7790: }
1.795     www      7791: 
1.507     raeburn  7792: table.LC_nested_outer tr th.LC_right_item,
                   7793: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7794: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7795: table.LC_nested tr td.LC_right_item {
1.451     albertel 7796:   text-align: right;
                   7797: }
                   7798: 
1.507     raeburn  7799: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7800:   background-color: #EEEEEE;
1.451     albertel 7801: }
                   7802: 
1.473     raeburn  7803: table.LC_createuser {
                   7804: }
                   7805: 
                   7806: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7807:   font-size: small;
1.473     raeburn  7808: }
                   7809: 
                   7810: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7811:   background-color: #CCCCCC;
1.473     raeburn  7812:   font-weight: bold;
                   7813:   text-align: center;
                   7814: }
                   7815: 
1.349     albertel 7816: table.LC_calendar {
                   7817:   border: 1px solid #000000;
                   7818:   border-collapse: collapse;
1.917     raeburn  7819:   width: 98%;
1.349     albertel 7820: }
1.795     www      7821: 
1.349     albertel 7822: table.LC_calendar_pickdate {
                   7823:   font-size: xx-small;
                   7824: }
1.795     www      7825: 
1.349     albertel 7826: table.LC_calendar tr td {
                   7827:   border: 1px solid #000000;
                   7828:   vertical-align: top;
1.917     raeburn  7829:   width: 14%;
1.349     albertel 7830: }
1.795     www      7831: 
1.349     albertel 7832: table.LC_calendar tr td.LC_calendar_day_empty {
                   7833:   background-color: $data_table_dark;
                   7834: }
1.795     www      7835: 
1.779     bisitz   7836: table.LC_calendar tr td.LC_calendar_day_current {
                   7837:   background-color: $data_table_highlight;
1.777     tempelho 7838: }
1.795     www      7839: 
1.938     bisitz   7840: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7841:   background-color: $mail_new;
                   7842: }
1.795     www      7843: 
1.938     bisitz   7844: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7845:   background-color: $mail_new_hover;
                   7846: }
1.795     www      7847: 
1.938     bisitz   7848: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7849:   background-color: $mail_read;
                   7850: }
1.795     www      7851: 
1.938     bisitz   7852: /*
                   7853: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7854:   background-color: $mail_read_hover;
                   7855: }
1.938     bisitz   7856: */
1.795     www      7857: 
1.938     bisitz   7858: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7859:   background-color: $mail_replied;
                   7860: }
1.795     www      7861: 
1.938     bisitz   7862: /*
                   7863: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7864:   background-color: $mail_replied_hover;
                   7865: }
1.938     bisitz   7866: */
1.795     www      7867: 
1.938     bisitz   7868: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7869:   background-color: $mail_other;
                   7870: }
1.795     www      7871: 
1.938     bisitz   7872: /*
                   7873: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7874:   background-color: $mail_other_hover;
                   7875: }
1.938     bisitz   7876: */
1.494     raeburn  7877: 
1.777     tempelho 7878: table.LC_data_table tr > td.LC_browser_file,
                   7879: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7880:   background: #AAEE77;
1.389     albertel 7881: }
1.795     www      7882: 
1.777     tempelho 7883: table.LC_data_table tr > td.LC_browser_file_locked,
                   7884: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7885:   background: #FFAA99;
1.387     albertel 7886: }
1.795     www      7887: 
1.777     tempelho 7888: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7889:   background: #888888;
1.779     bisitz   7890: }
1.795     www      7891: 
1.777     tempelho 7892: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7893: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7894:   background: #F8F866;
1.777     tempelho 7895: }
1.795     www      7896: 
1.696     bisitz   7897: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7898:   background: #E0E8FF;
1.387     albertel 7899: }
1.696     bisitz   7900: 
1.707     bisitz   7901: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7902:   /* background: #77FF77; */
1.707     bisitz   7903: }
1.795     www      7904: 
1.707     bisitz   7905: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7906:   border-right: 8px solid #FFFF77;
1.707     bisitz   7907: }
1.795     www      7908: 
1.707     bisitz   7909: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7910:   border-right: 8px solid #FFAA77;
1.707     bisitz   7911: }
1.795     www      7912: 
1.707     bisitz   7913: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7914:   border-right: 8px solid #FF7777;
1.707     bisitz   7915: }
1.795     www      7916: 
1.707     bisitz   7917: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7918:   border-right: 8px solid #AAFF77;
1.707     bisitz   7919: }
1.795     www      7920: 
1.707     bisitz   7921: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7922:   border-right: 8px solid #11CC55;
1.707     bisitz   7923: }
                   7924: 
1.388     albertel 7925: span.LC_current_location {
1.701     harmsja  7926:   font-size:larger;
1.388     albertel 7927:   background: $pgbg;
                   7928: }
1.387     albertel 7929: 
1.1029    www      7930: span.LC_current_nav_location {
                   7931:   font-weight:bold;
                   7932:   background: $sidebg;
                   7933: }
                   7934: 
1.395     albertel 7935: span.LC_parm_menu_item {
                   7936:   font-size: larger;
                   7937: }
1.795     www      7938: 
1.395     albertel 7939: span.LC_parm_scope_all {
                   7940:   color: red;
                   7941: }
1.795     www      7942: 
1.395     albertel 7943: span.LC_parm_scope_folder {
                   7944:   color: green;
                   7945: }
1.795     www      7946: 
1.395     albertel 7947: span.LC_parm_scope_resource {
                   7948:   color: orange;
                   7949: }
1.795     www      7950: 
1.395     albertel 7951: span.LC_parm_part {
                   7952:   color: blue;
                   7953: }
1.795     www      7954: 
1.911     bisitz   7955: span.LC_parm_folder,
                   7956: span.LC_parm_symb {
1.395     albertel 7957:   font-size: x-small;
                   7958:   font-family: $mono;
                   7959:   color: #AAAAAA;
                   7960: }
                   7961: 
1.977     bisitz   7962: ul.LC_parm_parmlist li {
                   7963:   display: inline-block;
                   7964:   padding: 0.3em 0.8em;
                   7965:   vertical-align: top;
                   7966:   width: 150px;
                   7967:   border-top:1px solid $lg_border_color;
                   7968: }
                   7969: 
1.795     www      7970: td.LC_parm_overview_level_menu,
                   7971: td.LC_parm_overview_map_menu,
                   7972: td.LC_parm_overview_parm_selectors,
                   7973: td.LC_parm_overview_restrictions  {
1.396     albertel 7974:   border: 1px solid black;
                   7975:   border-collapse: collapse;
                   7976: }
1.795     www      7977: 
1.1285    raeburn  7978: span.LC_parm_recursive,
                   7979: td.LC_parm_recursive {
                   7980:   font-weight: bold;
                   7981:   font-size: smaller;
                   7982: }
                   7983: 
1.396     albertel 7984: table.LC_parm_overview_restrictions td {
                   7985:   border-width: 1px 4px 1px 4px;
                   7986:   border-style: solid;
                   7987:   border-color: $pgbg;
                   7988:   text-align: center;
                   7989: }
1.795     www      7990: 
1.396     albertel 7991: table.LC_parm_overview_restrictions th {
                   7992:   background: $tabbg;
                   7993:   border-width: 1px 4px 1px 4px;
                   7994:   border-style: solid;
                   7995:   border-color: $pgbg;
                   7996: }
1.795     www      7997: 
1.398     albertel 7998: table#LC_helpmenu {
1.803     bisitz   7999:   border: none;
1.398     albertel 8000:   height: 55px;
1.803     bisitz   8001:   border-spacing: 0;
1.398     albertel 8002: }
                   8003: 
                   8004: table#LC_helpmenu fieldset legend {
                   8005:   font-size: larger;
                   8006: }
1.795     www      8007: 
1.1456    raeburn  8008: .LC_helpdesk_headbox {
                   8009:   border: 2px groove threedface;
                   8010:   padding: 1em;
                   8011: }
                   8012: 
                   8013: h1.LC_helpdesk_legend {
                   8014:   float: left;
                   8015:   margin: -1.7em 0 0;
                   8016:   padding: 0 .5em;
1.397     albertel 8017:   background: $pgbg;
1.1456    raeburn  8018:   font-size: 1em;
                   8019:   font-weight: bold;
                   8020: }
                   8021: 
                   8022: h1.LC_helpdesk_title {
                   8023:   display: inline;
                   8024:   font-size: 1em;
                   8025:   line-height: 2.5em;
                   8026:   margin: 0;
1.803     bisitz   8027:   padding: 0;
1.1456    raeburn  8028:   vertical-align: bottom;
1.397     albertel 8029: }
1.795     www      8030: 
1.1456    raeburn  8031: .LC_helpdesk_links {
                   8032:   border: 1px solid black;
                   8033:   padding: 3px;
1.397     albertel 8034:   background: $tabbg;
1.399     albertel 8035:   text-align: center;
                   8036:   font-weight: bold;
1.1456    raeburn  8037:   display: inline;
                   8038:   margin-right: -6px;
                   8039: }
                   8040: 
                   8041: .LC_helpdesk_img,
                   8042: .LC_helpdesk_text {
                   8043:   padding: 0;
                   8044:   margin: 0;
                   8045:   border: 0;
                   8046:   display: inline;
1.397     albertel 8047: }
1.396     albertel 8048: 
1.1456    raeburn  8049: .LC_helpdesk_img a:link,
                   8050: .LC_helpdesk_img a:visited,
                   8051: .LC_helpdesk_img a:active,
                   8052: .LC_helpdesk_text a:link,
                   8053: .LC_helpdesk_text a:visited,
                   8054: .LC_helpdesk_text a:active {
1.397     albertel 8055:   text-decoration: none;
                   8056:   color: $font;
                   8057: }
1.795     www      8058: 
1.1456    raeburn  8059: div.LC_helpdesk_text a:hover {
1.397     albertel 8060:   text-decoration: underline;
                   8061:   color: $vlink;
                   8062: }
1.396     albertel 8063: 
1.417     albertel 8064: .LC_chrt_popup_exists {
                   8065:   border: 1px solid #339933;
                   8066:   margin: -1px;
                   8067: }
1.795     www      8068: 
1.417     albertel 8069: .LC_chrt_popup_up {
                   8070:   border: 1px solid yellow;
                   8071:   margin: -1px;
                   8072: }
1.795     www      8073: 
1.417     albertel 8074: .LC_chrt_popup {
                   8075:   border: 1px solid #8888FF;
                   8076:   background: #CCCCFF;
                   8077: }
1.795     www      8078: 
1.421     albertel 8079: table.LC_pick_box {
                   8080:   border-collapse: separate;
                   8081:   background: white;
                   8082:   border: 1px solid black;
                   8083:   border-spacing: 1px;
                   8084: }
1.795     www      8085: 
1.1454    raeburn  8086: table.LC_pick_box th.LC_pick_box_title {
1.850     bisitz   8087:   background: $sidebg;
1.421     albertel 8088:   font-weight: bold;
1.900     bisitz   8089:   text-align: left;
1.740     bisitz   8090:   vertical-align: top;
1.421     albertel 8091:   width: 184px;
                   8092:   padding: 8px;
                   8093: }
1.795     www      8094: 
1.579     raeburn  8095: table.LC_pick_box td.LC_pick_box_value {
                   8096:   text-align: left;
                   8097:   padding: 8px;
                   8098: }
1.795     www      8099: 
1.579     raeburn  8100: table.LC_pick_box td.LC_pick_box_select {
                   8101:   text-align: left;
                   8102:   padding: 8px;
                   8103: }
1.795     www      8104: 
1.424     albertel 8105: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   8106:   padding: 0;
1.421     albertel 8107:   height: 1px;
                   8108:   background: black;
                   8109: }
1.795     www      8110: 
1.421     albertel 8111: table.LC_pick_box td.LC_pick_box_submit {
                   8112:   text-align: right;
                   8113: }
1.795     www      8114: 
1.579     raeburn  8115: table.LC_pick_box td.LC_evenrow_value {
                   8116:   text-align: left;
                   8117:   padding: 8px;
                   8118:   background-color: $data_table_light;
                   8119: }
1.795     www      8120: 
1.579     raeburn  8121: table.LC_pick_box td.LC_oddrow_value {
                   8122:   text-align: left;
                   8123:   padding: 8px;
                   8124:   background-color: $data_table_light;
                   8125: }
1.795     www      8126: 
1.579     raeburn  8127: span.LC_helpform_receipt_cat {
                   8128:   font-weight: bold;
                   8129: }
1.795     www      8130: 
1.424     albertel 8131: table.LC_group_priv_box {
                   8132:   background: white;
                   8133:   border: 1px solid black;
                   8134:   border-spacing: 1px;
                   8135: }
1.795     www      8136: 
1.424     albertel 8137: table.LC_group_priv_box td.LC_pick_box_title {
                   8138:   background: $tabbg;
                   8139:   font-weight: bold;
                   8140:   text-align: right;
                   8141:   width: 184px;
                   8142: }
1.795     www      8143: 
1.424     albertel 8144: table.LC_group_priv_box td.LC_groups_fixed {
                   8145:   background: $data_table_light;
                   8146:   text-align: center;
                   8147: }
1.795     www      8148: 
1.424     albertel 8149: table.LC_group_priv_box td.LC_groups_optional {
                   8150:   background: $data_table_dark;
                   8151:   text-align: center;
                   8152: }
1.795     www      8153: 
1.424     albertel 8154: table.LC_group_priv_box td.LC_groups_functionality {
                   8155:   background: $data_table_darker;
                   8156:   text-align: center;
                   8157:   font-weight: bold;
                   8158: }
1.795     www      8159: 
1.424     albertel 8160: table.LC_group_priv td {
                   8161:   text-align: left;
1.803     bisitz   8162:   padding: 0;
1.424     albertel 8163: }
                   8164: 
                   8165: .LC_navbuttons {
                   8166:   margin: 2ex 0ex 2ex 0ex;
                   8167: }
1.795     www      8168: 
1.423     albertel 8169: .LC_topic_bar {
                   8170:   font-weight: bold;
                   8171:   background: $tabbg;
1.918     wenzelju 8172:   margin: 1em 0em 1em 2em;
1.805     bisitz   8173:   padding: 3px;
1.918     wenzelju 8174:   font-size: 1.2em;
1.423     albertel 8175: }
1.795     www      8176: 
1.423     albertel 8177: .LC_topic_bar span {
1.918     wenzelju 8178:   left: 0.5em;
                   8179:   position: absolute;
1.423     albertel 8180:   vertical-align: middle;
1.918     wenzelju 8181:   font-size: 1.2em;
1.423     albertel 8182: }
1.795     www      8183: 
1.423     albertel 8184: table.LC_course_group_status {
                   8185:   margin: 20px;
                   8186: }
1.795     www      8187: 
1.423     albertel 8188: table.LC_status_selector td {
                   8189:   vertical-align: top;
                   8190:   text-align: center;
1.424     albertel 8191:   padding: 4px;
                   8192: }
1.795     www      8193: 
1.599     albertel 8194: div.LC_feedback_link {
1.616     albertel 8195:   clear: both;
1.829     kalberla 8196:   background: $sidebg;
1.779     bisitz   8197:   width: 100%;
1.829     kalberla 8198:   padding-bottom: 10px;
                   8199:   border: 1px $tabbg solid;
1.833     kalberla 8200:   height: 22px;
                   8201:   line-height: 22px;
                   8202:   padding-top: 5px;
                   8203: }
                   8204: 
                   8205: div.LC_feedback_link img {
                   8206:   height: 22px;
1.867     kalberla 8207:   vertical-align:middle;
1.829     kalberla 8208: }
                   8209: 
1.911     bisitz   8210: div.LC_feedback_link a {
1.829     kalberla 8211:   text-decoration: none;
1.489     raeburn  8212: }
1.795     www      8213: 
1.867     kalberla 8214: div.LC_comblock {
1.911     bisitz   8215:   display:inline;
1.867     kalberla 8216:   color:$font;
                   8217:   font-size:90%;
                   8218: }
                   8219: 
                   8220: div.LC_feedback_link div.LC_comblock {
                   8221:   padding-left:5px;
                   8222: }
                   8223: 
                   8224: div.LC_feedback_link div.LC_comblock a {
                   8225:   color:$font;
                   8226: }
                   8227: 
1.489     raeburn  8228: span.LC_feedback_link {
1.858     bisitz   8229:   /* background: $feedback_link_bg; */
1.599     albertel 8230:   font-size: larger;
                   8231: }
1.795     www      8232: 
1.599     albertel 8233: span.LC_message_link {
1.858     bisitz   8234:   /* background: $feedback_link_bg; */
1.599     albertel 8235:   font-size: larger;
                   8236:   position: absolute;
                   8237:   right: 1em;
1.489     raeburn  8238: }
1.421     albertel 8239: 
1.515     albertel 8240: table.LC_prior_tries {
1.524     albertel 8241:   border: 1px solid #000000;
                   8242:   border-collapse: separate;
                   8243:   border-spacing: 1px;
1.515     albertel 8244: }
1.523     albertel 8245: 
1.515     albertel 8246: table.LC_prior_tries td {
1.524     albertel 8247:   padding: 2px;
1.515     albertel 8248: }
1.523     albertel 8249: 
                   8250: .LC_answer_correct {
1.795     www      8251:   background: lightgreen;
                   8252:   color: darkgreen;
                   8253:   padding: 6px;
1.523     albertel 8254: }
1.795     www      8255: 
1.523     albertel 8256: .LC_answer_charged_try {
1.797     www      8257:   background: #FFAAAA;
1.795     www      8258:   color: darkred;
                   8259:   padding: 6px;
1.523     albertel 8260: }
1.795     www      8261: 
1.779     bisitz   8262: .LC_answer_not_charged_try,
1.523     albertel 8263: .LC_answer_no_grade,
                   8264: .LC_answer_late {
1.795     www      8265:   background: lightyellow;
1.523     albertel 8266:   color: black;
1.795     www      8267:   padding: 6px;
1.523     albertel 8268: }
1.795     www      8269: 
1.523     albertel 8270: .LC_answer_previous {
1.795     www      8271:   background: lightblue;
                   8272:   color: darkblue;
                   8273:   padding: 6px;
1.523     albertel 8274: }
1.795     www      8275: 
1.779     bisitz   8276: .LC_answer_no_message {
1.777     tempelho 8277:   background: #FFFFFF;
                   8278:   color: black;
1.795     www      8279:   padding: 6px;
1.779     bisitz   8280: }
1.795     www      8281: 
1.1334    raeburn  8282: .LC_answer_unknown,
                   8283: .LC_answer_warning {
1.779     bisitz   8284:   background: orange;
                   8285:   color: black;
1.795     www      8286:   padding: 6px;
1.777     tempelho 8287: }
1.795     www      8288: 
1.1446    raeburn  8289: .LC_prob_status {
1.1447    raeburn  8290:   margin-top: 5px;
1.1446    raeburn  8291:   padding-top: 0;
                   8292:   padding-left: 0;
                   8293:   padding-bottom: 0;
                   8294:   padding-right: 5px;
                   8295: }
                   8296: 
1.1448    raeburn  8297: .LC_mail_actions {
                   8298:   float: left;
                   8299:   padding: 0;
                   8300:   margin: 6px;
                   8301: }
                   8302: 
                   8303: .LC_vertical_line {
                   8304:   width: 1px;
                   8305:   background-color: black;
                   8306:   height: 4em;
                   8307:   float: left;
                   8308:   margin: 0;
                   8309:   padding: 0;
                   8310: }
                   8311: 
1.529     albertel 8312: span.LC_prior_numerical,
                   8313: span.LC_prior_string,
                   8314: span.LC_prior_custom,
                   8315: span.LC_prior_reaction,
                   8316: span.LC_prior_math {
1.925     bisitz   8317:   font-family: $mono;
1.523     albertel 8318:   white-space: pre;
                   8319: }
                   8320: 
1.525     albertel 8321: span.LC_prior_string {
1.925     bisitz   8322:   font-family: $mono;
1.525     albertel 8323:   white-space: pre;
                   8324: }
                   8325: 
1.523     albertel 8326: table.LC_prior_option {
                   8327:   width: 100%;
                   8328:   border-collapse: collapse;
                   8329: }
1.795     www      8330: 
1.911     bisitz   8331: table.LC_prior_rank,
1.795     www      8332: table.LC_prior_match {
1.528     albertel 8333:   border-collapse: collapse;
                   8334: }
1.795     www      8335: 
1.528     albertel 8336: table.LC_prior_option tr td,
                   8337: table.LC_prior_rank tr td,
                   8338: table.LC_prior_match tr td {
1.524     albertel 8339:   border: 1px solid #000000;
1.515     albertel 8340: }
                   8341: 
1.855     bisitz   8342: .LC_nobreak {
1.544     albertel 8343:   white-space: nowrap;
1.519     raeburn  8344: }
                   8345: 
1.576     raeburn  8346: span.LC_cusr_emph {
                   8347:   font-style: italic;
                   8348: }
                   8349: 
1.633     raeburn  8350: span.LC_cusr_subheading {
                   8351:   font-weight: normal;
                   8352:   font-size: 85%;
                   8353: }
                   8354: 
1.861     bisitz   8355: div.LC_docs_entry_move {
1.859     bisitz   8356:   border: 1px solid #BBBBBB;
1.545     albertel 8357:   background: #DDDDDD;
1.861     bisitz   8358:   width: 22px;
1.859     bisitz   8359:   padding: 1px;
                   8360:   margin: 0;
1.545     albertel 8361: }
                   8362: 
1.861     bisitz   8363: table.LC_data_table tr > td.LC_docs_entry_commands,
                   8364: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 8365:   font-size: x-small;
                   8366: }
1.795     www      8367: 
1.861     bisitz   8368: .LC_docs_entry_parameter {
                   8369:   white-space: nowrap;
                   8370: }
                   8371: 
1.544     albertel 8372: .LC_docs_copy {
1.545     albertel 8373:   color: #000099;
1.544     albertel 8374: }
1.795     www      8375: 
1.544     albertel 8376: .LC_docs_cut {
1.545     albertel 8377:   color: #550044;
1.544     albertel 8378: }
1.795     www      8379: 
1.544     albertel 8380: .LC_docs_rename {
1.545     albertel 8381:   color: #009900;
1.544     albertel 8382: }
1.795     www      8383: 
1.544     albertel 8384: .LC_docs_remove {
1.545     albertel 8385:   color: #990000;
                   8386: }
                   8387: 
1.1284    raeburn  8388: .LC_docs_alias {
                   8389:   color: #440055;  
                   8390: }
                   8391: 
1.1286    raeburn  8392: .LC_domprefs_email,
1.1284    raeburn  8393: .LC_docs_alias_name,
1.547     albertel 8394: .LC_docs_reinit_warn,
                   8395: .LC_docs_ext_edit {
                   8396:   font-size: x-small;
                   8397: }
                   8398: 
1.545     albertel 8399: table.LC_docs_adddocs td,
                   8400: table.LC_docs_adddocs th {
                   8401:   border: 1px solid #BBBBBB;
                   8402:   padding: 4px;
                   8403:   background: #DDDDDD;
1.543     albertel 8404: }
                   8405: 
1.584     albertel 8406: table.LC_sty_begin {
                   8407:   background: #BBFFBB;
                   8408: }
1.795     www      8409: 
1.584     albertel 8410: table.LC_sty_end {
                   8411:   background: #FFBBBB;
                   8412: }
                   8413: 
1.589     raeburn  8414: table.LC_double_column {
1.803     bisitz   8415:   border-width: 0;
1.589     raeburn  8416:   border-collapse: collapse;
                   8417:   width: 100%;
                   8418:   padding: 2px;
                   8419: }
                   8420: 
                   8421: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  8422:   top: 2px;
1.589     raeburn  8423:   left: 2px;
                   8424:   width: 47%;
                   8425:   vertical-align: top;
                   8426: }
                   8427: 
                   8428: table.LC_double_column tr td.LC_right_col {
                   8429:   top: 2px;
1.779     bisitz   8430:   right: 2px;
1.589     raeburn  8431:   width: 47%;
                   8432:   vertical-align: top;
                   8433: }
                   8434: 
1.591     raeburn  8435: div.LC_left_float {
                   8436:   float: left;
                   8437:   padding-right: 5%;
1.597     albertel 8438:   padding-bottom: 4px;
1.591     raeburn  8439: }
                   8440: 
                   8441: div.LC_clear_float_header {
1.597     albertel 8442:   padding-bottom: 2px;
1.591     raeburn  8443: }
                   8444: 
                   8445: div.LC_clear_float_footer {
1.597     albertel 8446:   padding-top: 10px;
1.591     raeburn  8447:   clear: both;
                   8448: }
                   8449: 
1.597     albertel 8450: div.LC_grade_show_user {
1.941     bisitz   8451: /*  border-left: 5px solid $sidebg; */
                   8452:   border-top: 5px solid #000000;
                   8453:   margin: 50px 0 0 0;
1.936     bisitz   8454:   padding: 15px 0 5px 10px;
1.597     albertel 8455: }
1.795     www      8456: 
1.936     bisitz   8457: div.LC_grade_show_user_odd_row {
1.941     bisitz   8458: /*  border-left: 5px solid #000000; */
                   8459: }
                   8460: 
                   8461: div.LC_grade_show_user div.LC_Box {
                   8462:   margin-right: 50px;
1.597     albertel 8463: }
                   8464: 
                   8465: div.LC_grade_submissions,
                   8466: div.LC_grade_message_center,
1.936     bisitz   8467: div.LC_grade_info_links {
1.597     albertel 8468:   margin: 5px;
                   8469:   width: 99%;
                   8470:   background: #FFFFFF;
                   8471: }
1.795     www      8472: 
1.597     albertel 8473: div.LC_grade_submissions_header,
1.936     bisitz   8474: div.LC_grade_message_center_header {
1.705     tempelho 8475:   font-weight: bold;
                   8476:   font-size: large;
1.597     albertel 8477: }
1.795     www      8478: 
1.597     albertel 8479: div.LC_grade_submissions_body,
1.936     bisitz   8480: div.LC_grade_message_center_body {
1.597     albertel 8481:   border: 1px solid black;
                   8482:   width: 99%;
                   8483:   background: #FFFFFF;
                   8484: }
1.795     www      8485: 
1.613     albertel 8486: table.LC_scantron_action {
                   8487:   width: 100%;
                   8488: }
1.795     www      8489: 
1.613     albertel 8490: table.LC_scantron_action tr th {
1.698     harmsja  8491:   font-weight:bold;
                   8492:   font-style:normal;
1.613     albertel 8493: }
1.795     www      8494: 
1.779     bisitz   8495: .LC_edit_problem_header,
1.614     albertel 8496: div.LC_edit_problem_footer {
1.705     tempelho 8497:   font-weight: normal;
                   8498:   font-size:  medium;
1.602     albertel 8499:   margin: 2px;
1.1060    bisitz   8500:   background-color: $sidebg;
1.600     albertel 8501: }
1.795     www      8502: 
1.600     albertel 8503: div.LC_edit_problem_header,
1.602     albertel 8504: div.LC_edit_problem_header div,
1.614     albertel 8505: div.LC_edit_problem_footer,
                   8506: div.LC_edit_problem_footer div,
1.602     albertel 8507: div.LC_edit_problem_editxml_header,
                   8508: div.LC_edit_problem_editxml_header div {
1.1205    golterma 8509:   z-index: 100;
1.600     albertel 8510: }
1.795     www      8511: 
1.600     albertel 8512: div.LC_edit_problem_header_title {
1.705     tempelho 8513:   font-weight: bold;
                   8514:   font-size: larger;
1.602     albertel 8515:   background: $tabbg;
                   8516:   padding: 3px;
1.1060    bisitz   8517:   margin: 0 0 5px 0;
1.602     albertel 8518: }
1.795     www      8519: 
1.602     albertel 8520: table.LC_edit_problem_header_title {
                   8521:   width: 100%;
1.600     albertel 8522:   background: $tabbg;
1.602     albertel 8523: }
                   8524: 
1.1205    golterma 8525: div.LC_edit_actionbar {
                   8526:     background-color: $sidebg;
1.1218    droeschl 8527:     margin: 0;
                   8528:     padding: 0;
                   8529:     line-height: 200%;
1.602     albertel 8530: }
1.795     www      8531: 
1.1218    droeschl 8532: div.LC_edit_actionbar div{
                   8533:     padding: 0;
                   8534:     margin: 0;
                   8535:     display: inline-block;
1.600     albertel 8536: }
1.795     www      8537: 
1.1124    bisitz   8538: .LC_edit_opt {
                   8539:   padding-left: 1em;
                   8540:   white-space: nowrap;
                   8541: }
                   8542: 
1.1152    golterma 8543: .LC_edit_problem_latexhelper{
                   8544:     text-align: right;
                   8545: }
                   8546: 
                   8547: #LC_edit_problem_colorful div{
                   8548:     margin-left: 40px;
                   8549: }
                   8550: 
1.1205    golterma 8551: #LC_edit_problem_codemirror div{
                   8552:     margin-left: 0px;
                   8553: }
                   8554: 
1.911     bisitz   8555: img.stift {
1.803     bisitz   8556:   border-width: 0;
                   8557:   vertical-align: middle;
1.677     riegler  8558: }
1.680     riegler  8559: 
1.923     bisitz   8560: table td.LC_mainmenu_col_fieldset {
1.680     riegler  8561:   vertical-align: top;
1.777     tempelho 8562: }
1.795     www      8563: 
1.716     raeburn  8564: div.LC_createcourse {
1.911     bisitz   8565:   margin: 10px 10px 10px 10px;
1.716     raeburn  8566: }
                   8567: 
1.917     raeburn  8568: .LC_dccid {
1.1130    raeburn  8569:   float: right;
1.917     raeburn  8570:   margin: 0.2em 0 0 0;
                   8571:   padding: 0;
                   8572:   font-size: 90%;
                   8573:   display:none;
                   8574: }
                   8575: 
1.897     wenzelju 8576: ol.LC_primary_menu a:hover,
1.721     harmsja  8577: ol#LC_MenuBreadcrumbs a:hover,
                   8578: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 8579: ul#LC_secondary_menu a:hover,
1.721     harmsja  8580: .LC_FormSectionClearButton input:hover
1.795     www      8581: ul.LC_TabContent   li:hover a {
1.952     onken    8582:   color:$button_hover;
1.911     bisitz   8583:   text-decoration:none;
1.693     droeschl 8584: }
                   8585: 
1.779     bisitz   8586: h1 {
1.911     bisitz   8587:   padding: 0;
                   8588:   line-height:130%;
1.693     droeschl 8589: }
1.698     harmsja  8590: 
1.911     bisitz   8591: h2,
                   8592: h3,
                   8593: h4,
                   8594: h5,
                   8595: h6 {
                   8596:   margin: 5px 0 5px 0;
                   8597:   padding: 0;
                   8598:   line-height:130%;
1.693     droeschl 8599: }
1.795     www      8600: 
                   8601: .LC_hcell {
1.911     bisitz   8602:   padding:3px 15px 3px 15px;
                   8603:   margin: 0;
                   8604:   background-color:$tabbg;
                   8605:   color:$fontmenu;
                   8606:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8607: }
1.795     www      8608: 
1.840     bisitz   8609: .LC_Box > .LC_hcell {
1.911     bisitz   8610:   margin: 0 -10px 10px -10px;
1.835     bisitz   8611: }
                   8612: 
1.721     harmsja  8613: .LC_noBorder {
1.911     bisitz   8614:   border: 0;
1.698     harmsja  8615: }
1.693     droeschl 8616: 
1.721     harmsja  8617: .LC_FormSectionClearButton input {
1.911     bisitz   8618:   background-color:transparent;
                   8619:   border: none;
                   8620:   cursor:pointer;
                   8621:   text-decoration:underline;
1.693     droeschl 8622: }
1.763     bisitz   8623: 
                   8624: .LC_help_open_topic {
1.911     bisitz   8625:   color: #FFFFFF;
                   8626:   background-color: #EEEEFF;
                   8627:   margin: 1px;
                   8628:   padding: 4px;
                   8629:   border: 1px solid #000033;
                   8630:   white-space: nowrap;
                   8631:   /* vertical-align: middle; */
1.759     neumanie 8632: }
1.693     droeschl 8633: 
1.911     bisitz   8634: dl,
                   8635: ul,
                   8636: div,
                   8637: fieldset {
                   8638:   margin: 10px 10px 10px 0;
                   8639:   /* overflow: hidden; */
1.693     droeschl 8640: }
1.795     www      8641: 
1.1404    raeburn  8642: fieldset#LC_selectuser {
                   8643:     margin: 0;
                   8644:     padding: 0;
                   8645: }
                   8646: 
1.1211    raeburn  8647: article.geogebraweb div {
                   8648:     margin: 0;
                   8649: }
                   8650: 
1.838     bisitz   8651: fieldset > legend {
1.911     bisitz   8652:   font-weight: bold;
                   8653:   padding: 0 5px 0 5px;
1.838     bisitz   8654: }
                   8655: 
1.813     bisitz   8656: #LC_nav_bar {
1.911     bisitz   8657:   float: left;
1.995     raeburn  8658:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8659:   margin: 0 0 2px 0;
1.807     droeschl 8660: }
                   8661: 
1.916     droeschl 8662: #LC_realm {
                   8663:   margin: 0.2em 0 0 0;
                   8664:   padding: 0;
                   8665:   font-weight: bold;
                   8666:   text-align: center;
1.995     raeburn  8667:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8668: }
                   8669: 
1.911     bisitz   8670: #LC_nav_bar em {
                   8671:   font-weight: bold;
                   8672:   font-style: normal;
1.807     droeschl 8673: }
                   8674: 
1.897     wenzelju 8675: ol.LC_primary_menu {
1.934     droeschl 8676:   margin: 0;
1.1076    raeburn  8677:   padding: 0;
1.807     droeschl 8678: }
                   8679: 
1.852     droeschl 8680: ol#LC_PathBreadcrumbs {
1.911     bisitz   8681:   margin: 0;
1.693     droeschl 8682: }
                   8683: 
1.897     wenzelju 8684: ol.LC_primary_menu li {
1.1076    raeburn  8685:   color: RGB(80, 80, 80);
                   8686:   vertical-align: middle;
                   8687:   text-align: left;
                   8688:   list-style: none;
1.1205    golterma 8689:   position: relative;
1.1076    raeburn  8690:   float: left;
1.1205    golterma 8691:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8692:   line-height: 1.5em;
1.1076    raeburn  8693: }
                   8694: 
1.1205    golterma 8695: ol.LC_primary_menu li a,
                   8696: ol.LC_primary_menu li p {
1.1076    raeburn  8697:   display: block;
                   8698:   margin: 0;
                   8699:   padding: 0 5px 0 10px;
                   8700:   text-decoration: none;
                   8701: }
                   8702: 
1.1205    golterma 8703: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8704:   display: inline-block;
                   8705:   width: 95%;
                   8706:   text-align: left;
                   8707: }
                   8708: 
                   8709: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8710:   display: inline-block;	
                   8711:   width: 5%;
                   8712:   float: right;
                   8713:   text-align: right;
                   8714:   font-size: 70%;
                   8715: }
                   8716: 
                   8717: ol.LC_primary_menu ul {
1.1076    raeburn  8718:   display: none;
1.1205    golterma 8719:   width: 15em;
1.1076    raeburn  8720:   background-color: $data_table_light;
1.1205    golterma 8721:   position: absolute;
                   8722:   top: 100%;
1.1076    raeburn  8723: }
                   8724: 
1.1205    golterma 8725: ol.LC_primary_menu ul ul {
                   8726:   left: 100%;
                   8727:   top: 0;
                   8728: }
                   8729: 
                   8730: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8731:   display: block;
                   8732:   position: absolute;
                   8733:   margin: 0;
                   8734:   padding: 0;
1.1078    raeburn  8735:   z-index: 2;
1.1076    raeburn  8736: }
                   8737: 
                   8738: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8739: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8740:   font-size: 90%;
1.911     bisitz   8741:   vertical-align: top;
1.1076    raeburn  8742:   float: none;
1.1079    raeburn  8743:   border-left: 1px solid black;
                   8744:   border-right: 1px solid black;
1.1205    golterma 8745: /* A dark bottom border to visualize different menu options; 
                   8746: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8747:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8748: }
                   8749: 
1.1205    golterma 8750: ol.LC_primary_menu li li p:hover {
                   8751:   color:$button_hover;
                   8752:   text-decoration:none;
                   8753:   background-color:$data_table_dark;
1.1076    raeburn  8754: }
                   8755: 
                   8756: ol.LC_primary_menu li li a:hover {
                   8757:    color:$button_hover;
                   8758:    background-color:$data_table_dark;
1.693     droeschl 8759: }
                   8760: 
1.1205    golterma 8761: /* Font-size equal to the size of the predecessors*/
                   8762: ol.LC_primary_menu li:hover li li {
                   8763:   font-size: 100%;
                   8764: }
                   8765: 
1.897     wenzelju 8766: ol.LC_primary_menu li img {
1.911     bisitz   8767:   vertical-align: bottom;
1.934     droeschl 8768:   height: 1.1em;
1.1077    raeburn  8769:   margin: 0.2em 0 0 0;
1.693     droeschl 8770: }
                   8771: 
1.897     wenzelju 8772: ol.LC_primary_menu a {
1.911     bisitz   8773:   color: RGB(80, 80, 80);
                   8774:   text-decoration: none;
1.693     droeschl 8775: }
1.795     www      8776: 
1.949     droeschl 8777: ol.LC_primary_menu a.LC_new_message {
                   8778:   font-weight:bold;
                   8779:   color: darkred;
                   8780: }
                   8781: 
1.975     raeburn  8782: ol.LC_docs_parameters {
                   8783:   margin-left: 0;
                   8784:   padding: 0;
                   8785:   list-style: none;
                   8786: }
                   8787: 
                   8788: ol.LC_docs_parameters li {
                   8789:   margin: 0;
                   8790:   padding-right: 20px;
                   8791:   display: inline;
                   8792: }
                   8793: 
1.976     raeburn  8794: ol.LC_docs_parameters li:before {
                   8795:   content: "\\002022 \\0020";
                   8796: }
                   8797: 
                   8798: li.LC_docs_parameters_title {
                   8799:   font-weight: bold;
                   8800: }
                   8801: 
                   8802: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8803:   content: "";
                   8804: }
                   8805: 
1.897     wenzelju 8806: ul#LC_secondary_menu {
1.1107    raeburn  8807:   clear: right;
1.911     bisitz   8808:   color: $fontmenu;
                   8809:   background: $tabbg;
                   8810:   list-style: none;
                   8811:   padding: 0;
                   8812:   margin: 0;
                   8813:   width: 100%;
1.995     raeburn  8814:   text-align: left;
1.1107    raeburn  8815:   float: left;
1.808     droeschl 8816: }
                   8817: 
1.897     wenzelju 8818: ul#LC_secondary_menu li {
1.911     bisitz   8819:   font-weight: bold;
                   8820:   line-height: 1.8em;
1.1107    raeburn  8821:   border-right: 1px solid black;
                   8822:   float: left;
                   8823: }
                   8824: 
                   8825: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8826:   background-color: $data_table_light;
                   8827: }
                   8828: 
                   8829: ul#LC_secondary_menu li a {
1.911     bisitz   8830:   padding: 0 0.8em;
1.1107    raeburn  8831: }
                   8832: 
                   8833: ul#LC_secondary_menu li ul {
                   8834:   display: none;
                   8835: }
                   8836: 
                   8837: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8838:   display: block;
                   8839:   position: absolute;
                   8840:   margin: 0;
                   8841:   padding: 0;
                   8842:   list-style:none;
                   8843:   float: none;
                   8844:   background-color: $data_table_light;
                   8845:   z-index: 2;
                   8846:   margin-left: -1px;
                   8847: }
                   8848: 
                   8849: ul#LC_secondary_menu li ul li {
                   8850:   font-size: 90%;
                   8851:   vertical-align: top;
                   8852:   border-left: 1px solid black;
1.911     bisitz   8853:   border-right: 1px solid black;
1.1119    raeburn  8854:   background-color: $data_table_light;
1.1107    raeburn  8855:   list-style:none;
                   8856:   float: none;
                   8857: }
                   8858: 
                   8859: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8860:   background-color: $data_table_dark;
1.807     droeschl 8861: }
                   8862: 
1.847     tempelho 8863: ul.LC_TabContent {
1.911     bisitz   8864:   display:block;
                   8865:   background: $sidebg;
                   8866:   border-bottom: solid 1px $lg_border_color;
                   8867:   list-style:none;
1.1020    raeburn  8868:   margin: -1px -10px 0 -10px;
1.911     bisitz   8869:   padding: 0;
1.693     droeschl 8870: }
                   8871: 
1.795     www      8872: ul.LC_TabContent li,
                   8873: ul.LC_TabContentBigger li {
1.911     bisitz   8874:   float:left;
1.741     harmsja  8875: }
1.795     www      8876: 
1.897     wenzelju 8877: ul#LC_secondary_menu li a {
1.911     bisitz   8878:   color: $fontmenu;
                   8879:   text-decoration: none;
1.693     droeschl 8880: }
1.795     www      8881: 
1.721     harmsja  8882: ul.LC_TabContent {
1.952     onken    8883:   min-height:20px;
1.721     harmsja  8884: }
1.795     www      8885: 
                   8886: ul.LC_TabContent li {
1.911     bisitz   8887:   vertical-align:middle;
1.959     onken    8888:   padding: 0 16px 0 10px;
1.911     bisitz   8889:   background-color:$tabbg;
                   8890:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8891:   border-left: solid 1px $font;
1.721     harmsja  8892: }
1.795     www      8893: 
1.847     tempelho 8894: ul.LC_TabContent .right {
1.911     bisitz   8895:   float:right;
1.847     tempelho 8896: }
                   8897: 
1.911     bisitz   8898: ul.LC_TabContent li a,
                   8899: ul.LC_TabContent li {
                   8900:   color:rgb(47,47,47);
                   8901:   text-decoration:none;
                   8902:   font-size:95%;
                   8903:   font-weight:bold;
1.952     onken    8904:   min-height:20px;
                   8905: }
                   8906: 
1.959     onken    8907: ul.LC_TabContent li a:hover,
                   8908: ul.LC_TabContent li a:focus {
1.952     onken    8909:   color: $button_hover;
1.959     onken    8910:   background:none;
                   8911:   outline:none;
1.952     onken    8912: }
                   8913: 
                   8914: ul.LC_TabContent li:hover {
                   8915:   color: $button_hover;
                   8916:   cursor:pointer;
1.721     harmsja  8917: }
1.795     www      8918: 
1.911     bisitz   8919: ul.LC_TabContent li.active {
1.952     onken    8920:   color: $font;
1.911     bisitz   8921:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8922:   border-bottom:solid 1px #FFFFFF;
                   8923:   cursor: default;
1.744     ehlerst  8924: }
1.795     www      8925: 
1.959     onken    8926: ul.LC_TabContent li.active a {
                   8927:   color:$font;
                   8928:   background:#FFFFFF;
                   8929:   outline: none;
                   8930: }
1.1047    raeburn  8931: 
                   8932: ul.LC_TabContent li.goback {
                   8933:   float: left;
                   8934:   border-left: none;
                   8935: }
                   8936: 
1.870     tempelho 8937: #maincoursedoc {
1.911     bisitz   8938:   clear:both;
1.870     tempelho 8939: }
                   8940: 
                   8941: ul.LC_TabContentBigger {
1.911     bisitz   8942:   display:block;
                   8943:   list-style:none;
                   8944:   padding: 0;
1.870     tempelho 8945: }
                   8946: 
1.795     www      8947: ul.LC_TabContentBigger li {
1.911     bisitz   8948:   vertical-align:bottom;
                   8949:   height: 30px;
                   8950:   font-size:110%;
                   8951:   font-weight:bold;
                   8952:   color: #737373;
1.841     tempelho 8953: }
                   8954: 
1.957     onken    8955: ul.LC_TabContentBigger li.active {
                   8956:   position: relative;
                   8957:   top: 1px;
                   8958: }
                   8959: 
1.870     tempelho 8960: ul.LC_TabContentBigger li a {
1.911     bisitz   8961:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8962:   height: 30px;
                   8963:   line-height: 30px;
                   8964:   text-align: center;
                   8965:   display: block;
                   8966:   text-decoration: none;
1.958     onken    8967:   outline: none;  
1.741     harmsja  8968: }
1.795     www      8969: 
1.870     tempelho 8970: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8971:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8972:   color:$font;
1.744     ehlerst  8973: }
1.795     www      8974: 
1.870     tempelho 8975: ul.LC_TabContentBigger li b {
1.911     bisitz   8976:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8977:   display: block;
                   8978:   float: left;
                   8979:   padding: 0 30px;
1.957     onken    8980:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8981: }
                   8982: 
1.956     onken    8983: ul.LC_TabContentBigger li:hover b {
                   8984:   color:$button_hover;
                   8985: }
                   8986: 
1.870     tempelho 8987: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8988:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8989:   color:$font;
1.957     onken    8990:   border: 0;
1.741     harmsja  8991: }
1.693     droeschl 8992: 
1.870     tempelho 8993: 
1.862     bisitz   8994: ul.LC_CourseBreadcrumbs {
                   8995:   background: $sidebg;
1.1020    raeburn  8996:   height: 2em;
1.862     bisitz   8997:   padding-left: 10px;
1.1020    raeburn  8998:   margin: 0;
1.862     bisitz   8999:   list-style-position: inside;
                   9000: }
                   9001: 
1.911     bisitz   9002: ol#LC_MenuBreadcrumbs,
1.862     bisitz   9003: ol#LC_PathBreadcrumbs {
1.911     bisitz   9004:   padding-left: 10px;
                   9005:   margin: 0;
1.933     droeschl 9006:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 9007: }
                   9008: 
1.911     bisitz   9009: ol#LC_MenuBreadcrumbs li,
                   9010: ol#LC_PathBreadcrumbs li,
1.862     bisitz   9011: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   9012:   display: inline;
1.933     droeschl 9013:   white-space: normal;  
1.693     droeschl 9014: }
                   9015: 
1.823     bisitz   9016: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   9017: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   9018:   text-decoration: none;
                   9019:   font-size:90%;
1.693     droeschl 9020: }
1.795     www      9021: 
1.969     droeschl 9022: ol#LC_MenuBreadcrumbs h1 {
                   9023:   display: inline;
                   9024:   font-size: 90%;
                   9025:   line-height: 2.5em;
                   9026:   margin: 0;
                   9027:   padding: 0;
                   9028: }
                   9029: 
1.795     www      9030: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   9031:   text-decoration:none;
                   9032:   font-size:100%;
                   9033:   font-weight:bold;
1.693     droeschl 9034: }
1.795     www      9035: 
1.840     bisitz   9036: .LC_Box {
1.911     bisitz   9037:   border: solid 1px $lg_border_color;
                   9038:   padding: 0 10px 10px 10px;
1.746     neumanie 9039: }
1.795     www      9040: 
1.1020    raeburn  9041: .LC_DocsBox {
                   9042:   border: solid 1px $lg_border_color;
                   9043:   padding: 0 0 10px 10px;
                   9044: }
                   9045: 
1.795     www      9046: .LC_AboutMe_Image {
1.911     bisitz   9047:   float:left;
                   9048:   margin-right:10px;
1.747     neumanie 9049: }
1.795     www      9050: 
                   9051: .LC_Clear_AboutMe_Image {
1.911     bisitz   9052:   clear:left;
1.747     neumanie 9053: }
1.795     www      9054: 
1.721     harmsja  9055: dl.LC_ListStyleClean dt {
1.911     bisitz   9056:   padding-right: 5px;
                   9057:   display: table-header-group;
1.693     droeschl 9058: }
                   9059: 
1.721     harmsja  9060: dl.LC_ListStyleClean dd {
1.911     bisitz   9061:   display: table-row;
1.693     droeschl 9062: }
                   9063: 
1.721     harmsja  9064: .LC_ListStyleClean,
                   9065: .LC_ListStyleSimple,
                   9066: .LC_ListStyleNormal,
1.795     www      9067: .LC_ListStyleSpecial {
1.911     bisitz   9068:   /* display:block; */
                   9069:   list-style-position: inside;
                   9070:   list-style-type: none;
                   9071:   overflow: hidden;
                   9072:   padding: 0;
1.693     droeschl 9073: }
                   9074: 
1.721     harmsja  9075: .LC_ListStyleSimple li,
                   9076: .LC_ListStyleSimple dd,
                   9077: .LC_ListStyleNormal li,
                   9078: .LC_ListStyleNormal dd,
                   9079: .LC_ListStyleSpecial li,
1.795     www      9080: .LC_ListStyleSpecial dd {
1.911     bisitz   9081:   margin: 0;
                   9082:   padding: 5px 5px 5px 10px;
                   9083:   clear: both;
1.693     droeschl 9084: }
                   9085: 
1.721     harmsja  9086: .LC_ListStyleClean li,
                   9087: .LC_ListStyleClean dd {
1.911     bisitz   9088:   padding-top: 0;
                   9089:   padding-bottom: 0;
1.693     droeschl 9090: }
                   9091: 
1.721     harmsja  9092: .LC_ListStyleSimple dd,
1.795     www      9093: .LC_ListStyleSimple li {
1.911     bisitz   9094:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 9095: }
                   9096: 
1.721     harmsja  9097: .LC_ListStyleSpecial li,
                   9098: .LC_ListStyleSpecial dd {
1.911     bisitz   9099:   list-style-type: none;
                   9100:   background-color: RGB(220, 220, 220);
                   9101:   margin-bottom: 4px;
1.693     droeschl 9102: }
                   9103: 
1.721     harmsja  9104: table.LC_SimpleTable {
1.911     bisitz   9105:   margin:5px;
                   9106:   border:solid 1px $lg_border_color;
1.795     www      9107: }
1.693     droeschl 9108: 
1.721     harmsja  9109: table.LC_SimpleTable tr {
1.911     bisitz   9110:   padding: 0;
                   9111:   border:solid 1px $lg_border_color;
1.693     droeschl 9112: }
1.795     www      9113: 
                   9114: table.LC_SimpleTable thead {
1.911     bisitz   9115:   background:rgb(220,220,220);
1.693     droeschl 9116: }
                   9117: 
1.721     harmsja  9118: div.LC_columnSection {
1.911     bisitz   9119:   display: block;
                   9120:   clear: both;
                   9121:   overflow: hidden;
                   9122:   margin: 0;
1.693     droeschl 9123: }
                   9124: 
1.721     harmsja  9125: div.LC_columnSection>* {
1.911     bisitz   9126:   float: left;
                   9127:   margin: 10px 20px 10px 0;
                   9128:   overflow:hidden;
1.693     droeschl 9129: }
1.721     harmsja  9130: 
1.795     www      9131: table em {
1.911     bisitz   9132:   font-weight: bold;
                   9133:   font-style: normal;
1.748     schulted 9134: }
1.795     www      9135: 
1.779     bisitz   9136: table.LC_tableBrowseRes,
1.795     www      9137: table.LC_tableOfContent {
1.911     bisitz   9138:   border:none;
                   9139:   border-spacing: 1px;
                   9140:   padding: 3px;
                   9141:   background-color: #FFFFFF;
                   9142:   font-size: 90%;
1.753     droeschl 9143: }
1.789     droeschl 9144: 
1.911     bisitz   9145: table.LC_tableOfContent {
                   9146:   border-collapse: collapse;
1.789     droeschl 9147: }
                   9148: 
1.771     droeschl 9149: table.LC_tableBrowseRes a,
1.768     schulted 9150: table.LC_tableOfContent a {
1.911     bisitz   9151:   background-color: transparent;
                   9152:   text-decoration: none;
1.753     droeschl 9153: }
                   9154: 
1.795     www      9155: table.LC_tableOfContent img {
1.911     bisitz   9156:   border: none;
                   9157:   height: 1.3em;
                   9158:   vertical-align: text-bottom;
                   9159:   margin-right: 0.3em;
1.753     droeschl 9160: }
1.757     schulted 9161: 
1.795     www      9162: a#LC_content_toolbar_firsthomework {
1.911     bisitz   9163:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  9164: }
                   9165: 
1.795     www      9166: a#LC_content_toolbar_everything {
1.911     bisitz   9167:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  9168: }
                   9169: 
1.795     www      9170: a#LC_content_toolbar_uncompleted {
1.911     bisitz   9171:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  9172: }
                   9173: 
1.795     www      9174: #LC_content_toolbar_clearbubbles {
1.911     bisitz   9175:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  9176: }
                   9177: 
1.795     www      9178: a#LC_content_toolbar_changefolder {
1.911     bisitz   9179:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 9180: }
                   9181: 
1.795     www      9182: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   9183:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 9184: }
                   9185: 
1.1043    raeburn  9186: a#LC_content_toolbar_edittoplevel {
                   9187:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   9188: }
                   9189: 
1.1384    raeburn  9190: a#LC_content_toolbar_printout {
                   9191:   background-image:url(/res/adm/pages/printout.gif);
                   9192: }
                   9193: 
1.795     www      9194: ul#LC_toolbar li a:hover {
1.911     bisitz   9195:   background-position: bottom center;
1.757     schulted 9196: }
                   9197: 
1.795     www      9198: ul#LC_toolbar {
1.911     bisitz   9199:   padding: 0;
                   9200:   margin: 2px;
                   9201:   list-style:none;
1.1449    raeburn  9202:   display:inline;
1.911     bisitz   9203:   background-color:white;
1.1082    raeburn  9204:   overflow: auto;
1.757     schulted 9205: }
                   9206: 
1.795     www      9207: ul#LC_toolbar li {
1.911     bisitz   9208:   border:1px solid white;
                   9209:   padding: 0;
                   9210:   margin: 0;
                   9211:   float: left;
                   9212:   display:inline;
                   9213:   vertical-align:middle;
1.1082    raeburn  9214:   white-space: nowrap;
1.911     bisitz   9215: }
1.757     schulted 9216: 
1.783     amueller 9217: 
1.795     www      9218: a.LC_toolbarItem {
1.911     bisitz   9219:   display:block;
                   9220:   padding: 0;
                   9221:   margin: 0;
                   9222:   height: 32px;
                   9223:   width: 32px;
                   9224:   color:white;
                   9225:   border: none;
                   9226:   background-repeat:no-repeat;
                   9227:   background-color:transparent;
1.757     schulted 9228: }
                   9229: 
1.1449    raeburn  9230: .LC_navtools {
                   9231:   display: inline-block;
                   9232:   padding: 0;
                   9233:   margin: 2px;
                   9234:   vertical-align: middle;
                   9235: }
                   9236: 
1.915     droeschl 9237: ul.LC_funclist {
                   9238:     margin: 0;
                   9239:     padding: 0.5em 1em 0.5em 0;
                   9240: }
                   9241: 
1.933     droeschl 9242: ul.LC_funclist > li:first-child {
                   9243:     font-weight:bold; 
                   9244:     margin-left:0.8em;
                   9245: }
                   9246: 
1.915     droeschl 9247: ul.LC_funclist + ul.LC_funclist {
                   9248:     /* 
                   9249:        left border as a seperator if we have more than
                   9250:        one list 
                   9251:     */
                   9252:     border-left: 1px solid $sidebg;
                   9253:     /* 
                   9254:        this hides the left border behind the border of the 
                   9255:        outer box if element is wrapped to the next 'line' 
                   9256:     */
                   9257:     margin-left: -1px;
                   9258: }
                   9259: 
1.843     bisitz   9260: ul.LC_funclist li {
1.915     droeschl 9261:   display: inline;
1.782     bisitz   9262:   white-space: nowrap;
1.915     droeschl 9263:   margin: 0 0 0 25px;
                   9264:   line-height: 150%;
1.782     bisitz   9265: }
                   9266: 
1.974     wenzelju 9267: .LC_hidden {
                   9268:   display: none;
                   9269: }
                   9270: 
1.1030    www      9271: .LCmodal-overlay {
                   9272: 		position:fixed;
                   9273: 		top:0;
                   9274: 		right:0;
                   9275: 		bottom:0;
                   9276: 		left:0;
                   9277: 		height:100%;
                   9278: 		width:100%;
                   9279: 		margin:0;
                   9280: 		padding:0;
                   9281: 		background:#999;
                   9282: 		opacity:.75;
                   9283: 		filter: alpha(opacity=75);
                   9284: 		-moz-opacity: 0.75;
                   9285: 		z-index:101;
                   9286: }
                   9287: 
                   9288: * html .LCmodal-overlay {   
                   9289: 		position: absolute;
                   9290: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   9291: }
                   9292: 
                   9293: .LCmodal-window {
                   9294: 		position:fixed;
                   9295: 		top:50%;
                   9296: 		left:50%;
                   9297: 		margin:0;
                   9298: 		padding:0;
                   9299: 		z-index:102;
                   9300: 	}
                   9301: 
                   9302: * html .LCmodal-window {
                   9303: 		position:absolute;
                   9304: }
                   9305: 
                   9306: .LCclose-window {
                   9307: 		position:absolute;
                   9308: 		width:32px;
                   9309: 		height:32px;
                   9310: 		right:8px;
                   9311: 		top:8px;
                   9312: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   9313: 		text-indent:-99999px;
                   9314: 		overflow:hidden;
                   9315: 		cursor:pointer;
                   9316: }
                   9317: 
1.1369    raeburn  9318: .LCisDisabled {
                   9319:   cursor: not-allowed;
                   9320:   opacity: 0.5;
                   9321: }
                   9322: 
                   9323: a[aria-disabled="true"] {
                   9324:   color: currentColor;
                   9325:   display: inline-block;  /* For IE11/ MS Edge bug */
                   9326:   pointer-events: none;
                   9327:   text-decoration: none;
                   9328: }
                   9329: 
1.1335    raeburn  9330: pre.LC_wordwrap {
                   9331:   white-space: pre-wrap;
                   9332:   white-space: -moz-pre-wrap;
                   9333:   white-space: -pre-wrap;
                   9334:   white-space: -o-pre-wrap;
                   9335:   word-wrap: break-word;
                   9336: }
                   9337: 
1.1100    raeburn  9338: /*
1.1231    damieng  9339:   styles used for response display
                   9340: */
                   9341: div.LC_radiofoil, div.LC_rankfoil {
                   9342:   margin: .5em 0em .5em 0em;
                   9343: }
                   9344: table.LC_itemgroup {
                   9345:   margin-top: 1em;
                   9346: }
                   9347: 
                   9348: /*
1.1100    raeburn  9349:   styles used by TTH when "Default set of options to pass to tth/m
                   9350:   when converting TeX" in course settings has been set
                   9351: 
                   9352:   option passed: -t
                   9353: 
                   9354: */
                   9355: 
                   9356: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   9357: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   9358: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   9359: td div.norm {line-height:normal;}
                   9360: 
                   9361: /*
                   9362:   option passed -y3
                   9363: */
                   9364: 
                   9365: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   9366: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   9367: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   9368: 
1.1230    damieng  9369: /*
                   9370:   sections with roles, for content only
                   9371: */
                   9372: section[class^="role-"] {
                   9373:   padding-left: 10px;
                   9374:   padding-right: 5px;
                   9375:   margin-top: 8px;
                   9376:   margin-bottom: 8px;
                   9377:   border: 1px solid #2A4;
                   9378:   border-radius: 5px;
                   9379:   box-shadow: 0px 1px 1px #BBB;
                   9380: }
                   9381: section[class^="role-"]>h1 {
                   9382:   position: relative;
                   9383:   margin: 0px;
                   9384:   padding-top: 10px;
                   9385:   padding-left: 40px;
                   9386: }
                   9387: section[class^="role-"]>h1:before {
                   9388:   position: absolute;
                   9389:   left: -5px;
                   9390:   top: 5px;
                   9391: }
                   9392: section.role-activity>h1:before {
                   9393:   content:url('/adm/daxe/images/section_icons/activity.png');
                   9394: }
                   9395: section.role-advice>h1:before {
                   9396:   content:url('/adm/daxe/images/section_icons/advice.png');
                   9397: }
                   9398: section.role-bibliography>h1:before {
                   9399:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   9400: }
                   9401: section.role-citation>h1:before {
                   9402:   content:url('/adm/daxe/images/section_icons/citation.png');
                   9403: }
                   9404: section.role-conclusion>h1:before {
                   9405:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   9406: }
                   9407: section.role-definition>h1:before {
                   9408:   content:url('/adm/daxe/images/section_icons/definition.png');
                   9409: }
                   9410: section.role-demonstration>h1:before {
                   9411:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   9412: }
                   9413: section.role-example>h1:before {
                   9414:   content:url('/adm/daxe/images/section_icons/example.png');
                   9415: }
                   9416: section.role-explanation>h1:before {
                   9417:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   9418: }
                   9419: section.role-introduction>h1:before {
                   9420:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   9421: }
                   9422: section.role-method>h1:before {
                   9423:   content:url('/adm/daxe/images/section_icons/method.png');
                   9424: }
                   9425: section.role-more_information>h1:before {
                   9426:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   9427: }
                   9428: section.role-objectives>h1:before {
                   9429:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   9430: }
                   9431: section.role-prerequisites>h1:before {
                   9432:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   9433: }
                   9434: section.role-remark>h1:before {
                   9435:   content:url('/adm/daxe/images/section_icons/remark.png');
                   9436: }
                   9437: section.role-reminder>h1:before {
                   9438:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   9439: }
                   9440: section.role-summary>h1:before {
                   9441:   content:url('/adm/daxe/images/section_icons/summary.png');
                   9442: }
                   9443: section.role-syntax>h1:before {
                   9444:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   9445: }
                   9446: section.role-warning>h1:before {
                   9447:   content:url('/adm/daxe/images/section_icons/warning.png');
                   9448: }
                   9449: 
1.1269    raeburn  9450: #LC_minitab_header {
                   9451:   float:left;
                   9452:   width:100%;
                   9453:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   9454:   font-size:93%;
                   9455:   line-height:normal;
                   9456:   margin: 0.5em 0 0.5em 0;
                   9457: }
                   9458: #LC_minitab_header ul {
                   9459:   margin:0;
                   9460:   padding:10px 10px 0;
                   9461:   list-style:none;
                   9462: }
                   9463: #LC_minitab_header li {
                   9464:   float:left;
                   9465:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   9466:   margin:0;
                   9467:   padding:0 0 0 9px;
                   9468: }
                   9469: #LC_minitab_header a {
                   9470:   display:block;
                   9471:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   9472:   padding:5px 15px 4px 6px;
                   9473: }
                   9474: #LC_minitab_header #LC_current_minitab {
                   9475:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   9476: }
                   9477: #LC_minitab_header #LC_current_minitab a {
                   9478:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   9479:   padding-bottom:5px;
                   9480: }
                   9481: 
                   9482: 
1.343     albertel 9483: END
                   9484: }
                   9485: 
1.306     albertel 9486: =pod
                   9487: 
                   9488: =item * &headtag()
                   9489: 
                   9490: Returns a uniform footer for LON-CAPA web pages.
                   9491: 
1.307     albertel 9492: Inputs: $title - optional title for the head
                   9493:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 9494:         $args - optional arguments
1.319     albertel 9495:             force_register - if is true call registerurl so the remote is 
                   9496:                              informed
1.415     albertel 9497:             redirect       -> array ref of
                   9498:                                    1- seconds before redirect occurs
                   9499:                                    2- url to redirect to
                   9500:                                    3- whether the side effect should occur
1.315     albertel 9501:                            (side effect of setting 
                   9502:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  9503:                                redirected to)
                   9504:                                    4- whether the redirect target should be
                   9505:                                       the opener of the current (pop-up)
                   9506:                                       window (side effect of setting
                   9507:                                       $env{'internal.head.to_opener'} to
                   9508:                                       1, if true.
1.1388    raeburn  9509:                                    5- whether encrypt check should be skipped
1.352     albertel 9510:             domain         -> force to color decorate a page for a specific
                   9511:                                domain
                   9512:             function       -> force usage of a specific rolish color scheme
                   9513:             bgcolor        -> override the default page bgcolor
1.460     albertel 9514:             no_auto_mt_title
                   9515:                            -> prevent &mt()ing the title arg
1.464     albertel 9516: 
1.306     albertel 9517: =cut
                   9518: 
                   9519: sub headtag {
1.313     albertel 9520:     my ($title,$head_extra,$args) = @_;
1.306     albertel 9521:     
1.363     albertel 9522:     my $function = $args->{'function'} || &get_users_function();
                   9523:     my $domain   = $args->{'domain'}   || &determinedomain();
                   9524:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  9525:     my $httphost = $args->{'use_absolute'};
1.418     albertel 9526:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 9527: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 9528: 		   #time(),
1.418     albertel 9529: 		   $env{'environment.color.timestamp'},
1.363     albertel 9530: 		   $function,$domain,$bgcolor);
                   9531: 
1.369     www      9532:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 9533: 
1.308     albertel 9534:     my $result =
                   9535: 	'<head>'.
1.1160    raeburn  9536: 	&font_settings($args);
1.319     albertel 9537: 
1.1188    raeburn  9538:     my $inhibitprint;
                   9539:     if ($args->{'print_suppress'}) {
                   9540:         $inhibitprint = &print_suppression();
                   9541:     }
1.1064    raeburn  9542: 
1.1439    raeburn  9543:     if (!$args->{'frameset'} && !$args->{'switchserver'}) {
1.461     albertel 9544: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   9545:     }
1.962     droeschl 9546:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   9547:         $result .= Apache::lonxml::display_title();
1.319     albertel 9548:     }
1.436     albertel 9549:     if (!$args->{'no_nav_bar'} 
                   9550: 	&& !$args->{'only_body'}
1.1438    raeburn  9551: 	&& !$args->{'frameset'}
                   9552: 	&& !$args->{'switchserver'}) {
1.1154    raeburn  9553: 	$result .= &help_menu_js($httphost);
1.1032    www      9554:         $result.=&modal_window();
1.1038    www      9555:         $result.=&togglebox_script();
1.1034    www      9556:         $result.=&wishlist_window();
1.1041    www      9557:         $result.=&LCprogressbarUpdate_script();
1.1034    www      9558:     } else {
                   9559:         if ($args->{'add_modal'}) {
                   9560:            $result.=&modal_window();
                   9561:         }
                   9562:         if ($args->{'add_wishlist'}) {
                   9563:            $result.=&wishlist_window();
                   9564:         }
1.1038    www      9565:         if ($args->{'add_togglebox'}) {
                   9566:            $result.=&togglebox_script();
                   9567:         }
1.1041    www      9568:         if ($args->{'add_progressbar'}) {
                   9569:            $result.=&LCprogressbarUpdate_script();
                   9570:         }
1.436     albertel 9571:     }
1.314     albertel 9572:     if (ref($args->{'redirect'})) {
1.1388    raeburn  9573: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   9574:         if (!$skip_enc_check) {
                   9575:             $url = &Apache::lonenc::check_encrypt($url);
                   9576:         }
1.414     albertel 9577: 	if (!$inhibit_continue) {
                   9578: 	    $env{'internal.head.redirect'} = $url;
                   9579: 	}
1.1386    raeburn  9580: 	$result.=<<"ADDMETA";
1.313     albertel 9581: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  9582: ADDMETA
                   9583:         if ($to_opener) {
                   9584:             $env{'internal.head.to_opener'} = 1;
                   9585:             my $dest = &js_escape($url);
                   9586:             my $timeout = int($time * 1000);
                   9587:             $result .=<<"ENDJS";
                   9588: <script type="text/javascript">
                   9589: // <![CDATA[
                   9590: function LC_To_Opener() {
                   9591:     var dest = '$dest';
                   9592:     if (dest != '') {
                   9593:         if (window.opener != null && !window.opener.closed) {
                   9594:             window.opener.location.href=dest;
                   9595:             window.close();
                   9596:         } else {
                   9597:             window.location.href=dest;
                   9598:         }
                   9599:     }
                   9600: }
                   9601: \$(document).ready(function () {
                   9602:     setTimeout('LC_To_Opener()',$timeout);
                   9603: });
                   9604: // ]]>
                   9605: </script>
                   9606: ENDJS
                   9607:         } else {
                   9608:             $result.=<<"ADDMETA";
1.344     albertel 9609: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9610: ADDMETA
1.1386    raeburn  9611:         }
1.1210    raeburn  9612:     } else {
                   9613:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9614:             my $requrl = $env{'request.uri'};
                   9615:             if ($requrl eq '') {
                   9616:                 $requrl = $ENV{'REQUEST_URI'};
                   9617:                 $requrl =~ s/\?.+$//;
                   9618:             }
                   9619:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9620:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9621:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9622:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9623:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9624:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9625:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9626:                     my ($offload,$offloadoth);
1.1210    raeburn  9627:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9628:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9629:                             $offload = 1;
1.1353    raeburn  9630:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9631:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9632:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9633:                                     $offloadoth = 1;
                   9634:                                     $dom_in_use = $env{'user.domain'};
                   9635:                                 }
                   9636:                             }
1.1340    raeburn  9637:                         }
                   9638:                     }
                   9639:                     unless ($offload) {
                   9640:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9641:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9642:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9643:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9644:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9645:                                         $offload = 1;
1.1352    raeburn  9646:                                         $offloadoth = 1;
1.1340    raeburn  9647:                                         $dom_in_use = $env{'user.domain'};
                   9648:                                     }
1.1210    raeburn  9649:                                 }
1.1340    raeburn  9650:                             }
                   9651:                         }
                   9652:                     }
                   9653:                     if ($offload) {
1.1358    raeburn  9654:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9655:                         if (($newserver eq '') && ($offloadoth)) {
                   9656:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9657:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9658:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9659:                             }
                   9660:                         }
1.1340    raeburn  9661:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9662:                             my $numsec = 5;
                   9663:                             my $timeout = $numsec * 1000;
                   9664:                             my ($newurl,$locknum,%locks,$msg);
                   9665:                             if ($env{'request.role.adv'}) {
                   9666:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9667:                             }
                   9668:                             my $disable_submit = 0;
                   9669:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9670:                                 $disable_submit = 1;
                   9671:                             }
                   9672:                             if ($locknum) {
                   9673:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9674:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9675:                                        join(", ",sort(values(%locks)))."\n";
                   9676:                                 if (&show_course()) {
                   9677:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9678:                                 } else {
                   9679:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9680:                                 }
1.1340    raeburn  9681:                             } else {
                   9682:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9683:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9684:                                 }
                   9685:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9686:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9687:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9688:                                     $newurl .= '&role='.$env{'request.role'};
                   9689:                                 }
                   9690:                                 if ($env{'request.symb'}) {
                   9691:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9692:                                     if ($shownsymb =~ m{^/enc/}) {
                   9693:                                         my $reqdmajor = 2;
                   9694:                                         my $reqdminor = 11;
                   9695:                                         my $reqdsubminor = 3;
                   9696:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9697:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9698:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9699:                                         if (($major eq '' && $minor eq '') ||
                   9700:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9701:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9702:                                              ($reqdsubminor > $subminor))))) {
                   9703:                                             undef($shownsymb);
                   9704:                                         }
1.1210    raeburn  9705:                                     }
1.1340    raeburn  9706:                                     if ($shownsymb) {
                   9707:                                         &js_escape(\$shownsymb);
                   9708:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9709:                                     }
1.1340    raeburn  9710:                                 } else {
                   9711:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9712:                                     &js_escape(\$shownurl);
                   9713:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9714:                                 }
1.1340    raeburn  9715:                             }
                   9716:                             &js_escape(\$msg);
                   9717:                             $result.=<<OFFLOAD
1.1210    raeburn  9718: <meta http-equiv="pragma" content="no-cache" />
                   9719: <script type="text/javascript">
1.1215    raeburn  9720: // <![CDATA[
1.1210    raeburn  9721: function LC_Offload_Now() {
                   9722:     var dest = "$newurl";
                   9723:     if (dest != '') {
                   9724:         window.location.href="$newurl";
                   9725:     }
                   9726: }
1.1214    raeburn  9727: \$(document).ready(function () {
                   9728:     window.alert('$msg');
                   9729:     if ($disable_submit) {
1.1210    raeburn  9730:         \$(".LC_hwk_submit").prop("disabled", true);
                   9731:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9732:     }
                   9733:     setTimeout('LC_Offload_Now()', $timeout);
                   9734: });
1.1215    raeburn  9735: // ]]>
1.1210    raeburn  9736: </script>
                   9737: OFFLOAD
                   9738:                         }
                   9739:                     }
                   9740:                 }
                   9741:             }
                   9742:         }
1.313     albertel 9743:     }
1.306     albertel 9744:     if (!defined($title)) {
                   9745: 	$title = 'The LearningOnline Network with CAPA';
                   9746:     }
1.460     albertel 9747:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1432    raeburn  9748:     if ($title =~ /^LON-CAPA\s+/) {
                   9749:         $result .= '<title> '.$title.'</title>';
                   9750:     } else {
                   9751:         $result .= '<title> LON-CAPA '.$title.'</title>';
                   9752:     }
                   9753:     $result .= "\n".'<link rel="stylesheet" type="text/css" href="'.$url.'"';
1.1168    raeburn  9754:     if (!$args->{'frameset'}) {
                   9755:         $result .= ' /';
                   9756:     }
                   9757:     $result .= '>' 
1.1064    raeburn  9758:         .$inhibitprint
1.414     albertel 9759: 	.$head_extra;
1.1242    raeburn  9760:     my $clientmobile;
                   9761:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9762:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9763:     } else {
                   9764:         $clientmobile = $env{'browser.mobile'};
                   9765:     }
                   9766:     if ($clientmobile) {
1.1137    raeburn  9767:         $result .= '
1.1435    raeburn  9768: <meta name="viewport" content="width=device-width, initial-scale=1.0">
1.1137    raeburn  9769: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9770:     }
1.1455    raeburn  9771:     $result .= '<meta name="google" content="notranslate"';
                   9772:     if (!$args->{'frameset'}) {
                   9773:         $result .= ' /';
                   9774:     }
                   9775:     $result .= '>'."\n";
1.962     droeschl 9776:     return $result.'</head>';
1.306     albertel 9777: }
                   9778: 
                   9779: =pod
                   9780: 
1.340     albertel 9781: =item * &font_settings()
                   9782: 
                   9783: Returns neccessary <meta> to set the proper encoding
                   9784: 
1.1160    raeburn  9785: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9786: 
                   9787: =cut
                   9788: 
                   9789: sub font_settings {
1.1160    raeburn  9790:     my ($args) = @_;
1.340     albertel 9791:     my $headerstring='';
1.1160    raeburn  9792:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9793:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9794:         $headerstring.=
                   9795:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9796:         if (!$args->{'frameset'}) {
                   9797: 	    $headerstring.= ' /';
                   9798:         }
                   9799: 	$headerstring .= '>'."\n";
1.340     albertel 9800:     }
                   9801:     return $headerstring;
                   9802: }
                   9803: 
1.341     albertel 9804: =pod
                   9805: 
1.1064    raeburn  9806: =item * &print_suppression()
                   9807: 
                   9808: In course context returns css which causes the body to be blank when media="print",
                   9809: if printout generation is unavailable for the current resource.
                   9810: 
                   9811: This could be because:
                   9812: 
                   9813: (a) printstartdate is in the future
                   9814: 
                   9815: (b) printenddate is in the past
                   9816: 
                   9817: (c) there is an active exam block with "printout"
                   9818: functionality blocked
                   9819: 
                   9820: Users with pav, pfo or evb privileges are exempt.
                   9821: 
                   9822: Inputs: none
                   9823: 
                   9824: =cut
                   9825: 
                   9826: 
                   9827: sub print_suppression {
                   9828:     my $noprint;
                   9829:     if ($env{'request.course.id'}) {
                   9830:         my $scope = $env{'request.course.id'};
                   9831:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9832:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9833:             return;
                   9834:         }
                   9835:         if ($env{'request.course.sec'} ne '') {
                   9836:             $scope .= "/$env{'request.course.sec'}";
                   9837:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9838:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9839:                 return;
1.1064    raeburn  9840:             }
                   9841:         }
                   9842:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9843:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9844:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9845:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9846:         if ($blocked) {
                   9847:             my $checkrole = "cm./$cdom/$cnum";
                   9848:             if ($env{'request.course.sec'} ne '') {
                   9849:                 $checkrole .= "/$env{'request.course.sec'}";
                   9850:             }
                   9851:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9852:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9853:                 $noprint = 1;
                   9854:             }
                   9855:         }
                   9856:         unless ($noprint) {
                   9857:             my $symb = &Apache::lonnet::symbread();
                   9858:             if ($symb ne '') {
                   9859:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9860:                 if (ref($navmap)) {
                   9861:                     my $res = $navmap->getBySymb($symb);
                   9862:                     if (ref($res)) {
                   9863:                         if (!$res->resprintable()) {
                   9864:                             $noprint = 1;
                   9865:                         }
                   9866:                     }
                   9867:                 }
                   9868:             }
                   9869:         }
                   9870:         if ($noprint) {
                   9871:             return <<"ENDSTYLE";
                   9872: <style type="text/css" media="print">
                   9873:     body { display:none }
                   9874: </style>
                   9875: ENDSTYLE
                   9876:         }
                   9877:     }
                   9878:     return;
                   9879: }
                   9880: 
                   9881: =pod
                   9882: 
1.341     albertel 9883: =item * &xml_begin()
                   9884: 
                   9885: Returns the needed doctype and <html>
                   9886: 
                   9887: Inputs: none
                   9888: 
                   9889: =cut
                   9890: 
                   9891: sub xml_begin {
1.1168    raeburn  9892:     my ($is_frameset) = @_;
1.341     albertel 9893:     my $output='';
                   9894: 
                   9895:     if ($env{'browser.mathml'}) {
                   9896: 	$output='<?xml version="1.0"?>'
                   9897:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9898: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9899:             
                   9900: #	    .'<!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">] >'
                   9901: 	    .'<!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">'
                   9902:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9903: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9904:     } elsif ($is_frameset) {
                   9905:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9906:                 '<html>'."\n";
1.341     albertel 9907:     } else {
1.1168    raeburn  9908: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9909:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9910:     }
                   9911:     return $output;
                   9912: }
1.340     albertel 9913: 
                   9914: =pod
                   9915: 
1.306     albertel 9916: =item * &start_page()
                   9917: 
                   9918: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9919: 
1.648     raeburn  9920: Inputs:
                   9921: 
                   9922: =over 4
                   9923: 
                   9924: $title - optional title for the page
                   9925: 
                   9926: $head_extra - optional extra HTML to incude inside the <head>
                   9927: 
                   9928: $args - additional optional args supported are:
                   9929: 
                   9930: =over 8
                   9931: 
                   9932:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9933:                                     arg on
1.814     bisitz   9934:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9935:              add_entries    -> additional attributes to add to the  <body>
                   9936:              domain         -> force to color decorate a page for a 
1.317     albertel 9937:                                     specific domain
1.648     raeburn  9938:              function       -> force usage of a specific rolish color
1.317     albertel 9939:                                     scheme
1.648     raeburn  9940:              redirect       -> see &headtag()
                   9941:              bgcolor        -> override the default page bg color
                   9942:              js_ready       -> return a string ready for being used in 
1.317     albertel 9943:                                     a javascript writeln
1.648     raeburn  9944:              html_encode    -> return a string ready for being used in 
1.320     albertel 9945:                                     a html attribute
1.648     raeburn  9946:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9947:                                     $forcereg arg
1.648     raeburn  9948:              frameset       -> if true will start with a <frameset>
1.330     albertel 9949:                                     rather than <body>
1.648     raeburn  9950:              skip_phases    -> hash ref of 
1.338     albertel 9951:                                     head -> skip the <html><head> generation
                   9952:                                     body -> skip all <body> generation
1.648     raeburn  9953:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9954:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9955:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1437    raeburn  9956:              bread_crumbs_style -> breadcrumbs are contained within <div id="LC_breadcrumbs">,
                   9957:                                    and &standard_css() contains CSS for #LC_breadcrumbs, if you want
                   9958:                                    to override those values, or add to them, specify the value to
                   9959:                                    include in the style attribute to include in the div tag by using
                   9960:                                    bread_crumbs_style (e.g., overflow: visible)
1.1272    raeburn  9961:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9962:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9963:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9964:                                specific group
                   9965:              use_absolute   -> for request for external resource or syllabus, this
                   9966:                                will contain https://<hostname> if server uses
                   9967:                                https (as per hosts.tab), but request is for http
                   9968:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9969:              links_disabled -> Links in primary and secondary menus are disabled
                   9970:                                (Can enable them once page has loaded - see lonroles.pm
                   9971:                                for an example).
1.1380    raeburn  9972:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9973: 
1.648     raeburn  9974: =back
1.460     albertel 9975: 
1.648     raeburn  9976: =back
1.562     albertel 9977: 
1.306     albertel 9978: =cut
                   9979: 
                   9980: sub start_page {
1.309     albertel 9981:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9982:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9983: 
1.315     albertel 9984:     $env{'internal.start_page'}++;
1.1359    raeburn  9985:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9986: 
1.338     albertel 9987:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9988:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9989:     }
1.1316    raeburn  9990: 
                   9991:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9992:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9993:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9994:                 $args->{'no_primary_menu'} = 1;
                   9995:             }
                   9996:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9997:                 $args->{'no_inline_menu'} = 1;
                   9998:             }
                   9999:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   10000:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   10001:             }
                   10002:         } else {
                   10003:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10004:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   10005:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   10006:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   10007:                     $args->{'no_primary_menu'} = 1;
                   10008:                 }
                   10009:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   10010:                     $args->{'no_inline_menu'} = 1;
                   10011:                 }
                   10012:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   10013:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   10014:                 }
                   10015:             }
                   10016:         }
1.1316    raeburn  10017:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   10018:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   10019:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  10020:     } elsif ($env{'request.course.id'}) {
                   10021:         my $expiretime=600;
                   10022:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   10023:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   10024:         }
                   10025:         my ($deeplinkmenu,$menuref);
                   10026:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   10027:         if ($menucoll) {
                   10028:             if (ref($menuref) eq 'HASH') {
                   10029:                 %menu = %{$menuref};
                   10030:             }
                   10031:             if ($menu{'top'} eq 'n') {
                   10032:                 $args->{'no_primary_menu'} = 1;
                   10033:             }
                   10034:             if ($menu{'inline'} eq 'n') {
                   10035:                 unless (&Apache::lonnet::allowed('opa')) {
                   10036:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10037:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10038:                     my $crstype = &course_type();
                   10039:                     my $now = time;
                   10040:                     my $ccrole;
                   10041:                     if ($crstype eq 'Community') {
                   10042:                         $ccrole = 'co';
                   10043:                     } else {
                   10044:                         $ccrole = 'cc';
                   10045:                     }
                   10046:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   10047:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   10048:                         if ((($start) && ($start<0)) ||
                   10049:                             (($end) && ($end<$now))  ||
                   10050:                             (($start) && ($now<$start))) {
                   10051:                             $args->{'no_inline_menu'} = 1;
                   10052:                         }
                   10053:                     } else {
                   10054:                         $args->{'no_inline_menu'} = 1;
                   10055:                     }
                   10056:                 }
                   10057:             }
                   10058:         }
1.1316    raeburn  10059:     }
1.1359    raeburn  10060: 
1.1385    raeburn  10061:     my $showncrumbs;
1.338     albertel 10062:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   10063: 	if ($args->{'frameset'}) {
                   10064: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   10065: 						$args->{'add_entries'});
                   10066: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   10067:         } else {
                   10068:             $result .=
                   10069:                 &bodytag($title, 
                   10070:                          $args->{'function'},       $args->{'add_entries'},
                   10071:                          $args->{'only_body'},      $args->{'domain'},
                   10072:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  10073:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  10074:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   10075:                          \%menu,\$showncrumbs);
1.831     bisitz   10076:         }
1.330     albertel 10077:     }
1.338     albertel 10078: 
1.315     albertel 10079:     if ($args->{'js_ready'}) {
1.713     kaisler  10080: 		$result = &js_ready($result);
1.315     albertel 10081:     }
1.320     albertel 10082:     if ($args->{'html_encode'}) {
1.713     kaisler  10083: 		$result = &html_encode($result);
                   10084:     }
                   10085: 
1.813     bisitz   10086:     # Preparation for new and consistent functionlist at top of screen
                   10087:     # if ($args->{'functionlist'}) {
                   10088:     #            $result .= &build_functionlist();
                   10089:     #}
                   10090: 
1.964     droeschl 10091:     # Don't add anything more if only_body wanted or in const space
                   10092:     return $result if    $args->{'only_body'} 
                   10093:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   10094: 
                   10095:     #Breadcrumbs
1.758     kaisler  10096:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  10097:         unless ($showncrumbs) {
1.758     kaisler  10098: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   10099: 		#if any br links exists, add them to the breadcrumbs
                   10100: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   10101: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   10102: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   10103: 			}
                   10104: 		}
1.1096    raeburn  10105:                 # if @advtools array contains items add then to the breadcrumbs
                   10106:                 if (@advtools > 0) {
                   10107:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   10108:                 }
1.1272    raeburn  10109:                 my $menulink;
                   10110:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   10111:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  10112:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  10113:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   10114:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   10115:                      (!$env{'request.role.adv'}))) {
                   10116:                     $menulink = 0;
                   10117:                 } else {
                   10118:                     undef($menulink);
                   10119:                 }
1.1385    raeburn  10120:                 my $linkprotout;
                   10121:                 if ($env{'request.deeplink.login'}) {
                   10122:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   10123:                     if ($linkprotout) {
                   10124:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   10125:                     }
                   10126:                 }
1.758     kaisler  10127: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   10128: 		if(exists($args->{'bread_crumbs_component'})){
1.1437    raeburn  10129: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},
                   10130:                                                                        '',$menulink,'',
                   10131:                                                                        $args->{'bread_crumbs_style'});
1.1237    raeburn  10132:                 } else {
1.1437    raeburn  10133: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink,'',
                   10134:                                                                        $args->{'bread_crumbs_style'});
1.758     kaisler  10135: 		}
1.1385    raeburn  10136:         }
1.320     albertel 10137:     }
1.315     albertel 10138:     return $result;
1.306     albertel 10139: }
                   10140: 
                   10141: sub end_page {
1.315     albertel 10142:     my ($args) = @_;
                   10143:     $env{'internal.end_page'}++;
1.330     albertel 10144:     my $result;
1.335     albertel 10145:     if ($args->{'discussion'}) {
                   10146: 	my ($target,$parser);
                   10147: 	if (ref($args->{'discussion'})) {
                   10148: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   10149: 				$args->{'discussion'}{'parser'});
                   10150: 	}
                   10151: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   10152:     }
1.330     albertel 10153:     if ($args->{'frameset'}) {
                   10154: 	$result .= '</frameset>';
                   10155:     } else {
1.635     raeburn  10156: 	$result .= &endbodytag($args);
1.330     albertel 10157:     }
1.1080    raeburn  10158:     unless ($args->{'notbody'}) {
                   10159:         $result .= "\n</html>";
                   10160:     }
1.330     albertel 10161: 
1.315     albertel 10162:     if ($args->{'js_ready'}) {
1.317     albertel 10163: 	$result = &js_ready($result);
1.315     albertel 10164:     }
1.335     albertel 10165: 
1.320     albertel 10166:     if ($args->{'html_encode'}) {
                   10167: 	$result = &html_encode($result);
                   10168:     }
1.335     albertel 10169: 
1.315     albertel 10170:     return $result;
                   10171: }
                   10172: 
1.1359    raeburn  10173: sub menucoll_in_effect {
                   10174:     my ($menucoll,$deeplinkmenu,%menu);
                   10175:     if ($env{'request.course.id'}) {
                   10176:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  10177:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  10178:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  10179:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10180:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10181:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   10182:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   10183:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10184:                     if (ref($navmap)) {
                   10185:                         $deeplink = $navmap->get_mapparam(undef,
                   10186:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   10187:                                                           '0.deeplink');
1.1370    raeburn  10188:                     } else {
                   10189:                         $check_login_symb = 1;
1.1362    raeburn  10190:                     }
                   10191:                 } else {
1.1370    raeburn  10192:                     my $symb = &Apache::lonnet::symbread();
                   10193:                     if ($symb) {
                   10194:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   10195:                     } else {
                   10196:                         $check_login_symb = 1;
                   10197:                     }
1.1362    raeburn  10198:                 }
                   10199:             } else {
1.1370    raeburn  10200:                 $check_login_symb = 1;
                   10201:             }
                   10202:             if ($check_login_symb) {
1.1362    raeburn  10203:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   10204:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   10205:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   10206:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10207:                     if (ref($navmap)) {
                   10208:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   10209:                     }
                   10210:                 } else {
                   10211:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   10212:                 }
                   10213:             }
1.1359    raeburn  10214:             if ($deeplink ne '') {
1.1378    raeburn  10215:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  10216:                 if ($display =~ /^\d+$/) {
                   10217:                     $deeplinkmenu = 1;
                   10218:                     $menucoll = $display;
                   10219:                 }
                   10220:             }
                   10221:         }
                   10222:         if ($menucoll) {
                   10223:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   10224:         }
                   10225:     }
                   10226:     return ($menucoll,$deeplinkmenu,\%menu);
                   10227: }
                   10228: 
1.1362    raeburn  10229: sub deeplink_login_symb {
                   10230:     my ($cnum,$cdom) = @_;
                   10231:     my $login_symb;
                   10232:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  10233:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   10234:     }
                   10235:     return $login_symb;
                   10236: }
                   10237: 
                   10238: sub symb_from_tinyurl {
                   10239:     my ($url,$cnum,$cdom) = @_;
                   10240:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   10241:         my $key = $1;
                   10242:         my ($tinyurl,$login);
                   10243:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   10244:         if (defined($cached)) {
                   10245:             $tinyurl = $result;
                   10246:         } else {
                   10247:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   10248:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   10249:             if ($currtiny{$key} ne '') {
                   10250:                 $tinyurl = $currtiny{$key};
                   10251:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  10252:             }
1.1364    raeburn  10253:         }
                   10254:         if ($tinyurl ne '') {
                   10255:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   10256:             if (wantarray) {
                   10257:                 return ($cnumreq,$symb);
                   10258:             } elsif ($cnumreq eq $cnum) {
                   10259:                 return $symb;
1.1362    raeburn  10260:             }
                   10261:         }
                   10262:     }
1.1364    raeburn  10263:     if (wantarray) {
                   10264:         return ();
                   10265:     } else {
                   10266:         return;
                   10267:     }
1.1362    raeburn  10268: }
                   10269: 
1.1405    raeburn  10270: sub usable_exttools {
                   10271:     my %tooltypes;
                   10272:     if ($env{'request.course.id'}) {
                   10273:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   10274:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   10275:                %tooltypes = (
                   10276:                              crs => 1,
                   10277:                              dom => 1,
                   10278:                             );
                   10279:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   10280:                $tooltypes{'crs'} = 1;
                   10281:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   10282:                $tooltypes{'dom'} = 1;
                   10283:            }
                   10284:         } else {
                   10285:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10286:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10287:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   10288:             if ($crstype eq '') {
                   10289:                 $crstype = 'course';
                   10290:             }
                   10291:             if ($crstype eq 'course') {
                   10292:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   10293:                     $crstype = 'official';
                   10294:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   10295:                     $crstype = 'textbook';
                   10296:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   10297:                     $crstype = 'lti';
                   10298:                 } else {
                   10299:                     $crstype = 'unofficial';
                   10300:                 }
                   10301:             }
                   10302:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   10303:             if ($domdefaults{$crstype.'domexttool'}) {
                   10304:                 $tooltypes{'dom'} = 1;
                   10305:             }
                   10306:             if ($domdefaults{$crstype.'exttool'}) {
                   10307:                 $tooltypes{'crs'} = 1;
                   10308:             }
                   10309:         }
                   10310:     }
                   10311:     return %tooltypes;
                   10312: }
                   10313: 
1.1034    www      10314: sub wishlist_window {
                   10315:     return(<<'ENDWISHLIST');
1.1046    raeburn  10316: <script type="text/javascript">
1.1034    www      10317: // <![CDATA[
                   10318: // <!-- BEGIN LON-CAPA Internal
                   10319: function set_wishlistlink(title, path) {
                   10320:     if (!title) {
                   10321:         title = document.title;
                   10322:         title = title.replace(/^LON-CAPA /,'');
                   10323:     }
1.1175    raeburn  10324:     title = encodeURIComponent(title);
1.1203    raeburn  10325:     title = title.replace("'","\\\'");
1.1034    www      10326:     if (!path) {
                   10327:         path = location.pathname;
                   10328:     }
1.1175    raeburn  10329:     path = encodeURIComponent(path);
1.1203    raeburn  10330:     path = path.replace("'","\\\'");
1.1034    www      10331:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   10332:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   10333: }
                   10334: // END LON-CAPA Internal -->
                   10335: // ]]>
                   10336: </script>
                   10337: ENDWISHLIST
                   10338: }
                   10339: 
1.1030    www      10340: sub modal_window {
                   10341:     return(<<'ENDMODAL');
1.1046    raeburn  10342: <script type="text/javascript">
1.1030    www      10343: // <![CDATA[
                   10344: // <!-- BEGIN LON-CAPA Internal
                   10345: var modalWindow = {
                   10346: 	parent:"body",
                   10347: 	windowId:null,
                   10348: 	content:null,
                   10349: 	width:null,
                   10350: 	height:null,
                   10351: 	close:function()
                   10352: 	{
                   10353: 	        $(".LCmodal-window").remove();
                   10354: 	        $(".LCmodal-overlay").remove();
                   10355: 	},
                   10356: 	open:function()
                   10357: 	{
                   10358: 		var modal = "";
                   10359: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   10360: 		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;\">";
                   10361: 		modal += this.content;
                   10362: 		modal += "</div>";	
                   10363: 
                   10364: 		$(this.parent).append(modal);
                   10365: 
                   10366: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   10367: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   10368: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   10369: 	}
                   10370: };
1.1140    raeburn  10371: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      10372: 	{
1.1266    raeburn  10373:                 source = source.replace(/'/g,"&#39;");
1.1030    www      10374: 		modalWindow.windowId = "myModal";
                   10375: 		modalWindow.width = width;
                   10376: 		modalWindow.height = height;
1.1196    raeburn  10377: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      10378: 		modalWindow.open();
1.1208    raeburn  10379: 	};
1.1030    www      10380: // END LON-CAPA Internal -->
                   10381: // ]]>
                   10382: </script>
                   10383: ENDMODAL
                   10384: }
                   10385: 
                   10386: sub modal_link {
1.1140    raeburn  10387:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      10388:     unless ($width) { $width=480; }
                   10389:     unless ($height) { $height=400; }
1.1031    www      10390:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  10391:     unless ($transparency) { $transparency='true'; }
                   10392: 
1.1074    raeburn  10393:     my $target_attr;
                   10394:     if (defined($target)) {
                   10395:         $target_attr = 'target="'.$target.'"';
                   10396:     }
                   10397:     return <<"ENDLINK";
1.1336    raeburn  10398: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  10399: ENDLINK
1.1030    www      10400: }
                   10401: 
1.1032    www      10402: sub modal_adhoc_script {
1.1365    raeburn  10403:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   10404:     my $mathjax;
                   10405:     if ($possmathjax) {
                   10406:         $mathjax = <<'ENDJAX';
                   10407:                if (typeof MathJax == 'object') {
                   10408:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   10409:                }
                   10410: ENDJAX
                   10411:     }
1.1032    www      10412:     return (<<ENDADHOC);
1.1046    raeburn  10413: <script type="text/javascript">
1.1032    www      10414: // <![CDATA[
                   10415:         var $funcname = function()
                   10416:         {
                   10417:                 modalWindow.windowId = "myModal";
                   10418:                 modalWindow.width = $width;
                   10419:                 modalWindow.height = $height;
                   10420:                 modalWindow.content = '$content';
                   10421:                 modalWindow.open();
1.1365    raeburn  10422:                 $mathjax
1.1032    www      10423:         };  
                   10424: // ]]>
                   10425: </script>
                   10426: ENDADHOC
                   10427: }
                   10428: 
1.1041    www      10429: sub modal_adhoc_inner {
1.1365    raeburn  10430:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      10431:     my $innerwidth=$width-20;
                   10432:     $content=&js_ready(
1.1140    raeburn  10433:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   10434:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   10435:                  $content.
1.1041    www      10436:                  &end_scrollbox().
1.1140    raeburn  10437:                  &end_page()
1.1041    www      10438:              );
1.1365    raeburn  10439:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      10440: }
                   10441: 
                   10442: sub modal_adhoc_window {
1.1365    raeburn  10443:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   10444:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      10445:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   10446: }
                   10447: 
                   10448: sub modal_adhoc_launch {
                   10449:     my ($funcname,$width,$height,$content)=@_;
                   10450:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   10451: <script type="text/javascript">
                   10452: // <![CDATA[
                   10453: $funcname();
                   10454: // ]]>
                   10455: </script>
                   10456: ENDLAUNCH
                   10457: }
                   10458: 
                   10459: sub modal_adhoc_close {
                   10460:     return (<<ENDCLOSE);
                   10461: <script type="text/javascript">
                   10462: // <![CDATA[
                   10463: modalWindow.close();
                   10464: // ]]>
                   10465: </script>
                   10466: ENDCLOSE
                   10467: }
                   10468: 
1.1038    www      10469: sub togglebox_script {
                   10470:    return(<<ENDTOGGLE);
                   10471: <script type="text/javascript"> 
                   10472: // <![CDATA[
                   10473: function LCtoggleDisplay(id,hidetext,showtext) {
                   10474:    link = document.getElementById(id + "link").childNodes[0];
                   10475:    with (document.getElementById(id).style) {
                   10476:       if (display == "none" ) {
                   10477:           display = "inline";
                   10478:           link.nodeValue = hidetext;
                   10479:         } else {
                   10480:           display = "none";
                   10481:           link.nodeValue = showtext;
                   10482:        }
                   10483:    }
                   10484: }
                   10485: // ]]>
                   10486: </script>
                   10487: ENDTOGGLE
                   10488: }
                   10489: 
1.1039    www      10490: sub start_togglebox {
                   10491:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   10492:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   10493:     unless ($showtext) { $showtext=&mt('show'); }
                   10494:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   10495:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   10496:     return &start_data_table().
                   10497:            &start_data_table_header_row().
                   10498:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   10499:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   10500:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   10501:            &end_data_table_header_row().
                   10502:            '<tr id="'.$id.'" style="display:none""><td>';
                   10503: }
                   10504: 
                   10505: sub end_togglebox {
                   10506:     return '</td></tr>'.&end_data_table();
                   10507: }
                   10508: 
1.1041    www      10509: sub LCprogressbar_script {
1.1302    raeburn  10510:    my ($id,$number_to_do)=@_;
                   10511:    if ($number_to_do) {
                   10512:        return(<<ENDPROGRESS);
1.1041    www      10513: <script type="text/javascript">
                   10514: // <![CDATA[
1.1045    www      10515: \$('#progressbar$id').progressbar({
1.1041    www      10516:   value: 0,
                   10517:   change: function(event, ui) {
                   10518:     var newVal = \$(this).progressbar('option', 'value');
                   10519:     \$('.pblabel', this).text(LCprogressTxt);
                   10520:   }
                   10521: });
                   10522: // ]]>
                   10523: </script>
                   10524: ENDPROGRESS
1.1302    raeburn  10525:    } else {
                   10526:        return(<<ENDPROGRESS);
                   10527: <script type="text/javascript">
                   10528: // <![CDATA[
                   10529: \$('#progressbar$id').progressbar({
                   10530:   value: false,
                   10531:   create: function(event, ui) {
                   10532:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   10533:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   10534:   }
                   10535: });
                   10536: // ]]>
                   10537: </script>
                   10538: ENDPROGRESS
                   10539:    }
1.1041    www      10540: }
                   10541: 
                   10542: sub LCprogressbarUpdate_script {
                   10543:    return(<<ENDPROGRESSUPDATE);
                   10544: <style type="text/css">
                   10545: .ui-progressbar { position:relative; }
1.1302    raeburn  10546: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
1.1041    www      10547: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   10548: </style>
                   10549: <script type="text/javascript">
                   10550: // <![CDATA[
1.1045    www      10551: var LCprogressTxt='---';
                   10552: 
1.1302    raeburn  10553: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      10554:    LCprogressTxt=progresstext;
1.1302    raeburn  10555:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   10556:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   10557:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  10558:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   10559:    } else {
                   10560:        \$('#progressbar'+id).progressbar('value',percent);
                   10561:    }
1.1041    www      10562: }
                   10563: // ]]>
                   10564: </script>
                   10565: ENDPROGRESSUPDATE
                   10566: }
                   10567: 
1.1042    www      10568: my $LClastpercent;
1.1045    www      10569: my $LCidcnt;
                   10570: my $LCcurrentid;
1.1042    www      10571: 
1.1041    www      10572: sub LCprogressbar {
1.1302    raeburn  10573:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      10574:     $LClastpercent=0;
1.1045    www      10575:     $LCidcnt++;
                   10576:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  10577:     my ($starting,$content);
                   10578:     if ($number_to_do) {
                   10579:         $starting=&mt('Starting');
                   10580:         $content=(<<ENDPROGBAR);
                   10581: $preamble
1.1045    www      10582:   <div id="progressbar$LCcurrentid">
1.1041    www      10583:     <span class="pblabel">$starting</span>
                   10584:   </div>
                   10585: ENDPROGBAR
1.1302    raeburn  10586:     } else {
                   10587:         $starting=&mt('Loading...');
                   10588:         $LClastpercent='false';
                   10589:         $content=(<<ENDPROGBAR);
                   10590: $preamble
                   10591:   <div id="progressbar$LCcurrentid">
                   10592:       <div class="progress-label">$starting</div>
                   10593:   </div>
                   10594: ENDPROGBAR
                   10595:     }
                   10596:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      10597: }
                   10598: 
                   10599: sub LCprogressbarUpdate {
1.1302    raeburn  10600:     my ($r,$val,$text,$number_to_do)=@_;
                   10601:     if ($number_to_do) {
                   10602:         unless ($val) { 
                   10603:             if ($LClastpercent) {
                   10604:                 $val=$LClastpercent;
                   10605:             } else {
                   10606:                 $val=0;
                   10607:             }
                   10608:         }
                   10609:         if ($val<0) { $val=0; }
                   10610:         if ($val>100) { $val=0; }
                   10611:         $LClastpercent=$val;
                   10612:         unless ($text) { $text=$val.'%'; }
                   10613:     } else {
                   10614:         $val = 'false';
1.1042    www      10615:     }
1.1041    www      10616:     $text=&js_ready($text);
1.1044    www      10617:     &r_print($r,<<ENDUPDATE);
1.1041    www      10618: <script type="text/javascript">
                   10619: // <![CDATA[
1.1302    raeburn  10620: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10621: // ]]>
                   10622: </script>
                   10623: ENDUPDATE
1.1035    www      10624: }
                   10625: 
1.1042    www      10626: sub LCprogressbarClose {
                   10627:     my ($r)=@_;
                   10628:     $LClastpercent=0;
1.1044    www      10629:     &r_print($r,<<ENDCLOSE);
1.1042    www      10630: <script type="text/javascript">
                   10631: // <![CDATA[
1.1045    www      10632: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10633: // ]]>
                   10634: </script>
                   10635: ENDCLOSE
1.1044    www      10636: }
                   10637: 
                   10638: sub r_print {
                   10639:     my ($r,$to_print)=@_;
                   10640:     if ($r) {
                   10641:       $r->print($to_print);
                   10642:       $r->rflush();
                   10643:     } else {
                   10644:       print($to_print);
                   10645:     }
1.1042    www      10646: }
                   10647: 
1.320     albertel 10648: sub html_encode {
                   10649:     my ($result) = @_;
                   10650: 
1.322     albertel 10651:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10652:     
                   10653:     return $result;
                   10654: }
1.1044    www      10655: 
1.317     albertel 10656: sub js_ready {
                   10657:     my ($result) = @_;
                   10658: 
1.323     albertel 10659:     $result =~ s/[\n\r]/ /xmsg;
                   10660:     $result =~ s/\\/\\\\/xmsg;
                   10661:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10662:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10663:     
                   10664:     return $result;
                   10665: }
                   10666: 
1.315     albertel 10667: sub validate_page {
                   10668:     if (  exists($env{'internal.start_page'})
1.316     albertel 10669: 	  &&     $env{'internal.start_page'} > 1) {
                   10670: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10671: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10672: 				 $ENV{'request.filename'});
1.315     albertel 10673:     }
                   10674:     if (  exists($env{'internal.end_page'})
1.316     albertel 10675: 	  &&     $env{'internal.end_page'} > 1) {
                   10676: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10677: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10678: 				 $env{'request.filename'});
1.315     albertel 10679:     }
                   10680:     if (     exists($env{'internal.start_page'})
                   10681: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10682: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10683: 				 $env{'request.filename'});
1.315     albertel 10684:     }
                   10685:     if (   ! exists($env{'internal.start_page'})
                   10686: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10687: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10688: 				 $env{'request.filename'});
1.315     albertel 10689:     }
1.306     albertel 10690: }
1.315     albertel 10691: 
1.996     www      10692: 
                   10693: sub start_scrollbox {
1.1140    raeburn  10694:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10695:     unless ($outerwidth) { $outerwidth='520px'; }
                   10696:     unless ($width) { $width='500px'; }
                   10697:     unless ($height) { $height='200px'; }
1.1075    raeburn  10698:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10699:     if ($id ne '') {
1.1140    raeburn  10700:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10701:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10702:     }
1.1075    raeburn  10703:     if ($bgcolor ne '') {
                   10704:         $tdcol = "background-color: $bgcolor;";
                   10705:     }
1.1137    raeburn  10706:     my $nicescroll_js;
                   10707:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10708:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10709:     }
                   10710:     return <<"END";
                   10711: $nicescroll_js
                   10712: 
                   10713: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10714: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10715: END
                   10716: }
                   10717: 
                   10718: sub end_scrollbox {
                   10719:     return '</div></td></tr></table>';
                   10720: }
                   10721: 
                   10722: sub nicescroll_javascript {
                   10723:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10724:     my %options;
                   10725:     if (ref($cursor) eq 'HASH') {
                   10726:         %options = %{$cursor};
                   10727:     }
                   10728:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10729:         $options{'railalign'} = 'left';
                   10730:     }
                   10731:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10732:         my $function  = &get_users_function();
                   10733:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10734:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10735:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10736:         }
1.1140    raeburn  10737:     }
                   10738:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10739:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10740:             $options{'cursoropacity'}='1.0';
                   10741:         }
1.1140    raeburn  10742:     } else {
                   10743:         $options{'cursoropacity'}='1.0';
                   10744:     }
                   10745:     if ($options{'cursorfixedheight'} eq 'none') {
                   10746:         delete($options{'cursorfixedheight'});
                   10747:     } else {
                   10748:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10749:     }
                   10750:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10751:         delete($options{'railoffset'});
                   10752:     }
                   10753:     my @niceoptions;
                   10754:     while (my($key,$value) = each(%options)) {
                   10755:         if ($value =~ /^\{.+\}$/) {
                   10756:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10757:         } else {
1.1140    raeburn  10758:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10759:         }
1.1140    raeburn  10760:     }
                   10761:     my $nicescroll_js = '
1.1137    raeburn  10762: $(document).ready(
1.1140    raeburn  10763:       function() {
                   10764:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10765:       }
1.1137    raeburn  10766: );
                   10767: ';
1.1140    raeburn  10768:     if ($framecheck) {
                   10769:         $nicescroll_js .= '
                   10770: function expand_div(caller) {
                   10771:     if (top === self) {
                   10772:         document.getElementById("'.$id.'").style.width = "auto";
                   10773:         document.getElementById("'.$id.'").style.height = "auto";
                   10774:     } else {
                   10775:         try {
                   10776:             if (parent.frames) {
                   10777:                 if (parent.frames.length > 1) {
                   10778:                     var framesrc = parent.frames[1].location.href;
                   10779:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10780:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10781:                         document.getElementById("'.$id.'").style.width = "auto";
                   10782:                         document.getElementById("'.$id.'").style.height = "auto";
                   10783:                     }
                   10784:                 }
                   10785:             }
                   10786:         } catch (e) {
                   10787:             return;
                   10788:         }
1.1137    raeburn  10789:     }
1.1140    raeburn  10790:     return;
1.996     www      10791: }
1.1140    raeburn  10792: ';
                   10793:     }
                   10794:     if ($needjsready) {
                   10795:         $nicescroll_js = '
                   10796: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10797:     } else {
                   10798:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10799:     }
                   10800:     return $nicescroll_js;
1.996     www      10801: }
                   10802: 
1.318     albertel 10803: sub simple_error_page {
1.1150    bisitz   10804:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10805:     my %displayargs;
1.1151    raeburn  10806:     if (ref($args) eq 'HASH') {
                   10807:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10808:         if ($args->{'only_body'}) {
                   10809:             $displayargs{'only_body'} = 1;
                   10810:         }
                   10811:         if ($args->{'no_nav_bar'}) {
                   10812:             $displayargs{'no_nav_bar'} = 1;
                   10813:         }
1.1151    raeburn  10814:     } else {
                   10815:         $msg = &mt($msg);
                   10816:     }
1.1150    bisitz   10817: 
1.318     albertel 10818:     my $page =
1.1304    raeburn  10819: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10820: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10821: 	&Apache::loncommon::end_page();
                   10822:     if (ref($r)) {
                   10823: 	$r->print($page);
1.327     albertel 10824: 	return;
1.318     albertel 10825:     }
                   10826:     return $page;
                   10827: }
1.347     albertel 10828: 
                   10829: {
1.610     albertel 10830:     my @row_count;
1.961     onken    10831: 
                   10832:     sub start_data_table_count {
                   10833:         unshift(@row_count, 0);
                   10834:         return;
                   10835:     }
                   10836: 
                   10837:     sub end_data_table_count {
                   10838:         shift(@row_count);
                   10839:         return;
                   10840:     }
                   10841: 
1.347     albertel 10842:     sub start_data_table {
1.1018    raeburn  10843: 	my ($add_class,$id) = @_;
1.422     albertel 10844: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10845:         my $table_id;
                   10846:         if (defined($id)) {
                   10847:             $table_id = ' id="'.$id.'"';
                   10848:         }
1.961     onken    10849: 	&start_data_table_count();
1.1018    raeburn  10850: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10851:     }
                   10852: 
                   10853:     sub end_data_table {
1.961     onken    10854: 	&end_data_table_count();
1.389     albertel 10855: 	return '</table>'."\n";;
1.347     albertel 10856:     }
                   10857: 
                   10858:     sub start_data_table_row {
1.974     wenzelju 10859: 	my ($add_class, $id) = @_;
1.610     albertel 10860: 	$row_count[0]++;
                   10861: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10862: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10863:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10864:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10865:     }
1.471     banghart 10866:     
                   10867:     sub continue_data_table_row {
1.974     wenzelju 10868: 	my ($add_class, $id) = @_;
1.610     albertel 10869: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10870: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10871:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10872:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10873:     }
1.347     albertel 10874: 
                   10875:     sub end_data_table_row {
1.389     albertel 10876: 	return '</tr>'."\n";;
1.347     albertel 10877:     }
1.367     www      10878: 
1.421     albertel 10879:     sub start_data_table_empty_row {
1.707     bisitz   10880: #	$row_count[0]++;
1.421     albertel 10881: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10882:     }
                   10883: 
                   10884:     sub end_data_table_empty_row {
                   10885: 	return '</tr>'."\n";;
                   10886:     }
                   10887: 
1.367     www      10888:     sub start_data_table_header_row {
1.389     albertel 10889: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10890:     }
                   10891: 
                   10892:     sub end_data_table_header_row {
1.389     albertel 10893: 	return '</tr>'."\n";;
1.367     www      10894:     }
1.890     droeschl 10895: 
                   10896:     sub data_table_caption {
                   10897:         my $caption = shift;
                   10898:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10899:     }
1.347     albertel 10900: }
                   10901: 
1.548     albertel 10902: =pod
                   10903: 
                   10904: =item * &inhibit_menu_check($arg)
                   10905: 
                   10906: Checks for a inhibitmenu state and generates output to preserve it
                   10907: 
                   10908: Inputs:         $arg - can be any of
                   10909:                      - undef - in which case the return value is a string 
                   10910:                                to add  into arguments list of a uri
                   10911:                      - 'input' - in which case the return value is a HTML
                   10912:                                  <form> <input> field of type hidden to
                   10913:                                  preserve the value
                   10914:                      - a url - in which case the return value is the url with
                   10915:                                the neccesary cgi args added to preserve the
                   10916:                                inhibitmenu state
                   10917:                      - a ref to a url - no return value, but the string is
                   10918:                                         updated to include the neccessary cgi
                   10919:                                         args to preserve the inhibitmenu state
                   10920: 
                   10921: =cut
                   10922: 
                   10923: sub inhibit_menu_check {
                   10924:     my ($arg) = @_;
                   10925:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10926:     if ($arg eq 'input') {
                   10927: 	if ($env{'form.inhibitmenu'}) {
                   10928: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10929: 	} else {
                   10930: 	    return
                   10931: 	}
                   10932:     }
                   10933:     if ($env{'form.inhibitmenu'}) {
                   10934: 	if (ref($arg)) {
                   10935: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10936: 	} elsif ($arg eq '') {
                   10937: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10938: 	} else {
                   10939: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10940: 	}
                   10941:     }
                   10942:     if (!ref($arg)) {
                   10943: 	return $arg;
                   10944:     }
                   10945: }
                   10946: 
1.251     albertel 10947: ###############################################
1.182     matthew  10948: 
                   10949: =pod
                   10950: 
1.549     albertel 10951: =back
                   10952: 
                   10953: =head1 User Information Routines
                   10954: 
                   10955: =over 4
                   10956: 
1.405     albertel 10957: =item * &get_users_function()
1.182     matthew  10958: 
                   10959: Used by &bodytag to determine the current users primary role.
                   10960: Returns either 'student','coordinator','admin', or 'author'.
                   10961: 
                   10962: =cut
                   10963: 
                   10964: ###############################################
                   10965: sub get_users_function {
1.815     tempelho 10966:     my $function = 'norole';
1.818     tempelho 10967:     if ($env{'request.role'}=~/^(st)/) {
                   10968:         $function='student';
                   10969:     }
1.907     raeburn  10970:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10971:         $function='coordinator';
                   10972:     }
1.258     albertel 10973:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10974:         $function='admin';
                   10975:     }
1.826     bisitz   10976:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10977:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10978:         $function='author';
                   10979:     }
                   10980:     return $function;
1.54      www      10981: }
1.99      www      10982: 
                   10983: ###############################################
                   10984: 
1.233     raeburn  10985: =pod
                   10986: 
1.821     raeburn  10987: =item * &show_course()
                   10988: 
                   10989: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10990: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10991: 
                   10992: Inputs:
                   10993: None
                   10994: 
                   10995: Outputs:
                   10996: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10997: 
                   10998: =cut
                   10999: 
                   11000: ###############################################
                   11001: sub show_course {
1.1408    raeburn  11002:     my ($udom,$uname) = @_;
                   11003:     if (($udom ne '') && ($uname ne '')) {
                   11004:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
1.1410    raeburn  11005:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
1.1408    raeburn  11006:                 return 0;
                   11007:             } else {
                   11008:                 return 1;
                   11009:             }
                   11010:         }
                   11011:     }
1.821     raeburn  11012:     my $course = !$env{'user.adv'};
                   11013:     if (!$env{'user.adv'}) {
                   11014:         foreach my $env (keys(%env)) {
                   11015:             next if ($env !~ m/^user\.priv\./);
                   11016:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   11017:                 $course = 0;
                   11018:                 last;
                   11019:             }
                   11020:         }
                   11021:     }
                   11022:     return $course;
                   11023: }
                   11024: 
                   11025: ###############################################
                   11026: 
                   11027: =pod
                   11028: 
1.542     raeburn  11029: =item * &check_user_status()
1.274     raeburn  11030: 
                   11031: Determines current status of supplied role for a
                   11032: specific user. Roles can be active, previous or future.
                   11033: 
                   11034: Inputs: 
                   11035: user's domain, user's username, course's domain,
1.375     raeburn  11036: course's number, optional section ID.
1.274     raeburn  11037: 
                   11038: Outputs:
                   11039: role status: active, previous or future. 
                   11040: 
                   11041: =cut
                   11042: 
                   11043: sub check_user_status {
1.412     raeburn  11044:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  11045:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  11046:     my @uroles = keys(%userinfo);
1.274     raeburn  11047:     my $srchstr;
                   11048:     my $active_chk = 'none';
1.412     raeburn  11049:     my $now = time;
1.274     raeburn  11050:     if (@uroles > 0) {
1.908     raeburn  11051:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  11052:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   11053:         } else {
1.412     raeburn  11054:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   11055:         }
                   11056:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  11057:             my $role_end = 0;
                   11058:             my $role_start = 0;
                   11059:             $active_chk = 'active';
1.412     raeburn  11060:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   11061:                 $role_end = $1;
                   11062:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   11063:                     $role_start = $1;
1.274     raeburn  11064:                 }
                   11065:             }
                   11066:             if ($role_start > 0) {
1.412     raeburn  11067:                 if ($now < $role_start) {
1.274     raeburn  11068:                     $active_chk = 'future';
                   11069:                 }
                   11070:             }
                   11071:             if ($role_end > 0) {
1.412     raeburn  11072:                 if ($now > $role_end) {
1.274     raeburn  11073:                     $active_chk = 'previous';
                   11074:                 }
                   11075:             }
                   11076:         }
                   11077:     }
                   11078:     return $active_chk;
                   11079: }
                   11080: 
                   11081: ###############################################
                   11082: 
                   11083: =pod
                   11084: 
1.405     albertel 11085: =item * &get_sections()
1.233     raeburn  11086: 
                   11087: Determines all the sections for a course including
                   11088: sections with students and sections containing other roles.
1.419     raeburn  11089: Incoming parameters: 
                   11090: 
                   11091: 1. domain
                   11092: 2. course number 
                   11093: 3. reference to array containing roles for which sections should 
                   11094: be gathered (optional).
                   11095: 4. reference to array containing status types for which sections 
                   11096: should be gathered (optional).
                   11097: 
                   11098: If the third argument is undefined, sections are gathered for any role. 
                   11099: If the fourth argument is undefined, sections are gathered for any status.
                   11100: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  11101:  
1.374     raeburn  11102: Returns section hash (keys are section IDs, values are
                   11103: number of users in each section), subject to the
1.419     raeburn  11104: optional roles filter, optional status filter 
1.233     raeburn  11105: 
                   11106: =cut
                   11107: 
                   11108: ###############################################
                   11109: sub get_sections {
1.419     raeburn  11110:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 11111:     if (!defined($cdom) || !defined($cnum)) {
                   11112:         my $cid =  $env{'request.course.id'};
                   11113: 
                   11114: 	return if (!defined($cid));
                   11115: 
                   11116:         $cdom = $env{'course.'.$cid.'.domain'};
                   11117:         $cnum = $env{'course.'.$cid.'.num'};
                   11118:     }
                   11119: 
                   11120:     my %sectioncount;
1.419     raeburn  11121:     my $now = time;
1.240     albertel 11122: 
1.1118    raeburn  11123:     my $check_students = 1;
                   11124:     my $only_students = 0;
                   11125:     if (ref($possible_roles) eq 'ARRAY') {
                   11126:         if (grep(/^st$/,@{$possible_roles})) {
                   11127:             if (@{$possible_roles} == 1) {
                   11128:                 $only_students = 1;
                   11129:             }
                   11130:         } else {
                   11131:             $check_students = 0;
                   11132:         }
                   11133:     }
                   11134: 
                   11135:     if ($check_students) { 
1.276     albertel 11136: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 11137: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   11138: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  11139:         my $start_index = &Apache::loncoursedata::CL_START();
                   11140:         my $end_index = &Apache::loncoursedata::CL_END();
                   11141:         my $status;
1.366     albertel 11142: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  11143: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   11144: 				                     $data->[$status_index],
                   11145:                                                      $data->[$start_index],
                   11146:                                                      $data->[$end_index]);
                   11147:             if ($stu_status eq 'Active') {
                   11148:                 $status = 'active';
                   11149:             } elsif ($end < $now) {
                   11150:                 $status = 'previous';
                   11151:             } elsif ($start > $now) {
                   11152:                 $status = 'future';
                   11153:             } 
                   11154: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   11155:                 if ((!defined($possible_status)) || (($status ne '') && 
                   11156:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   11157: 		    $sectioncount{$section}++;
                   11158:                 }
1.240     albertel 11159: 	    }
                   11160: 	}
                   11161:     }
1.1118    raeburn  11162:     if ($only_students) {
                   11163:         return %sectioncount;
                   11164:     }
1.240     albertel 11165:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11166:     foreach my $user (sort(keys(%courseroles))) {
                   11167: 	if ($user !~ /^(\w{2})/) { next; }
                   11168: 	my ($role) = ($user =~ /^(\w{2})/);
                   11169: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  11170: 	my ($section,$status);
1.240     albertel 11171: 	if ($role eq 'cr' &&
                   11172: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   11173: 	    $section=$1;
                   11174: 	}
                   11175: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   11176: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  11177:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   11178:         if ($end == -1 && $start == -1) {
                   11179:             next; #deleted role
                   11180:         }
                   11181:         if (!defined($possible_status)) { 
                   11182:             $sectioncount{$section}++;
                   11183:         } else {
                   11184:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   11185:                 $status = 'active';
                   11186:             } elsif ($end < $now) {
                   11187:                 $status = 'future';
                   11188:             } elsif ($start > $now) {
                   11189:                 $status = 'previous';
                   11190:             }
                   11191:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   11192:                 $sectioncount{$section}++;
                   11193:             }
                   11194:         }
1.233     raeburn  11195:     }
1.366     albertel 11196:     return %sectioncount;
1.233     raeburn  11197: }
                   11198: 
1.274     raeburn  11199: ###############################################
1.294     raeburn  11200: 
                   11201: =pod
1.405     albertel 11202: 
                   11203: =item * &get_course_users()
                   11204: 
1.275     raeburn  11205: Retrieves usernames:domains for users in the specified course
                   11206: with specific role(s), and access status. 
                   11207: 
                   11208: Incoming parameters:
1.277     albertel 11209: 1. course domain
                   11210: 2. course number
                   11211: 3. access status: users must have - either active, 
1.275     raeburn  11212: previous, future, or all.
1.277     albertel 11213: 4. reference to array of permissible roles
1.288     raeburn  11214: 5. reference to array of section restrictions (optional)
                   11215: 6. reference to results object (hash of hashes).
                   11216: 7. reference to optional userdata hash
1.609     raeburn  11217: 8. reference to optional statushash
1.630     raeburn  11218: 9. flag if privileged users (except those set to unhide in
                   11219:    course settings) should be excluded    
1.609     raeburn  11220: Keys of top level results hash are roles.
1.275     raeburn  11221: Keys of inner hashes are username:domain, with 
                   11222: values set to access type.
1.288     raeburn  11223: Optional userdata hash returns an array with arguments in the 
                   11224: same order as loncoursedata::get_classlist() for student data.
                   11225: 
1.609     raeburn  11226: Optional statushash returns
                   11227: 
1.288     raeburn  11228: Entries for end, start, section and status are blank because
                   11229: of the possibility of multiple values for non-student roles.
                   11230: 
1.275     raeburn  11231: =cut
1.405     albertel 11232: 
1.275     raeburn  11233: ###############################################
1.405     albertel 11234: 
1.275     raeburn  11235: sub get_course_users {
1.630     raeburn  11236:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  11237:     my %idx = ();
1.419     raeburn  11238:     my %seclists;
1.288     raeburn  11239: 
                   11240:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   11241:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   11242:     $idx{end} = &Apache::loncoursedata::CL_END();
                   11243:     $idx{start} = &Apache::loncoursedata::CL_START();
                   11244:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   11245:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   11246:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   11247:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   11248: 
1.290     albertel 11249:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 11250:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  11251:         my $now = time;
1.277     albertel 11252:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  11253:             my $match = 0;
1.412     raeburn  11254:             my $secmatch = 0;
1.419     raeburn  11255:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  11256:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  11257:             if ($section eq '') {
                   11258:                 $section = 'none';
                   11259:             }
1.291     albertel 11260:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11261:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11262:                     $secmatch = 1;
                   11263:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 11264:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11265:                         $secmatch = 1;
                   11266:                     }
                   11267:                 } else {  
1.419     raeburn  11268: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  11269: 		        $secmatch = 1;
                   11270:                     }
1.290     albertel 11271: 		}
1.412     raeburn  11272:                 if (!$secmatch) {
                   11273:                     next;
                   11274:                 }
1.419     raeburn  11275:             }
1.275     raeburn  11276:             if (defined($$types{'active'})) {
1.288     raeburn  11277:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  11278:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  11279:                     $match = 1;
1.275     raeburn  11280:                 }
                   11281:             }
                   11282:             if (defined($$types{'previous'})) {
1.609     raeburn  11283:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  11284:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  11285:                     $match = 1;
1.275     raeburn  11286:                 }
                   11287:             }
                   11288:             if (defined($$types{'future'})) {
1.609     raeburn  11289:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  11290:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  11291:                     $match = 1;
1.275     raeburn  11292:                 }
                   11293:             }
1.609     raeburn  11294:             if ($match) {
                   11295:                 push(@{$seclists{$student}},$section);
                   11296:                 if (ref($userdata) eq 'HASH') {
                   11297:                     $$userdata{$student} = $$classlist{$student};
                   11298:                 }
                   11299:                 if (ref($statushash) eq 'HASH') {
                   11300:                     $statushash->{$student}{'st'}{$section} = $status;
                   11301:                 }
1.288     raeburn  11302:             }
1.275     raeburn  11303:         }
                   11304:     }
1.412     raeburn  11305:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  11306:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11307:         my $now = time;
1.609     raeburn  11308:         my %displaystatus = ( previous => 'Expired',
                   11309:                               active   => 'Active',
                   11310:                               future   => 'Future',
                   11311:                             );
1.1121    raeburn  11312:         my (%nothide,@possdoms);
1.630     raeburn  11313:         if ($hidepriv) {
                   11314:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   11315:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   11316:                 if ($user !~ /:/) {
                   11317:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   11318:                 } else {
                   11319:                     $nothide{$user} = 1;
                   11320:                 }
                   11321:             }
1.1121    raeburn  11322:             my @possdoms = ($cdom);
                   11323:             if ($coursehash{'checkforpriv'}) {
                   11324:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   11325:             }
1.630     raeburn  11326:         }
1.439     raeburn  11327:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  11328:             my $match = 0;
1.412     raeburn  11329:             my $secmatch = 0;
1.439     raeburn  11330:             my $status;
1.412     raeburn  11331:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  11332:             $user =~ s/:$//;
1.439     raeburn  11333:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   11334:             if ($end == -1 || $start == -1) {
                   11335:                 next;
                   11336:             }
                   11337:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   11338:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  11339:                 my ($uname,$udom) = split(/:/,$user);
                   11340:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11341:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11342:                         $secmatch = 1;
                   11343:                     } elsif ($usec eq '') {
1.420     albertel 11344:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11345:                             $secmatch = 1;
                   11346:                         }
                   11347:                     } else {
                   11348:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   11349:                             $secmatch = 1;
                   11350:                         }
                   11351:                     }
                   11352:                     if (!$secmatch) {
                   11353:                         next;
                   11354:                     }
1.288     raeburn  11355:                 }
1.419     raeburn  11356:                 if ($usec eq '') {
                   11357:                     $usec = 'none';
                   11358:                 }
1.275     raeburn  11359:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  11360:                     if ($hidepriv) {
1.1121    raeburn  11361:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  11362:                             (!$nothide{$uname.':'.$udom})) {
                   11363:                             next;
                   11364:                         }
                   11365:                     }
1.503     raeburn  11366:                     if ($end > 0 && $end < $now) {
1.439     raeburn  11367:                         $status = 'previous';
                   11368:                     } elsif ($start > $now) {
                   11369:                         $status = 'future';
                   11370:                     } else {
                   11371:                         $status = 'active';
                   11372:                     }
1.277     albertel 11373:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  11374:                         if ($status eq $type) {
1.420     albertel 11375:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  11376:                                 push(@{$$users{$role}{$user}},$type);
                   11377:                             }
1.288     raeburn  11378:                             $match = 1;
                   11379:                         }
                   11380:                     }
1.419     raeburn  11381:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   11382:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   11383: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   11384:                         }
1.420     albertel 11385:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  11386:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   11387:                         }
1.609     raeburn  11388:                         if (ref($statushash) eq 'HASH') {
                   11389:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   11390:                         }
1.275     raeburn  11391:                     }
                   11392:                 }
                   11393:             }
                   11394:         }
1.290     albertel 11395:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  11396:             if ((defined($cdom)) && (defined($cnum))) {
                   11397:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   11398:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   11399:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  11400:                     next if ($owner eq '');
                   11401:                     my ($ownername,$ownerdom);
                   11402:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   11403:                         $ownername = $1;
                   11404:                         $ownerdom = $2;
                   11405:                     } else {
                   11406:                         $ownername = $owner;
                   11407:                         $ownerdom = $cdom;
                   11408:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  11409:                     }
                   11410:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 11411:                     if (defined($userdata) && 
1.609     raeburn  11412: 			!exists($$userdata{$owner})) {
                   11413: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   11414:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   11415:                             push(@{$seclists{$owner}},'none');
                   11416:                         }
                   11417:                         if (ref($statushash) eq 'HASH') {
                   11418:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  11419:                         }
1.290     albertel 11420: 		    }
1.279     raeburn  11421:                 }
                   11422:             }
                   11423:         }
1.419     raeburn  11424:         foreach my $user (keys(%seclists)) {
                   11425:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   11426:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   11427:         }
1.275     raeburn  11428:     }
                   11429:     return;
                   11430: }
                   11431: 
1.288     raeburn  11432: sub get_user_info {
                   11433:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 11434:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   11435: 	&plainname($uname,$udom,'lastname');
1.291     albertel 11436:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  11437:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  11438:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   11439:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  11440:     return;
                   11441: }
1.275     raeburn  11442: 
1.472     raeburn  11443: ###############################################
                   11444: 
                   11445: =pod
                   11446: 
                   11447: =item * &get_user_quota()
                   11448: 
1.1134    raeburn  11449: Retrieves quota assigned for storage of user files.
                   11450: Default is to report quota for portfolio files.
1.472     raeburn  11451: 
                   11452: Incoming parameters:
                   11453: 1. user's username
                   11454: 2. user's domain
1.1134    raeburn  11455: 3. quota name - portfolio, author, or course
1.1136    raeburn  11456:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  11457: 4. crstype - official, unofficial, textbook, placement or community, 
                   11458:    if quota name is course
1.472     raeburn  11459: 
                   11460: Returns:
1.1163    raeburn  11461: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  11462: 2. (Optional) Type of setting: custom or default
                   11463:    (individually assigned or default for user's 
                   11464:    institutional status).
                   11465: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   11466:    or student - types as defined in localenroll::inst_usertypes 
                   11467:    for user's domain, which determines default quota for user.
                   11468: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  11469: 
                   11470: If a value has been stored in the user's environment, 
1.536     raeburn  11471: it will return that, otherwise it returns the maximal default
1.1134    raeburn  11472: defined for the user's institutional status(es) in the domain.
1.472     raeburn  11473: 
                   11474: =cut
                   11475: 
                   11476: ###############################################
                   11477: 
                   11478: 
                   11479: sub get_user_quota {
1.1136    raeburn  11480:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  11481:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  11482:     if (!defined($udom)) {
                   11483:         $udom = $env{'user.domain'};
                   11484:     }
                   11485:     if (!defined($uname)) {
                   11486:         $uname = $env{'user.name'};
                   11487:     }
                   11488:     if (($udom eq '' || $uname eq '') ||
                   11489:         ($udom eq 'public') && ($uname eq 'public')) {
                   11490:         $quota = 0;
1.536     raeburn  11491:         $quotatype = 'default';
                   11492:         $defquota = 0; 
1.472     raeburn  11493:     } else {
1.536     raeburn  11494:         my $inststatus;
1.1134    raeburn  11495:         if ($quotaname eq 'course') {
                   11496:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   11497:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   11498:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   11499:             } else {
                   11500:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   11501:                 $quota = $cenv{'internal.uploadquota'};
                   11502:             }
1.536     raeburn  11503:         } else {
1.1134    raeburn  11504:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   11505:                 if ($quotaname eq 'author') {
                   11506:                     $quota = $env{'environment.authorquota'};
                   11507:                 } else {
                   11508:                     $quota = $env{'environment.portfolioquota'};
                   11509:                 }
                   11510:                 $inststatus = $env{'environment.inststatus'};
                   11511:             } else {
                   11512:                 my %userenv = 
                   11513:                     &Apache::lonnet::get('environment',['portfolioquota',
                   11514:                                          'authorquota','inststatus'],$udom,$uname);
                   11515:                 my ($tmp) = keys(%userenv);
                   11516:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   11517:                     if ($quotaname eq 'author') {
                   11518:                         $quota = $userenv{'authorquota'};
                   11519:                     } else {
                   11520:                         $quota = $userenv{'portfolioquota'};
                   11521:                     }
                   11522:                     $inststatus = $userenv{'inststatus'};
                   11523:                 } else {
                   11524:                     undef(%userenv);
                   11525:                 }
                   11526:             }
                   11527:         }
                   11528:         if ($quota eq '' || wantarray) {
                   11529:             if ($quotaname eq 'course') {
                   11530:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  11531:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  11532:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   11533:                     ($crstype eq 'placement')) { 
1.1136    raeburn  11534:                     $defquota = $domdefs{$crstype.'quota'};
                   11535:                 }
                   11536:                 if ($defquota eq '') {
                   11537:                     $defquota = 500;
                   11538:                 }
1.1134    raeburn  11539:             } else {
                   11540:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   11541:             }
                   11542:             if ($quota eq '') {
                   11543:                 $quota = $defquota;
                   11544:                 $quotatype = 'default';
                   11545:             } else {
                   11546:                 $quotatype = 'custom';
                   11547:             }
1.472     raeburn  11548:         }
                   11549:     }
1.536     raeburn  11550:     if (wantarray) {
                   11551:         return ($quota,$quotatype,$settingstatus,$defquota);
                   11552:     } else {
                   11553:         return $quota;
                   11554:     }
1.472     raeburn  11555: }
                   11556: 
                   11557: ###############################################
                   11558: 
                   11559: =pod
                   11560: 
                   11561: =item * &default_quota()
                   11562: 
1.536     raeburn  11563: Retrieves default quota assigned for storage of user portfolio files,
                   11564: given an (optional) user's institutional status.
1.472     raeburn  11565: 
                   11566: Incoming parameters:
1.1142    raeburn  11567: 
1.472     raeburn  11568: 1. domain
1.536     raeburn  11569: 2. (Optional) institutional status(es).  This is a : separated list of 
                   11570:    status types (e.g., faculty, staff, student etc.)
                   11571:    which apply to the user for whom the default is being retrieved.
                   11572:    If the institutional status string in undefined, the domain
1.1134    raeburn  11573:    default quota will be returned.
                   11574: 3.  quota name - portfolio, author, or course
                   11575:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  11576: 
                   11577: Returns:
1.1142    raeburn  11578: 
1.1163    raeburn  11579: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  11580: 2. (Optional) institutional type which determined the value of the
                   11581:    default quota.
1.472     raeburn  11582: 
                   11583: If a value has been stored in the domain's configuration db,
                   11584: it will return that, otherwise it returns 20 (for backwards 
                   11585: compatibility with domains which have not set up a configuration
1.1163    raeburn  11586: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  11587: 
1.536     raeburn  11588: If the user's status includes multiple types (e.g., staff and student),
                   11589: the largest default quota which applies to the user determines the
                   11590: default quota returned.
                   11591: 
1.472     raeburn  11592: =cut
                   11593: 
                   11594: ###############################################
                   11595: 
                   11596: 
                   11597: sub default_quota {
1.1134    raeburn  11598:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  11599:     my ($defquota,$settingstatus);
                   11600:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  11601:                                             ['quotas'],$udom);
1.1134    raeburn  11602:     my $key = 'defaultquota';
                   11603:     if ($quotaname eq 'author') {
                   11604:         $key = 'authorquota';
                   11605:     }
1.622     raeburn  11606:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  11607:         if ($inststatus ne '') {
1.765     raeburn  11608:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  11609:             foreach my $item (@statuses) {
1.1134    raeburn  11610:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11611:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  11612:                         if ($defquota eq '') {
1.1134    raeburn  11613:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11614:                             $settingstatus = $item;
1.1134    raeburn  11615:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11616:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11617:                             $settingstatus = $item;
                   11618:                         }
                   11619:                     }
1.1134    raeburn  11620:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11621:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11622:                         if ($defquota eq '') {
                   11623:                             $defquota = $quotahash{'quotas'}{$item};
                   11624:                             $settingstatus = $item;
                   11625:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11626:                             $defquota = $quotahash{'quotas'}{$item};
                   11627:                             $settingstatus = $item;
                   11628:                         }
1.536     raeburn  11629:                     }
                   11630:                 }
                   11631:             }
                   11632:         }
                   11633:         if ($defquota eq '') {
1.1134    raeburn  11634:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11635:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11636:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11637:                 $defquota = $quotahash{'quotas'}{'default'};
                   11638:             }
1.536     raeburn  11639:             $settingstatus = 'default';
1.1139    raeburn  11640:             if ($defquota eq '') {
                   11641:                 if ($quotaname eq 'author') {
                   11642:                     $defquota = 500;
                   11643:                 }
                   11644:             }
1.536     raeburn  11645:         }
                   11646:     } else {
                   11647:         $settingstatus = 'default';
1.1134    raeburn  11648:         if ($quotaname eq 'author') {
                   11649:             $defquota = 500;
                   11650:         } else {
                   11651:             $defquota = 20;
                   11652:         }
1.536     raeburn  11653:     }
                   11654:     if (wantarray) {
                   11655:         return ($defquota,$settingstatus);
1.472     raeburn  11656:     } else {
1.536     raeburn  11657:         return $defquota;
1.472     raeburn  11658:     }
                   11659: }
                   11660: 
1.1135    raeburn  11661: ###############################################
                   11662: 
                   11663: =pod
                   11664: 
1.1136    raeburn  11665: =item * &excess_filesize_warning()
1.1135    raeburn  11666: 
                   11667: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  11668: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  11669: space to be exceeded.
1.1136    raeburn  11670: 
                   11671: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  11672: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  11673: 
1.1165    raeburn  11674: Inputs: 7 
1.1136    raeburn  11675: 1. username or coursenum
1.1135    raeburn  11676: 2. domain
1.1136    raeburn  11677: 3. context ('author' or 'course')
1.1135    raeburn  11678: 4. filename of file for which action is being requested
                   11679: 5. filesize (kB) of file
                   11680: 6. action being taken: copy or upload.
1.1237    raeburn  11681: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  11682: 
                   11683: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  11684:          otherwise return null.
                   11685: 
                   11686: =back
1.1135    raeburn  11687: 
                   11688: =cut
                   11689: 
1.1136    raeburn  11690: sub excess_filesize_warning {
1.1165    raeburn  11691:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  11692:     my $current_disk_usage = 0;
1.1165    raeburn  11693:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  11694:     if ($context eq 'author') {
                   11695:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11696:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11697:     } else {
                   11698:         foreach my $subdir ('docs','supplemental') {
                   11699:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11700:         }
                   11701:     }
1.1135    raeburn  11702:     $disk_quota = int($disk_quota * 1000);
                   11703:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11704:         return '<p class="LC_warning">'.
1.1135    raeburn  11705:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11706:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11707:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11708:                             $disk_quota,$current_disk_usage).
                   11709:                '</p>';
                   11710:     }
                   11711:     return;
                   11712: }
                   11713: 
                   11714: ###############################################
                   11715: 
                   11716: 
1.1136    raeburn  11717: 
                   11718: 
1.384     raeburn  11719: sub get_secgrprole_info {
                   11720:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11721:     my %sections_count = &get_sections($cdom,$cnum);
                   11722:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11723:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11724:     my @groups = sort(keys(%curr_groups));
                   11725:     my $allroles = [];
                   11726:     my $rolehash;
                   11727:     my $accesshash = {
                   11728:                      active => 'Currently has access',
                   11729:                      future => 'Will have future access',
                   11730:                      previous => 'Previously had access',
                   11731:                   };
                   11732:     if ($needroles) {
                   11733:         $rolehash = {'all' => 'all'};
1.385     albertel 11734:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11735: 	if (&Apache::lonnet::error(%user_roles)) {
                   11736: 	    undef(%user_roles);
                   11737: 	}
                   11738:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11739:             my ($role)=split(/\:/,$item,2);
                   11740:             if ($role eq 'cr') { next; }
                   11741:             if ($role =~ /^cr/) {
                   11742:                 $$rolehash{$role} = (split('/',$role))[3];
                   11743:             } else {
                   11744:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11745:             }
                   11746:         }
                   11747:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11748:             push(@{$allroles},$key);
                   11749:         }
                   11750:         push (@{$allroles},'st');
                   11751:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11752:     }
                   11753:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11754: }
                   11755: 
1.555     raeburn  11756: sub user_picker {
1.1279    raeburn  11757:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11758:     my $currdom = $dom;
1.1253    raeburn  11759:     my @alldoms = &Apache::lonnet::all_domains();
                   11760:     if (@alldoms == 1) {
                   11761:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11762:                                                ['directorysrch'],$alldoms[0]);
                   11763:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11764:         my $showdom = $domdesc;
                   11765:         if ($showdom eq '') {
                   11766:             $showdom = $dom;
                   11767:         }
                   11768:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11769:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11770:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11771:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11772:             }
                   11773:         }
                   11774:     }
1.555     raeburn  11775:     my %curr_selected = (
                   11776:                         srchin => 'dom',
1.580     raeburn  11777:                         srchby => 'lastname',
1.555     raeburn  11778:                       );
                   11779:     my $srchterm;
1.625     raeburn  11780:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11781:         if ($srch->{'srchby'} ne '') {
                   11782:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11783:         }
                   11784:         if ($srch->{'srchin'} ne '') {
                   11785:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11786:         }
                   11787:         if ($srch->{'srchtype'} ne '') {
                   11788:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11789:         }
                   11790:         if ($srch->{'srchdomain'} ne '') {
                   11791:             $currdom = $srch->{'srchdomain'};
                   11792:         }
                   11793:         $srchterm = $srch->{'srchterm'};
                   11794:     }
1.1222    damieng  11795:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11796:                     'usr'       => 'Search criteria',
1.563     raeburn  11797:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11798:                     'uname'     => 'username',
                   11799:                     'lastname'  => 'last name',
1.555     raeburn  11800:                     'lastfirst' => 'last name, first name',
1.558     albertel 11801:                     'crs'       => 'in this course',
1.576     raeburn  11802:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11803:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11804:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11805:                     'exact'     => 'is',
                   11806:                     'contains'  => 'contains',
1.569     raeburn  11807:                     'begins'    => 'begins with',
1.1222    damieng  11808:                                        );
                   11809:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11810:                     'youm'      => "You must include some text to search for.",
                   11811:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11812:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11813:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11814:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11815:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11816:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11817:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11818:                                        );
1.1222    damieng  11819:     &html_escape(\%html_lt);
                   11820:     &js_escape(\%js_lt);
1.1255    raeburn  11821:     my $domform;
1.1277    raeburn  11822:     my $allow_blank = 1;
1.1255    raeburn  11823:     if ($fixeddom) {
1.1277    raeburn  11824:         $allow_blank = 0;
                   11825:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11826:     } else {
1.1287    raeburn  11827:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11828:         my ($trusted,$untrusted);
1.1287    raeburn  11829:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11830:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11831:         } elsif ($context eq 'author') {
1.1288    raeburn  11832:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11833:         } elsif ($context eq 'domain') {
1.1288    raeburn  11834:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11835:         }
1.1288    raeburn  11836:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11837:     }
1.563     raeburn  11838:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11839: 
                   11840:     my @srchins = ('crs','dom','alc','instd');
                   11841: 
                   11842:     foreach my $option (@srchins) {
                   11843:         # FIXME 'alc' option unavailable until 
                   11844:         #       loncreateuser::print_user_query_page()
                   11845:         #       has been completed.
                   11846:         next if ($option eq 'alc');
1.880     raeburn  11847:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11848:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11849:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11850:         if ($curr_selected{'srchin'} eq $option) {
                   11851:             $srchinsel .= ' 
1.1222    damieng  11852:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11853:         } else {
                   11854:             $srchinsel .= '
1.1222    damieng  11855:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11856:         }
1.555     raeburn  11857:     }
1.563     raeburn  11858:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11859: 
                   11860:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11861:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11862:         if ($curr_selected{'srchby'} eq $option) {
                   11863:             $srchbysel .= '
1.1222    damieng  11864:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11865:         } else {
                   11866:             $srchbysel .= '
1.1222    damieng  11867:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11868:          }
                   11869:     }
                   11870:     $srchbysel .= "\n  </select>\n";
                   11871: 
                   11872:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11873:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11874:         if ($curr_selected{'srchtype'} eq $option) {
                   11875:             $srchtypesel .= '
1.1222    damieng  11876:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11877:         } else {
                   11878:             $srchtypesel .= '
1.1222    damieng  11879:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11880:         }
                   11881:     }
                   11882:     $srchtypesel .= "\n  </select>\n";
                   11883: 
1.558     albertel 11884:     my ($newuserscript,$new_user_create);
1.994     raeburn  11885:     my $context_dom = $env{'request.role.domain'};
                   11886:     if ($context eq 'requestcrs') {
                   11887:         if ($env{'form.coursedom'} ne '') { 
                   11888:             $context_dom = $env{'form.coursedom'};
                   11889:         }
                   11890:     }
1.556     raeburn  11891:     if ($forcenewuser) {
1.576     raeburn  11892:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11893:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11894:                 if ($cancreate) {
                   11895:                     $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>';
                   11896:                 } else {
1.799     bisitz   11897:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11898:                     my %usertypetext = (
                   11899:                         official   => 'institutional',
                   11900:                         unofficial => 'non-institutional',
                   11901:                     );
1.799     bisitz   11902:                     $new_user_create = '<p class="LC_warning">'
                   11903:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11904:                                       .' '
                   11905:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11906:                                           ,'<a href="'.$helplink.'">','</a>')
                   11907:                                       .'</p><br />';
1.627     raeburn  11908:                 }
1.576     raeburn  11909:             }
                   11910:         }
                   11911: 
1.556     raeburn  11912:         $newuserscript = <<"ENDSCRIPT";
                   11913: 
1.570     raeburn  11914: function setSearch(createnew,callingForm) {
1.556     raeburn  11915:     if (createnew == 1) {
1.570     raeburn  11916:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11917:             if (callingForm.srchby.options[i].value == 'uname') {
                   11918:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11919:             }
                   11920:         }
1.570     raeburn  11921:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11922:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11923: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11924:             }
                   11925:         }
1.570     raeburn  11926:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11927:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11928:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11929:             }
                   11930:         }
1.570     raeburn  11931:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11932:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11933:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11934:             }
                   11935:         }
                   11936:     }
                   11937: }
                   11938: ENDSCRIPT
1.558     albertel 11939: 
1.556     raeburn  11940:     }
                   11941: 
1.555     raeburn  11942:     my $output = <<"END_BLOCK";
1.556     raeburn  11943: <script type="text/javascript">
1.824     bisitz   11944: // <![CDATA[
1.570     raeburn  11945: function validateEntry(callingForm) {
1.558     albertel 11946: 
1.556     raeburn  11947:     var checkok = 1;
1.558     albertel 11948:     var srchin;
1.570     raeburn  11949:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11950: 	if ( callingForm.srchin[i].checked ) {
                   11951: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11952: 	}
                   11953:     }
                   11954: 
1.570     raeburn  11955:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11956:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11957:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11958:     var srchterm =  callingForm.srchterm.value;
                   11959:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11960:     var msg = "";
                   11961: 
                   11962:     if (srchterm == "") {
                   11963:         checkok = 0;
1.1222    damieng  11964:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11965:     }
                   11966: 
1.569     raeburn  11967:     if (srchtype== 'begins') {
                   11968:         if (srchterm.length < 2) {
                   11969:             checkok = 0;
1.1222    damieng  11970:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11971:         }
                   11972:     }
                   11973: 
1.556     raeburn  11974:     if (srchtype== 'contains') {
                   11975:         if (srchterm.length < 3) {
                   11976:             checkok = 0;
1.1222    damieng  11977:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11978:         }
                   11979:     }
                   11980:     if (srchin == 'instd') {
                   11981:         if (srchdomain == '') {
                   11982:             checkok = 0;
1.1222    damieng  11983:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11984:         }
                   11985:     }
                   11986:     if (srchin == 'dom') {
                   11987:         if (srchdomain == '') {
                   11988:             checkok = 0;
1.1222    damieng  11989:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11990:         }
                   11991:     }
                   11992:     if (srchby == 'lastfirst') {
                   11993:         if (srchterm.indexOf(",") == -1) {
                   11994:             checkok = 0;
1.1222    damieng  11995:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11996:         }
                   11997:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11998:             checkok = 0;
1.1222    damieng  11999:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  12000:         }
                   12001:     }
                   12002:     if (checkok == 0) {
1.1222    damieng  12003:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  12004:         return;
                   12005:     }
                   12006:     if (checkok == 1) {
1.570     raeburn  12007:         callingForm.submit();
1.556     raeburn  12008:     }
                   12009: }
                   12010: 
                   12011: $newuserscript
                   12012: 
1.824     bisitz   12013: // ]]>
1.556     raeburn  12014: </script>
1.558     albertel 12015: 
                   12016: $new_user_create
                   12017: 
1.555     raeburn  12018: END_BLOCK
1.558     albertel 12019: 
1.876     raeburn  12020:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  12021:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  12022:                $domform.
                   12023:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  12024:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  12025:                $srchbysel.
                   12026:                $srchtypesel. 
                   12027:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   12028:                $srchinsel.
                   12029:                &Apache::lonhtmlcommon::row_closure(1). 
                   12030:                &Apache::lonhtmlcommon::end_pick_box().
                   12031:                '<br />';
1.1253    raeburn  12032:     return ($output,1);
1.555     raeburn  12033: }
                   12034: 
1.612     raeburn  12035: sub user_rule_check {
1.615     raeburn  12036:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  12037:     my ($response,%inst_response);
1.612     raeburn  12038:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  12039:         if (keys(%{$usershash}) > 1) {
                   12040:             my (%by_username,%by_id,%userdoms);
                   12041:             my $checkid; 
                   12042:             if (ref($checks) eq 'HASH') {
                   12043:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   12044:                     $checkid = 1;
                   12045:                 }
                   12046:             }
                   12047:             foreach my $user (keys(%{$usershash})) {
                   12048:                 my ($uname,$udom) = split(/:/,$user);
                   12049:                 if ($checkid) {
                   12050:                     if (ref($usershash->{$user}) eq 'HASH') {
                   12051:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  12052:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  12053:                             $userdoms{$udom} = 1;
1.1227    raeburn  12054:                             if (ref($inst_results) eq 'HASH') {
                   12055:                                 $inst_results->{$uname.':'.$udom} = {};
                   12056:                             }
1.1226    raeburn  12057:                         }
                   12058:                     }
                   12059:                 } else {
                   12060:                     $by_username{$udom}{$uname} = 1;
                   12061:                     $userdoms{$udom} = 1;
1.1227    raeburn  12062:                     if (ref($inst_results) eq 'HASH') {
                   12063:                         $inst_results->{$uname.':'.$udom} = {};
                   12064:                     }
1.1226    raeburn  12065:                 }
                   12066:             }
                   12067:             foreach my $udom (keys(%userdoms)) {
                   12068:                 if (!$got_rules->{$udom}) {
                   12069:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12070:                                                              ['usercreation'],$udom);
                   12071:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12072:                         foreach my $item ('username','id') {
                   12073:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  12074:                                 $$curr_rules{$udom}{$item} =
                   12075:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  12076:                             }
                   12077:                         }
                   12078:                     }
                   12079:                     $got_rules->{$udom} = 1;
                   12080:                 }
1.612     raeburn  12081:             }
1.1226    raeburn  12082:             if ($checkid) {
                   12083:                 foreach my $udom (keys(%by_id)) {
                   12084:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   12085:                     if ($outcome eq 'ok') {
1.1227    raeburn  12086:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   12087:                             my $uname = $by_id{$udom}{$id};
                   12088:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12089:                         }
1.1226    raeburn  12090:                         if (ref($results) eq 'HASH') {
                   12091:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  12092:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   12093:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   12094:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12095:                                 }
1.1226    raeburn  12096:                             }
                   12097:                         }
                   12098:                     }
1.612     raeburn  12099:                 }
1.615     raeburn  12100:             } else {
1.1226    raeburn  12101:                 foreach my $udom (keys(%by_username)) {
                   12102:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   12103:                     if ($outcome eq 'ok') {
1.1227    raeburn  12104:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   12105:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12106:                         }
1.1226    raeburn  12107:                         if (ref($results) eq 'HASH') {
                   12108:                             foreach my $uname (keys(%{$results})) {
                   12109:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12110:                             }
                   12111:                         }
                   12112:                     }
                   12113:                 }
1.612     raeburn  12114:             }
1.1226    raeburn  12115:         } elsif (keys(%{$usershash}) == 1) {
                   12116:             my $user = (keys(%{$usershash}))[0];
                   12117:             my ($uname,$udom) = split(/:/,$user);
                   12118:             if (($udom ne '') && ($uname ne '')) {
                   12119:                 if (ref($usershash->{$user}) eq 'HASH') {
                   12120:                     if (ref($checks) eq 'HASH') {
                   12121:                         if (defined($checks->{'username'})) {
                   12122:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   12123:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   12124:                         } elsif (defined($checks->{'id'})) {
                   12125:                             if ($usershash->{$user}->{'id'} ne '') {
                   12126:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12127:                                     &Apache::lonnet::get_instuser($udom,undef,
                   12128:                                                                   $usershash->{$user}->{'id'});
                   12129:                             } else {
                   12130:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12131:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   12132:                             }
1.585     raeburn  12133:                         }
1.1226    raeburn  12134:                     } else {
                   12135:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   12136:                             &Apache::lonnet::get_instuser($udom,$uname);
                   12137:                        return;
                   12138:                     }
                   12139:                     if (!$got_rules->{$udom}) {
                   12140:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12141:                                                                  ['usercreation'],$udom);
                   12142:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12143:                             foreach my $item ('username','id') {
                   12144:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   12145:                                    $$curr_rules{$udom}{$item} = 
                   12146:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   12147:                                 }
                   12148:                             }
                   12149:                         }
                   12150:                         $got_rules->{$udom} = 1;
1.585     raeburn  12151:                     }
                   12152:                 }
1.1226    raeburn  12153:             } else {
                   12154:                 return;
                   12155:             }
                   12156:         } else {
                   12157:             return;
                   12158:         }
                   12159:         foreach my $user (keys(%{$usershash})) {
                   12160:             my ($uname,$udom) = split(/:/,$user);
                   12161:             next if (($udom eq '') || ($uname eq ''));
                   12162:             my $id;
1.1227    raeburn  12163:             if (ref($inst_results) eq 'HASH') {
                   12164:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   12165:                     $id = $inst_results->{$user}->{'id'};
                   12166:                 }
                   12167:             }
                   12168:             if ($id eq '') { 
                   12169:                 if (ref($usershash->{$user})) {
                   12170:                     $id = $usershash->{$user}->{'id'};
                   12171:                 }
1.585     raeburn  12172:             }
1.612     raeburn  12173:             foreach my $item (keys(%{$checks})) {
                   12174:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   12175:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   12176:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  12177:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   12178:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  12179:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   12180:                                 if ($rule_check{$rule}) {
                   12181:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  12182:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  12183:                                         if (ref($inst_results) eq 'HASH') {
                   12184:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   12185:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   12186:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  12187:                                                 } elsif ($item eq 'id') {
                   12188:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   12189:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   12190:                                                     }
1.615     raeburn  12191:                                                 }
1.612     raeburn  12192:                                             }
                   12193:                                         }
1.615     raeburn  12194:                                     }
                   12195:                                     last;
1.585     raeburn  12196:                                 }
                   12197:                             }
                   12198:                         }
                   12199:                     }
                   12200:                 }
                   12201:             }
                   12202:         }
                   12203:     }
1.612     raeburn  12204:     return;
                   12205: }
                   12206: 
                   12207: sub user_rule_formats {
                   12208:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   12209:     my %text = ( 
                   12210:                  'username' => 'Usernames',
                   12211:                  'id'       => 'IDs',
                   12212:                );
                   12213:     my $output;
                   12214:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   12215:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   12216:         if (@{$ruleorder} > 0) {
1.1102    raeburn  12217:             $output = '<br />'.
                   12218:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   12219:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   12220:                       ' <ul>';
1.612     raeburn  12221:             foreach my $rule (@{$ruleorder}) {
                   12222:                 if (ref($curr_rules) eq 'ARRAY') {
                   12223:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   12224:                         if (ref($rules->{$rule}) eq 'HASH') {
                   12225:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   12226:                                         $rules->{$rule}{'desc'}.'</li>';
                   12227:                         }
                   12228:                     }
                   12229:                 }
                   12230:             }
                   12231:             $output .= '</ul>';
                   12232:         }
                   12233:     }
                   12234:     return $output;
                   12235: }
                   12236: 
                   12237: sub instrule_disallow_msg {
1.615     raeburn  12238:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  12239:     my $response;
                   12240:     my %text = (
                   12241:                   item   => 'username',
                   12242:                   items  => 'usernames',
                   12243:                   match  => 'matches',
                   12244:                   do     => 'does',
                   12245:                   action => 'a username',
                   12246:                   one    => 'one',
                   12247:                );
                   12248:     if ($count > 1) {
                   12249:         $text{'item'} = 'usernames';
                   12250:         $text{'match'} ='match';
                   12251:         $text{'do'} = 'do';
                   12252:         $text{'action'} = 'usernames',
                   12253:         $text{'one'} = 'ones';
                   12254:     }
                   12255:     if ($checkitem eq 'id') {
                   12256:         $text{'items'} = 'IDs';
                   12257:         $text{'item'} = 'ID';
                   12258:         $text{'action'} = 'an ID';
1.615     raeburn  12259:         if ($count > 1) {
                   12260:             $text{'item'} = 'IDs';
                   12261:             $text{'action'} = 'IDs';
                   12262:         }
1.612     raeburn  12263:     }
1.674     bisitz   12264:     $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  12265:     if ($mode eq 'upload') {
                   12266:         if ($checkitem eq 'username') {
                   12267:             $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'}.");
                   12268:         } elsif ($checkitem eq 'id') {
1.674     bisitz   12269:             $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  12270:         }
1.669     raeburn  12271:     } elsif ($mode eq 'selfcreate') {
                   12272:         if ($checkitem eq 'id') {
                   12273:             $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.");
                   12274:         }
1.615     raeburn  12275:     } else {
                   12276:         if ($checkitem eq 'username') {
                   12277:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   12278:         } elsif ($checkitem eq 'id') {
                   12279:             $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.");
                   12280:         }
1.612     raeburn  12281:     }
                   12282:     return $response;
1.585     raeburn  12283: }
                   12284: 
1.624     raeburn  12285: sub personal_data_fieldtitles {
                   12286:     my %fieldtitles = &Apache::lonlocal::texthash (
                   12287:                         id => 'Student/Employee ID',
                   12288:                         permanentemail => 'E-mail address',
                   12289:                         lastname => 'Last Name',
                   12290:                         firstname => 'First Name',
                   12291:                         middlename => 'Middle Name',
                   12292:                         generation => 'Generation',
                   12293:                         gen => 'Generation',
1.765     raeburn  12294:                         inststatus => 'Affiliation',
1.624     raeburn  12295:                    );
                   12296:     return %fieldtitles;
                   12297: }
                   12298: 
1.642     raeburn  12299: sub sorted_inst_types {
                   12300:     my ($dom) = @_;
1.1185    raeburn  12301:     my ($usertypes,$order);
                   12302:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   12303:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   12304:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   12305:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   12306:     } else {
                   12307:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   12308:     }
1.642     raeburn  12309:     my $othertitle = &mt('All users');
                   12310:     if ($env{'request.course.id'}) {
1.668     raeburn  12311:         $othertitle  = &mt('Any users');
1.642     raeburn  12312:     }
                   12313:     my @types;
                   12314:     if (ref($order) eq 'ARRAY') {
                   12315:         @types = @{$order};
                   12316:     }
                   12317:     if (@types == 0) {
                   12318:         if (ref($usertypes) eq 'HASH') {
                   12319:             @types = sort(keys(%{$usertypes}));
                   12320:         }
                   12321:     }
                   12322:     if (keys(%{$usertypes}) > 0) {
                   12323:         $othertitle = &mt('Other users');
                   12324:     }
                   12325:     return ($othertitle,$usertypes,\@types);
                   12326: }
                   12327: 
1.645     raeburn  12328: sub get_institutional_codes {
1.1361    raeburn  12329:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  12330: # Get complete list of course sections to update
                   12331:     my @currsections = ();
                   12332:     my @currxlists = ();
1.1361    raeburn  12333:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  12334:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  12335:     my $crskey = $crs.':'.$coursecode;
                   12336:     @{$unclutteredsec{$crskey}} = ();
                   12337:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  12338: 
                   12339:     if ($$settings{'internal.sectionnums'} ne '') {
                   12340:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   12341:     }
                   12342: 
                   12343:     if ($$settings{'internal.crosslistings'} ne '') {
                   12344:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   12345:     }
                   12346: 
                   12347:     if (@currxlists > 0) {
1.1361    raeburn  12348:         foreach my $xl (@currxlists) {
                   12349:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  12350:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  12351:                     push(@{$allcourses},$1);
1.645     raeburn  12352:                     $$LC_code{$1} = $2;
                   12353:                 }
                   12354:             }
                   12355:         }
                   12356:     }
1.1361    raeburn  12357: 
1.645     raeburn  12358:     if (@currsections > 0) {
1.1361    raeburn  12359:         foreach my $sec (@currsections) {
                   12360:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   12361:                 my $instsec = $1;
1.645     raeburn  12362:                 my $lc_sec = $2;
1.1361    raeburn  12363:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   12364:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   12365:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   12366:                 }
                   12367:             }
                   12368:         }
                   12369:     }
                   12370: 
                   12371:     if (@{$unclutteredsec{$crskey}} > 0) {
                   12372:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   12373:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   12374:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   12375:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   12376:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  12377:                     push(@{$allcourses},$sec);
1.1361    raeburn  12378:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  12379:                 }
                   12380:             }
                   12381:         }
                   12382:     }
                   12383:     return;
                   12384: }
                   12385: 
1.971     raeburn  12386: sub get_standard_codeitems {
                   12387:     return ('Year','Semester','Department','Number','Section');
                   12388: }
                   12389: 
1.112     bowersj2 12390: =pod
                   12391: 
1.780     raeburn  12392: =head1 Slot Helpers
                   12393: 
                   12394: =over 4
                   12395: 
                   12396: =item * sorted_slots()
                   12397: 
1.1040    raeburn  12398: Sorts an array of slot names in order of an optional sort key,
                   12399: default sort is by slot start time (earliest first). 
1.780     raeburn  12400: 
                   12401: Inputs:
                   12402: 
                   12403: =over 4
                   12404: 
                   12405: slotsarr  - Reference to array of unsorted slot names.
                   12406: 
                   12407: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   12408: 
1.1040    raeburn  12409: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   12410: 
1.549     albertel 12411: =back
                   12412: 
1.780     raeburn  12413: Returns:
                   12414: 
                   12415: =over 4
                   12416: 
1.1040    raeburn  12417: sorted   - An array of slot names sorted by a specified sort key 
                   12418:            (default sort key is start time of the slot).
1.780     raeburn  12419: 
                   12420: =back
                   12421: 
                   12422: =cut
                   12423: 
                   12424: 
                   12425: sub sorted_slots {
1.1040    raeburn  12426:     my ($slotsarr,$slots,$sortkey) = @_;
                   12427:     if ($sortkey eq '') {
                   12428:         $sortkey = 'starttime';
                   12429:     }
1.780     raeburn  12430:     my @sorted;
                   12431:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   12432:         @sorted =
                   12433:             sort {
                   12434:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  12435:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  12436:                      }
                   12437:                      if (ref($slots->{$a})) { return -1;}
                   12438:                      if (ref($slots->{$b})) { return 1;}
                   12439:                      return 0;
                   12440:                  } @{$slotsarr};
                   12441:     }
                   12442:     return @sorted;
                   12443: }
                   12444: 
1.1040    raeburn  12445: =pod
                   12446: 
                   12447: =item * get_future_slots()
                   12448: 
                   12449: Inputs:
                   12450: 
                   12451: =over 4
                   12452: 
                   12453: cnum - course number
                   12454: 
                   12455: cdom - course domain
                   12456: 
                   12457: now - current UNIX time
                   12458: 
                   12459: symb - optional symb
                   12460: 
                   12461: =back
                   12462: 
                   12463: Returns:
                   12464: 
                   12465: =over 4
                   12466: 
                   12467: sorted_reservable - ref to array of student_schedulable slots currently 
                   12468:                     reservable, ordered by end date of reservation period.
                   12469: 
                   12470: reservable_now - ref to hash of student_schedulable slots currently
                   12471:                  reservable.
                   12472: 
                   12473:     Keys in inner hash are:
                   12474:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12475:     (b) endreserve: end date of reservation period.
                   12476:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12477:         selected.
1.1040    raeburn  12478: 
                   12479: sorted_future - ref to array of student_schedulable slots reservable in
                   12480:                 the future, ordered by start date of reservation period.
                   12481: 
                   12482: future_reservable - ref to hash of student_schedulable slots reservable
                   12483:                     in the future.
                   12484: 
                   12485:     Keys in inner hash are:
                   12486:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12487:     (b) startreserve: start date of reservation period.
                   12488:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12489:         selected.
1.1040    raeburn  12490: 
                   12491: =back
                   12492: 
                   12493: =cut
                   12494: 
                   12495: sub get_future_slots {
                   12496:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  12497:     my $map;
                   12498:     if ($symb) {
                   12499:         ($map) = &Apache::lonnet::decode_symb($symb);
                   12500:     }
1.1040    raeburn  12501:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   12502:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   12503:     foreach my $slot (keys(%slots)) {
                   12504:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   12505:         if ($symb) {
1.1229    raeburn  12506:             if ($slots{$slot}->{'symb'} ne '') {
                   12507:                 my $canuse;
                   12508:                 my %oksymbs;
                   12509:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   12510:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   12511:                 if ($oksymbs{$symb}) {
                   12512:                     $canuse = 1;
                   12513:                 } else {
                   12514:                     foreach my $item (@slotsymbs) {
                   12515:                         if ($item =~ /\.(page|sequence)$/) {
                   12516:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   12517:                             if (($map ne '') && ($map eq $sloturl)) {
                   12518:                                 $canuse = 1;
                   12519:                                 last;
                   12520:                             }
                   12521:                         }
                   12522:                     }
                   12523:                 }
                   12524:                 next unless ($canuse);
                   12525:             }
1.1040    raeburn  12526:         }
                   12527:         if (($slots{$slot}->{'starttime'} > $now) &&
                   12528:             ($slots{$slot}->{'endtime'} > $now)) {
                   12529:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   12530:                 my $userallowed = 0;
                   12531:                 if ($slots{$slot}->{'allowedsections'}) {
                   12532:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   12533:                     if (!defined($env{'request.role.sec'})
                   12534:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   12535:                         $userallowed=1;
                   12536:                     } else {
                   12537:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   12538:                             $userallowed=1;
                   12539:                         }
                   12540:                     }
                   12541:                     unless ($userallowed) {
                   12542:                         if (defined($env{'request.course.groups'})) {
                   12543:                             my @groups = split(/:/,$env{'request.course.groups'});
                   12544:                             foreach my $group (@groups) {
                   12545:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   12546:                                     $userallowed=1;
                   12547:                                     last;
                   12548:                                 }
                   12549:                             }
                   12550:                         }
                   12551:                     }
                   12552:                 }
                   12553:                 if ($slots{$slot}->{'allowedusers'}) {
                   12554:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   12555:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   12556:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   12557:                         $userallowed = 1;
                   12558:                     }
                   12559:                 }
                   12560:                 next unless($userallowed);
                   12561:             }
                   12562:             my $startreserve = $slots{$slot}->{'startreserve'};
                   12563:             my $endreserve = $slots{$slot}->{'endreserve'};
                   12564:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  12565:             my $uniqueperiod;
                   12566:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   12567:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   12568:             }
1.1040    raeburn  12569:             if (($startreserve < $now) &&
                   12570:                 (!$endreserve || $endreserve > $now)) {
                   12571:                 my $lastres = $endreserve;
                   12572:                 if (!$lastres) {
                   12573:                     $lastres = $slots{$slot}->{'starttime'};
                   12574:                 }
                   12575:                 $reservable_now{$slot} = {
                   12576:                                            symb       => $symb,
1.1250    raeburn  12577:                                            endreserve => $lastres,
                   12578:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  12579:                                          };
                   12580:             } elsif (($startreserve > $now) &&
                   12581:                      (!$endreserve || $endreserve > $startreserve)) {
                   12582:                 $future_reservable{$slot} = {
                   12583:                                               symb         => $symb,
1.1250    raeburn  12584:                                               startreserve => $startreserve,
                   12585:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  12586:                                             };
                   12587:             }
                   12588:         }
                   12589:     }
                   12590:     my @unsorted_reservable = keys(%reservable_now);
                   12591:     if (@unsorted_reservable > 0) {
                   12592:         @sorted_reservable = 
                   12593:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   12594:     }
                   12595:     my @unsorted_future = keys(%future_reservable);
                   12596:     if (@unsorted_future > 0) {
                   12597:         @sorted_future =
                   12598:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   12599:     }
                   12600:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   12601: }
1.780     raeburn  12602: 
                   12603: =pod
                   12604: 
1.1057    foxr     12605: =back
                   12606: 
1.549     albertel 12607: =head1 HTTP Helpers
                   12608: 
                   12609: =over 4
                   12610: 
1.648     raeburn  12611: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 12612: 
1.258     albertel 12613: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 12614: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 12615: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 12616: 
                   12617: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   12618: $possible_names is an ref to an array of form element names.  As an example:
                   12619: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 12620: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 12621: 
                   12622: =cut
1.1       albertel 12623: 
1.6       albertel 12624: sub get_unprocessed_cgi {
1.25      albertel 12625:   my ($query,$possible_names)= @_;
1.26      matthew  12626:   # $Apache::lonxml::debug=1;
1.356     albertel 12627:   foreach my $pair (split(/&/,$query)) {
                   12628:     my ($name, $value) = split(/=/,$pair);
1.369     www      12629:     $name = &unescape($name);
1.25      albertel 12630:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   12631:       $value =~ tr/+/ /;
                   12632:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 12633:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 12634:     }
1.16      harris41 12635:   }
1.6       albertel 12636: }
                   12637: 
1.112     bowersj2 12638: =pod
                   12639: 
1.648     raeburn  12640: =item * &cacheheader() 
1.112     bowersj2 12641: 
                   12642: returns cache-controlling header code
                   12643: 
                   12644: =cut
                   12645: 
1.7       albertel 12646: sub cacheheader {
1.258     albertel 12647:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12648:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12649:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12650:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12651:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12652:     return $output;
1.7       albertel 12653: }
                   12654: 
1.112     bowersj2 12655: =pod
                   12656: 
1.648     raeburn  12657: =item * &no_cache($r) 
1.112     bowersj2 12658: 
                   12659: specifies header code to not have cache
                   12660: 
                   12661: =cut
                   12662: 
1.9       albertel 12663: sub no_cache {
1.216     albertel 12664:     my ($r) = @_;
                   12665:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12666: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12667:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12668:     $r->no_cache(1);
                   12669:     $r->header_out("Expires" => $date);
                   12670:     $r->header_out("Pragma" => "no-cache");
1.123     www      12671: }
                   12672: 
                   12673: sub content_type {
1.181     albertel 12674:     my ($r,$type,$charset) = @_;
1.299     foxr     12675:     if ($r) {
                   12676: 	#  Note that printout.pl calls this with undef for $r.
                   12677: 	&no_cache($r);
                   12678:     }
1.258     albertel 12679:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12680:     unless ($charset) {
                   12681: 	$charset=&Apache::lonlocal::current_encoding;
                   12682:     }
                   12683:     if ($charset) { $type.='; charset='.$charset; }
                   12684:     if ($r) {
                   12685: 	$r->content_type($type);
                   12686:     } else {
                   12687: 	print("Content-type: $type\n\n");
                   12688:     }
1.9       albertel 12689: }
1.25      albertel 12690: 
1.112     bowersj2 12691: =pod
                   12692: 
1.648     raeburn  12693: =item * &add_to_env($name,$value) 
1.112     bowersj2 12694: 
1.258     albertel 12695: adds $name to the %env hash with value
1.112     bowersj2 12696: $value, if $name already exists, the entry is converted to an array
                   12697: reference and $value is added to the array.
                   12698: 
                   12699: =cut
                   12700: 
1.25      albertel 12701: sub add_to_env {
                   12702:   my ($name,$value)=@_;
1.258     albertel 12703:   if (defined($env{$name})) {
                   12704:     if (ref($env{$name})) {
1.25      albertel 12705:       #already have multiple values
1.258     albertel 12706:       push(@{ $env{$name} },$value);
1.25      albertel 12707:     } else {
                   12708:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12709:       my $first=$env{$name};
                   12710:       undef($env{$name});
                   12711:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12712:     }
                   12713:   } else {
1.258     albertel 12714:     $env{$name}=$value;
1.25      albertel 12715:   }
1.31      albertel 12716: }
1.149     albertel 12717: 
                   12718: =pod
                   12719: 
1.648     raeburn  12720: =item * &get_env_multiple($name) 
1.149     albertel 12721: 
1.258     albertel 12722: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12723: values may be defined and end up as an array ref.
                   12724: 
                   12725: returns an array of values
                   12726: 
                   12727: =cut
                   12728: 
                   12729: sub get_env_multiple {
                   12730:     my ($name) = @_;
                   12731:     my @values;
1.258     albertel 12732:     if (defined($env{$name})) {
1.149     albertel 12733:         # exists is it an array
1.258     albertel 12734:         if (ref($env{$name})) {
                   12735:             @values=@{ $env{$name} };
1.149     albertel 12736:         } else {
1.258     albertel 12737:             $values[0]=$env{$name};
1.149     albertel 12738:         }
                   12739:     }
                   12740:     return(@values);
                   12741: }
                   12742: 
1.1249    damieng  12743: # Looks at given dependencies, and returns something depending on the context.
                   12744: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12745: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12746: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12747: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12748: # $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.
                   12749: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12750: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12751: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12752: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12753: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12754: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12755: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12756: # @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)
                   12757: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12758: sub ask_for_embedded_content {
1.1249    damieng  12759:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12760:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12761:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12762:         %currsubfile,%unused,$rem);
1.1071    raeburn  12763:     my $counter = 0;
                   12764:     my $numnew = 0;
1.987     raeburn  12765:     my $numremref = 0;
                   12766:     my $numinvalid = 0;
                   12767:     my $numpathchg = 0;
                   12768:     my $numexisting = 0;
1.1071    raeburn  12769:     my $numunused = 0;
                   12770:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12771:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12772:     my $heading = &mt('Upload embedded files');
                   12773:     my $buttontext = &mt('Upload');
                   12774: 
1.1249    damieng  12775:     # fills these variables based on the context:
                   12776:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12777:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12778:     if ($env{'request.course.id'}) {
1.1123    raeburn  12779:         if ($actionurl eq '/adm/dependencies') {
                   12780:             $navmap = Apache::lonnavmaps::navmap->new();
                   12781:         }
                   12782:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12783:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12784:     }
1.1123    raeburn  12785:     if (($actionurl eq '/adm/portfolio') || 
                   12786:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12787:         my $current_path='/';
                   12788:         if ($env{'form.currentpath'}) {
                   12789:             $current_path = $env{'form.currentpath'};
                   12790:         }
                   12791:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12792:             $udom = $cdom;
                   12793:             $uname = $cnum;
1.984     raeburn  12794:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12795:         } else {
                   12796:             $udom = $env{'user.domain'};
                   12797:             $uname = $env{'user.name'};
                   12798:             $url = '/userfiles/portfolio';
                   12799:         }
1.987     raeburn  12800:         $toplevel = $url.'/';
1.984     raeburn  12801:         $url .= $current_path;
                   12802:         $getpropath = 1;
1.987     raeburn  12803:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12804:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12805:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12806:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12807:         $toplevel = $url;
1.984     raeburn  12808:         if ($rest ne '') {
1.987     raeburn  12809:             $url .= $rest;
                   12810:         }
                   12811:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12812:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12813:             $url = $args->{'docs_url'};
                   12814:             $toplevel = $url;
1.1084    raeburn  12815:             if ($args->{'context'} eq 'paste') {
                   12816:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12817:                 ($path) = 
                   12818:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12819:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12820:                 $fileloc =~ s{^/}{};
                   12821:             }
1.1071    raeburn  12822:         }
1.1084    raeburn  12823:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12824:         if ($env{'request.course.id'} ne '') {
                   12825:             if (ref($args) eq 'HASH') {
                   12826:                 $url = $args->{'docs_url'};
                   12827:                 $title = $args->{'docs_title'};
1.1126    raeburn  12828:                 $toplevel = $url; 
                   12829:                 unless ($toplevel =~ m{^/}) {
                   12830:                     $toplevel = "/$url";
                   12831:                 }
1.1085    raeburn  12832:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12833:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12834:                     $path = $1;
                   12835:                 } else {
                   12836:                     ($path) =
                   12837:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12838:                 }
1.1195    raeburn  12839:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12840:                     $fileloc = $toplevel;
                   12841:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12842:                     my ($udom,$uname,$fname) =
                   12843:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12844:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12845:                 } else {
                   12846:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12847:                 }
1.1071    raeburn  12848:                 $fileloc =~ s{^/}{};
                   12849:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12850:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12851:             }
1.987     raeburn  12852:         }
1.1123    raeburn  12853:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12854:         $udom = $cdom;
                   12855:         $uname = $cnum;
                   12856:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12857:         $toplevel = $url;
                   12858:         $path = $url;
                   12859:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12860:         $fileloc =~ s{^/}{};
1.987     raeburn  12861:     }
1.1249    damieng  12862:     
                   12863:     # parses the dependency paths to get some info
                   12864:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12865:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12866:     # (will be completed later)
                   12867:     # $mapping:
                   12868:     #   for external URLs: external URL -> external URL
                   12869:     #   for relative paths: clean path -> original path
                   12870:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12871:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12872:     foreach my $file (keys(%{$allfiles})) {
                   12873:         my $embed_file;
                   12874:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12875:             $embed_file = $1;
                   12876:         } else {
                   12877:             $embed_file = $file;
                   12878:         }
1.1158    raeburn  12879:         my ($absolutepath,$cleaned_file);
                   12880:         if ($embed_file =~ m{^\w+://}) {
                   12881:             $cleaned_file = $embed_file;
1.1147    raeburn  12882:             $newfiles{$cleaned_file} = 1;
                   12883:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12884:         } else {
1.1158    raeburn  12885:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12886:             if ($embed_file =~ m{^/}) {
                   12887:                 $absolutepath = $embed_file;
                   12888:             }
1.1147    raeburn  12889:             if ($cleaned_file =~ m{/}) {
                   12890:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12891:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12892:                 my $item = $fname;
                   12893:                 if ($path ne '') {
                   12894:                     $item = $path.'/'.$fname;
                   12895:                     $subdependencies{$path}{$fname} = 1;
                   12896:                 } else {
                   12897:                     $dependencies{$item} = 1;
                   12898:                 }
                   12899:                 if ($absolutepath) {
                   12900:                     $mapping{$item} = $absolutepath;
                   12901:                 } else {
                   12902:                     $mapping{$item} = $embed_file;
                   12903:                 }
                   12904:             } else {
                   12905:                 $dependencies{$embed_file} = 1;
                   12906:                 if ($absolutepath) {
1.1147    raeburn  12907:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12908:                 } else {
1.1147    raeburn  12909:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12910:                 }
                   12911:             }
1.984     raeburn  12912:         }
                   12913:     }
1.1249    damieng  12914:     
                   12915:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12916:     # and lists
                   12917:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12918:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12919:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12920:     #                                    the path had to be cleaned up
                   12921:     # $existing: hash clean path -> 1 if the file exists
                   12922:     # $numexisting: number of keys in $existing
                   12923:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12924:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12925:     #                                      dependency subdirectories that are
                   12926:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12927:     my $dirptr = 16384;
1.984     raeburn  12928:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12929:         $currsubfile{$path} = {};
1.1123    raeburn  12930:         if (($actionurl eq '/adm/portfolio') || 
                   12931:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12932:             my ($sublistref,$listerror) =
                   12933:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12934:             if (ref($sublistref) eq 'ARRAY') {
                   12935:                 foreach my $line (@{$sublistref}) {
                   12936:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12937:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12938:                 }
1.984     raeburn  12939:             }
1.987     raeburn  12940:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12941:             if (opendir(my $dir,$url.'/'.$path)) {
                   12942:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12943:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12944:             }
1.1084    raeburn  12945:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12946:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12947:                   ($args->{'context'} eq 'paste')) ||
                   12948:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12949:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12950:                 my $dir;
                   12951:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12952:                     $dir = $fileloc;
                   12953:                 } else {
                   12954:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12955:                 }
1.1071    raeburn  12956:                 if ($dir ne '') {
                   12957:                     my ($sublistref,$listerror) =
                   12958:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12959:                     if (ref($sublistref) eq 'ARRAY') {
                   12960:                         foreach my $line (@{$sublistref}) {
                   12961:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12962:                                 undef,$mtime)=split(/\&/,$line,12);
                   12963:                             unless (($testdir&$dirptr) ||
                   12964:                                     ($file_name =~ /^\.\.?$/)) {
                   12965:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12966:                             }
                   12967:                         }
                   12968:                     }
                   12969:                 }
1.984     raeburn  12970:             }
                   12971:         }
                   12972:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12973:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12974:                 my $item = $path.'/'.$file;
                   12975:                 unless ($mapping{$item} eq $item) {
                   12976:                     $pathchanges{$item} = 1;
                   12977:                 }
                   12978:                 $existing{$item} = 1;
                   12979:                 $numexisting ++;
                   12980:             } else {
                   12981:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12982:             }
                   12983:         }
1.1071    raeburn  12984:         if ($actionurl eq '/adm/dependencies') {
                   12985:             foreach my $path (keys(%currsubfile)) {
                   12986:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12987:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12988:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12989:                              next if (($rem ne '') &&
                   12990:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12991:                                        (ref($navmap) &&
                   12992:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12993:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12994:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12995:                              $unused{$path.'/'.$file} = 1; 
                   12996:                          }
                   12997:                     }
                   12998:                 }
                   12999:             }
                   13000:         }
1.984     raeburn  13001:     }
1.1249    damieng  13002:     
                   13003:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   13004:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  13005:     my %currfile;
1.1123    raeburn  13006:     if (($actionurl eq '/adm/portfolio') ||
                   13007:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  13008:         my ($dirlistref,$listerror) =
                   13009:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   13010:         if (ref($dirlistref) eq 'ARRAY') {
                   13011:             foreach my $line (@{$dirlistref}) {
                   13012:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   13013:                 $currfile{$file_name} = 1;
                   13014:             }
1.984     raeburn  13015:         }
1.987     raeburn  13016:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  13017:         if (opendir(my $dir,$url)) {
1.987     raeburn  13018:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  13019:             map {$currfile{$_} = 1;} @dir_list;
                   13020:         }
1.1084    raeburn  13021:     } elsif (($actionurl eq '/adm/dependencies') ||
                   13022:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  13023:               ($args->{'context'} eq 'paste')) ||
                   13024:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  13025:         if ($env{'request.course.id'} ne '') {
                   13026:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   13027:             if ($dir ne '') {
                   13028:                 my ($dirlistref,$listerror) =
                   13029:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   13030:                 if (ref($dirlistref) eq 'ARRAY') {
                   13031:                     foreach my $line (@{$dirlistref}) {
                   13032:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   13033:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   13034:                         unless (($testdir&$dirptr) ||
                   13035:                                 ($file_name =~ /^\.\.?$/)) {
                   13036:                             $currfile{$file_name} = [$size,$mtime];
                   13037:                         }
                   13038:                     }
                   13039:                 }
                   13040:             }
                   13041:         }
1.984     raeburn  13042:     }
1.1249    damieng  13043:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   13044:     # are not in subdirectories, using $currfile
1.984     raeburn  13045:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  13046:         if (exists($currfile{$file})) {
1.987     raeburn  13047:             unless ($mapping{$file} eq $file) {
                   13048:                 $pathchanges{$file} = 1;
                   13049:             }
                   13050:             $existing{$file} = 1;
                   13051:             $numexisting ++;
                   13052:         } else {
1.984     raeburn  13053:             $newfiles{$file} = 1;
                   13054:         }
                   13055:     }
1.1071    raeburn  13056:     foreach my $file (keys(%currfile)) {
                   13057:         unless (($file eq $filename) ||
                   13058:                 ($file eq $filename.'.bak') ||
                   13059:                 ($dependencies{$file})) {
1.1085    raeburn  13060:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  13061:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   13062:                     next if (($rem ne '') &&
                   13063:                              (($env{"httpref.$rem".$file} ne '') ||
                   13064:                               (ref($navmap) &&
                   13065:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   13066:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   13067:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   13068:                 }
1.1085    raeburn  13069:             }
1.1071    raeburn  13070:             $unused{$file} = 1;
                   13071:         }
                   13072:     }
1.1249    damieng  13073:     
                   13074:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  13075:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   13076:         ($args->{'context'} eq 'paste')) {
                   13077:         $counter = scalar(keys(%existing));
                   13078:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  13079:         return ($output,$counter,$numpathchg,\%existing);
                   13080:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   13081:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   13082:         $counter = scalar(keys(%existing));
                   13083:         $numpathchg = scalar(keys(%pathchanges));
                   13084:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  13085:     }
1.1249    damieng  13086:     
                   13087:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   13088:     
                   13089:     # $upload_output: missing dependencies (with upload form)
                   13090:     # $modify_output: uploaded dependencies (in use)
                   13091:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  13092:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  13093:         if ($actionurl eq '/adm/dependencies') {
                   13094:             next if ($embed_file =~ m{^\w+://});
                   13095:         }
1.660     raeburn  13096:         $upload_output .= &start_data_table_row().
1.1123    raeburn  13097:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  13098:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  13099:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  13100:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   13101:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  13102:         }
1.1123    raeburn  13103:         $upload_output .= '</td>';
1.1071    raeburn  13104:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  13105:             $upload_output.='<td align="right">'.
                   13106:                             '<span class="LC_info LC_fontsize_medium">'.
                   13107:                             &mt("URL points to web address").'</span>';
1.987     raeburn  13108:             $numremref++;
1.660     raeburn  13109:         } elsif ($args->{'error_on_invalid_names'}
                   13110:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  13111:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   13112:                             &mt('Invalid characters').'</span>';
1.987     raeburn  13113:             $numinvalid++;
1.660     raeburn  13114:         } else {
1.1123    raeburn  13115:             $upload_output .= '<td>'.
                   13116:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  13117:                                                      $embed_file,\%mapping,
1.1071    raeburn  13118:                                                      $allfiles,$codebase,'upload');
                   13119:             $counter ++;
                   13120:             $numnew ++;
1.987     raeburn  13121:         }
                   13122:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   13123:     }
                   13124:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  13125:         if ($actionurl eq '/adm/dependencies') {
                   13126:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   13127:             $modify_output .= &start_data_table_row().
                   13128:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   13129:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   13130:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   13131:                               '<td>'.$size.'</td>'.
                   13132:                               '<td>'.$mtime.'</td>'.
                   13133:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   13134:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   13135:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   13136:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   13137:                               &embedded_file_element('upload_embedded',$counter,
                   13138:                                                      $embed_file,\%mapping,
                   13139:                                                      $allfiles,$codebase,'modify').
                   13140:                               '</div></td>'.
                   13141:                               &end_data_table_row()."\n";
                   13142:             $counter ++;
                   13143:         } else {
                   13144:             $upload_output .= &start_data_table_row().
1.1123    raeburn  13145:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   13146:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   13147:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  13148:                               &Apache::loncommon::end_data_table_row()."\n";
                   13149:         }
                   13150:     }
                   13151:     my $delidx = $counter;
                   13152:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   13153:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   13154:         $delete_output .= &start_data_table_row().
                   13155:                           '<td><img src="'.&icon($oldfile).'" />'.
                   13156:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   13157:                           '<td>'.$size.'</td>'.
                   13158:                           '<td>'.$mtime.'</td>'.
                   13159:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   13160:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   13161:                           &embedded_file_element('upload_embedded',$delidx,
                   13162:                                                  $oldfile,\%mapping,$allfiles,
                   13163:                                                  $codebase,'delete').'</td>'.
                   13164:                           &end_data_table_row()."\n"; 
                   13165:         $numunused ++;
                   13166:         $delidx ++;
1.987     raeburn  13167:     }
                   13168:     if ($upload_output) {
                   13169:         $upload_output = &start_data_table().
                   13170:                          $upload_output.
                   13171:                          &end_data_table()."\n";
                   13172:     }
1.1071    raeburn  13173:     if ($modify_output) {
                   13174:         $modify_output = &start_data_table().
                   13175:                          &start_data_table_header_row().
                   13176:                          '<th>'.&mt('File').'</th>'.
                   13177:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13178:                          '<th>'.&mt('Modified').'</th>'.
                   13179:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   13180:                          &end_data_table_header_row().
                   13181:                          $modify_output.
                   13182:                          &end_data_table()."\n";
                   13183:     }
                   13184:     if ($delete_output) {
                   13185:         $delete_output = &start_data_table().
                   13186:                          &start_data_table_header_row().
                   13187:                          '<th>'.&mt('File').'</th>'.
                   13188:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13189:                          '<th>'.&mt('Modified').'</th>'.
                   13190:                          '<th>'.&mt('Delete?').'</th>'.
                   13191:                          &end_data_table_header_row().
                   13192:                          $delete_output.
                   13193:                          &end_data_table()."\n";
                   13194:     }
1.987     raeburn  13195:     my $applies = 0;
                   13196:     if ($numremref) {
                   13197:         $applies ++;
                   13198:     }
                   13199:     if ($numinvalid) {
                   13200:         $applies ++;
                   13201:     }
                   13202:     if ($numexisting) {
                   13203:         $applies ++;
                   13204:     }
1.1071    raeburn  13205:     if ($counter || $numunused) {
1.987     raeburn  13206:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   13207:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  13208:                   $state.'<h3>'.$heading.'</h3>'; 
                   13209:         if ($actionurl eq '/adm/dependencies') {
                   13210:             if ($numnew) {
                   13211:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   13212:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   13213:                            $upload_output.'<br />'."\n";
                   13214:             }
                   13215:             if ($numexisting) {
                   13216:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   13217:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   13218:                            $modify_output.'<br />'."\n";
                   13219:                            $buttontext = &mt('Save changes');
                   13220:             }
                   13221:             if ($numunused) {
                   13222:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   13223:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   13224:                            $delete_output.'<br />'."\n";
                   13225:                            $buttontext = &mt('Save changes');
                   13226:             }
                   13227:         } else {
                   13228:             $output .= $upload_output.'<br />'."\n";
                   13229:         }
                   13230:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   13231:                    $counter.'" />'."\n";
                   13232:         if ($actionurl eq '/adm/dependencies') { 
                   13233:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   13234:                        $numnew.'" />'."\n";
                   13235:         } elsif ($actionurl eq '') {
1.987     raeburn  13236:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   13237:         }
                   13238:     } elsif ($applies) {
                   13239:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   13240:         if ($applies > 1) {
                   13241:             $output .=  
1.1123    raeburn  13242:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  13243:             if ($numremref) {
                   13244:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   13245:             }
                   13246:             if ($numinvalid) {
                   13247:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   13248:             }
                   13249:             if ($numexisting) {
                   13250:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   13251:             }
                   13252:             $output .= '</ul><br />';
                   13253:         } elsif ($numremref) {
                   13254:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   13255:         } elsif ($numinvalid) {
                   13256:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   13257:         } elsif ($numexisting) {
                   13258:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   13259:         }
                   13260:         $output .= $upload_output.'<br />';
                   13261:     }
                   13262:     my ($pathchange_output,$chgcount);
1.1071    raeburn  13263:     $chgcount = $counter;
1.987     raeburn  13264:     if (keys(%pathchanges) > 0) {
                   13265:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  13266:             if ($counter) {
1.987     raeburn  13267:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   13268:                                                   $embed_file,\%mapping,
1.1071    raeburn  13269:                                                   $allfiles,$codebase,'change');
1.987     raeburn  13270:             } else {
                   13271:                 $pathchange_output .= 
                   13272:                     &start_data_table_row().
                   13273:                     '<td><input type ="checkbox" name="namechange" value="'.
                   13274:                     $chgcount.'" checked="checked" /></td>'.
                   13275:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   13276:                     '<td>'.$embed_file.
                   13277:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  13278:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  13279:                     '</td>'.&end_data_table_row();
1.660     raeburn  13280:             }
1.987     raeburn  13281:             $numpathchg ++;
                   13282:             $chgcount ++;
1.660     raeburn  13283:         }
                   13284:     }
1.1127    raeburn  13285:     if (($counter) || ($numunused)) {
1.987     raeburn  13286:         if ($numpathchg) {
                   13287:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   13288:                        $numpathchg.'" />'."\n";
                   13289:         }
                   13290:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   13291:             ($actionurl eq '/adm/imsimport')) {
                   13292:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   13293:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   13294:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  13295:         } elsif ($actionurl eq '/adm/dependencies') {
                   13296:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  13297:         }
1.1123    raeburn  13298:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  13299:     } elsif ($numpathchg) {
                   13300:         my %pathchange = ();
                   13301:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   13302:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13303:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  13304:         }
1.987     raeburn  13305:     }
1.1071    raeburn  13306:     return ($output,$counter,$numpathchg);
1.987     raeburn  13307: }
                   13308: 
1.1147    raeburn  13309: =pod
                   13310: 
                   13311: =item * clean_path($name)
                   13312: 
                   13313: Performs clean-up of directories, subdirectories and filename in an
                   13314: embedded object, referenced in an HTML file which is being uploaded
                   13315: to a course or portfolio, where 
                   13316: "Upload embedded images/multimedia files if HTML file" checkbox was
                   13317: checked.
                   13318: 
                   13319: Clean-up is similar to replacements in lonnet::clean_filename()
                   13320: except each / between sub-directory and next level is preserved.
                   13321: 
                   13322: =cut
                   13323: 
                   13324: sub clean_path {
                   13325:     my ($embed_file) = @_;
                   13326:     $embed_file =~s{^/+}{};
                   13327:     my @contents;
                   13328:     if ($embed_file =~ m{/}) {
                   13329:         @contents = split(/\//,$embed_file);
                   13330:     } else {
                   13331:         @contents = ($embed_file);
                   13332:     }
                   13333:     my $lastidx = scalar(@contents)-1;
                   13334:     for (my $i=0; $i<=$lastidx; $i++) { 
                   13335:         $contents[$i]=~s{\\}{/}g;
                   13336:         $contents[$i]=~s/\s+/\_/g;
                   13337:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   13338:         if ($i == $lastidx) {
                   13339:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   13340:         }
                   13341:     }
                   13342:     if ($lastidx > 0) {
                   13343:         return join('/',@contents);
                   13344:     } else {
                   13345:         return $contents[0];
                   13346:     }
                   13347: }
                   13348: 
1.987     raeburn  13349: sub embedded_file_element {
1.1071    raeburn  13350:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  13351:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   13352:                    (ref($codebase) eq 'HASH'));
                   13353:     my $output;
1.1071    raeburn  13354:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  13355:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   13356:     }
                   13357:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   13358:                &escape($embed_file).'" />';
                   13359:     unless (($context eq 'upload_embedded') && 
                   13360:             ($mapping->{$embed_file} eq $embed_file)) {
                   13361:         $output .='
                   13362:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   13363:     }
                   13364:     my $attrib;
                   13365:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   13366:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   13367:     }
                   13368:     $output .=
                   13369:         "\n\t\t".
                   13370:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   13371:         $attrib.'" />';
                   13372:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   13373:         $output .=
                   13374:             "\n\t\t".
                   13375:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   13376:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  13377:     }
1.987     raeburn  13378:     return $output;
1.660     raeburn  13379: }
                   13380: 
1.1071    raeburn  13381: sub get_dependency_details {
                   13382:     my ($currfile,$currsubfile,$embed_file) = @_;
                   13383:     my ($size,$mtime,$showsize,$showmtime);
                   13384:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   13385:         if ($embed_file =~ m{/}) {
                   13386:             my ($path,$fname) = split(/\//,$embed_file);
                   13387:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   13388:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   13389:             }
                   13390:         } else {
                   13391:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   13392:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   13393:             }
                   13394:         }
                   13395:         $showsize = $size/1024.0;
                   13396:         $showsize = sprintf("%.1f",$showsize);
                   13397:         if ($mtime > 0) {
                   13398:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   13399:         }
                   13400:     }
                   13401:     return ($showsize,$showmtime);
                   13402: }
                   13403: 
                   13404: sub ask_embedded_js {
                   13405:     return <<"END";
                   13406: <script type="text/javascript"">
                   13407: // <![CDATA[
                   13408: function toggleBrowse(counter) {
                   13409:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   13410:     var fileid = document.getElementById('embedded_item_'+counter);
                   13411:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   13412:     if (chkboxid.checked == true) {
                   13413:         uploaddivid.style.display='block';
                   13414:     } else {
                   13415:         uploaddivid.style.display='none';
                   13416:         fileid.value = '';
                   13417:     }
                   13418: }
                   13419: // ]]>
                   13420: </script>
                   13421: 
                   13422: END
                   13423: }
                   13424: 
1.661     raeburn  13425: sub upload_embedded {
                   13426:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  13427:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   13428:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  13429:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   13430:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   13431:         my $orig_uploaded_filename =
                   13432:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  13433:         foreach my $type ('orig','ref','attrib','codebase') {
                   13434:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   13435:                 $env{'form.embedded_'.$type.'_'.$i} =
                   13436:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   13437:             }
                   13438:         }
1.661     raeburn  13439:         my ($path,$fname) =
                   13440:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   13441:         # no path, whole string is fname
                   13442:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   13443:         $fname = &Apache::lonnet::clean_filename($fname);
                   13444:         # See if there is anything left
                   13445:         next if ($fname eq '');
                   13446: 
                   13447:         # Check if file already exists as a file or directory.
                   13448:         my ($state,$msg);
                   13449:         if ($context eq 'portfolio') {
                   13450:             my $port_path = $dirpath;
                   13451:             if ($group ne '') {
                   13452:                 $port_path = "groups/$group/$port_path";
                   13453:             }
1.987     raeburn  13454:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   13455:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  13456:                                               $dir_root,$port_path,$disk_quota,
                   13457:                                               $current_disk_usage,$uname,$udom);
                   13458:             if ($state eq 'will_exceed_quota'
1.984     raeburn  13459:                 || $state eq 'file_locked') {
1.661     raeburn  13460:                 $output .= $msg;
                   13461:                 next;
                   13462:             }
                   13463:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   13464:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   13465:             if ($state eq 'exists') {
                   13466:                 $output .= $msg;
                   13467:                 next;
                   13468:             }
                   13469:         }
                   13470:         # Check if extension is valid
                   13471:         if (($fname =~ /\.(\w+)$/) &&
                   13472:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   13473:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   13474:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  13475:             next;
                   13476:         } elsif (($fname =~ /\.(\w+)$/) &&
                   13477:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  13478:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  13479:             next;
                   13480:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   13481:             $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  13482:             next;
                   13483:         }
                   13484:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  13485:         my $subdir = $path;
                   13486:         $subdir =~ s{/+$}{};
1.661     raeburn  13487:         if ($context eq 'portfolio') {
1.984     raeburn  13488:             my $result;
                   13489:             if ($state eq 'existingfile') {
                   13490:                 $result=
                   13491:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  13492:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  13493:             } else {
1.984     raeburn  13494:                 $result=
                   13495:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  13496:                                                     $dirpath.
1.1123    raeburn  13497:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  13498:                 if ($result !~ m|^/uploaded/|) {
                   13499:                     $output .= '<span class="LC_error">'
                   13500:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13501:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13502:                                .'</span><br />';
                   13503:                     next;
                   13504:                 } else {
1.987     raeburn  13505:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13506:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  13507:                 }
1.661     raeburn  13508:             }
1.1123    raeburn  13509:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  13510:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   13511:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  13512:             my $result =
1.1126    raeburn  13513:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  13514:             if ($result !~ m|^/uploaded/|) {
                   13515:                 $output .= '<span class="LC_error">'
                   13516:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13517:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13518:                            .'</span><br />';
                   13519:                     next;
                   13520:             } else {
                   13521:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13522:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  13523:                 if ($context eq 'syllabus') {
                   13524:                     &Apache::lonnet::make_public_indefinitely($result);
                   13525:                 }
1.987     raeburn  13526:             }
1.661     raeburn  13527:         } else {
                   13528: # Save the file
                   13529:             my $target = $env{'form.embedded_item_'.$i};
                   13530:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   13531:             my $dest = $fullpath.$fname;
                   13532:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  13533:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  13534:             my $count;
                   13535:             my $filepath = $dir_root;
1.1027    raeburn  13536:             foreach my $subdir (@parts) {
                   13537:                 $filepath .= "/$subdir";
                   13538:                 if (!-e $filepath) {
1.661     raeburn  13539:                     mkdir($filepath,0770);
                   13540:                 }
                   13541:             }
                   13542:             my $fh;
                   13543:             if (!open($fh,'>'.$dest)) {
                   13544:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   13545:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  13546:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   13547:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13548:                            '</span><br />';
                   13549:             } else {
                   13550:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   13551:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   13552:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  13553:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   13554:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13555:                               '</span><br />';
                   13556:                 } else {
1.987     raeburn  13557:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13558:                                $url.'</span>').'<br />';
                   13559:                     unless ($context eq 'testbank') {
                   13560:                         $footer .= &mt('View embedded file: [_1]',
                   13561:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   13562:                     }
                   13563:                 }
                   13564:                 close($fh);
                   13565:             }
                   13566:         }
                   13567:         if ($env{'form.embedded_ref_'.$i}) {
                   13568:             $pathchange{$i} = 1;
                   13569:         }
                   13570:     }
                   13571:     if ($output) {
                   13572:         $output = '<p>'.$output.'</p>';
                   13573:     }
                   13574:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   13575:     $returnflag = 'ok';
1.1071    raeburn  13576:     my $numpathchgs = scalar(keys(%pathchange));
                   13577:     if ($numpathchgs > 0) {
1.987     raeburn  13578:         if ($context eq 'portfolio') {
                   13579:             $output .= '<p>'.&mt('or').'</p>';
                   13580:         } elsif ($context eq 'testbank') {
1.1071    raeburn  13581:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   13582:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  13583:             $returnflag = 'modify_orightml';
                   13584:         }
                   13585:     }
1.1071    raeburn  13586:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  13587: }
                   13588: 
                   13589: sub modify_html_form {
                   13590:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   13591:     my $end = 0;
                   13592:     my $modifyform;
                   13593:     if ($context eq 'upload_embedded') {
                   13594:         return unless (ref($pathchange) eq 'HASH');
                   13595:         if ($env{'form.number_embedded_items'}) {
                   13596:             $end += $env{'form.number_embedded_items'};
                   13597:         }
                   13598:         if ($env{'form.number_pathchange_items'}) {
                   13599:             $end += $env{'form.number_pathchange_items'};
                   13600:         }
                   13601:         if ($end) {
                   13602:             for (my $i=0; $i<$end; $i++) {
                   13603:                 if ($i < $env{'form.number_embedded_items'}) {
                   13604:                     next unless($pathchange->{$i});
                   13605:                 }
                   13606:                 $modifyform .=
                   13607:                     &start_data_table_row().
                   13608:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   13609:                     'checked="checked" /></td>'.
                   13610:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   13611:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   13612:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   13613:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   13614:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   13615:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   13616:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   13617:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   13618:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   13619:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   13620:                     &end_data_table_row();
1.1071    raeburn  13621:             }
1.987     raeburn  13622:         }
                   13623:     } else {
                   13624:         $modifyform = $pathchgtable;
                   13625:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   13626:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   13627:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13628:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   13629:         }
                   13630:     }
                   13631:     if ($modifyform) {
1.1071    raeburn  13632:         if ($actionurl eq '/adm/dependencies') {
                   13633:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   13634:         }
1.987     raeburn  13635:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   13636:                '<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".
                   13637:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   13638:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   13639:                '</ol></p>'."\n".'<p>'.
                   13640:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   13641:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   13642:                &start_data_table()."\n".
                   13643:                &start_data_table_header_row().
                   13644:                '<th>'.&mt('Change?').'</th>'.
                   13645:                '<th>'.&mt('Current reference').'</th>'.
                   13646:                '<th>'.&mt('Required reference').'</th>'.
                   13647:                &end_data_table_header_row()."\n".
                   13648:                $modifyform.
                   13649:                &end_data_table().'<br />'."\n".$hiddenstate.
                   13650:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   13651:                '</form>'."\n";
                   13652:     }
                   13653:     return;
                   13654: }
                   13655: 
                   13656: sub modify_html_refs {
1.1123    raeburn  13657:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  13658:     my $container;
                   13659:     if ($context eq 'portfolio') {
                   13660:         $container = $env{'form.container'};
                   13661:     } elsif ($context eq 'coursedoc') {
                   13662:         $container = $env{'form.primaryurl'};
1.1071    raeburn  13663:     } elsif ($context eq 'manage_dependencies') {
                   13664:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   13665:         $container = "/$container";
1.1123    raeburn  13666:     } elsif ($context eq 'syllabus') {
                   13667:         $container = $url;
1.987     raeburn  13668:     } else {
1.1027    raeburn  13669:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  13670:     }
                   13671:     my (%allfiles,%codebase,$output,$content);
                   13672:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  13673:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  13674:         if (wantarray) {
                   13675:             return ('',0,0); 
                   13676:         } else {
                   13677:             return;
                   13678:         }
                   13679:     }
                   13680:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13681:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  13682:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   13683:             if (wantarray) {
                   13684:                 return ('',0,0);
                   13685:             } else {
                   13686:                 return;
                   13687:             }
                   13688:         } 
1.987     raeburn  13689:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  13690:         if ($content eq '-1') {
                   13691:             if (wantarray) {
                   13692:                 return ('',0,0);
                   13693:             } else {
                   13694:                 return;
                   13695:             }
                   13696:         }
1.987     raeburn  13697:     } else {
1.1071    raeburn  13698:         unless ($container =~ /^\Q$dir_root\E/) {
                   13699:             if (wantarray) {
                   13700:                 return ('',0,0);
                   13701:             } else {
                   13702:                 return;
                   13703:             }
                   13704:         } 
1.1317    raeburn  13705:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13706:             $content = join('', <$fh>);
                   13707:             close($fh);
                   13708:         } else {
1.1071    raeburn  13709:             if (wantarray) {
                   13710:                 return ('',0,0);
                   13711:             } else {
                   13712:                 return;
                   13713:             }
1.987     raeburn  13714:         }
                   13715:     }
                   13716:     my ($count,$codebasecount) = (0,0);
                   13717:     my $mm = new File::MMagic;
                   13718:     my $mime_type = $mm->checktype_contents($content);
                   13719:     if ($mime_type eq 'text/html') {
                   13720:         my $parse_result = 
                   13721:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13722:                                                     \%codebase,\$content);
                   13723:         if ($parse_result eq 'ok') {
                   13724:             foreach my $i (@changes) {
                   13725:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13726:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13727:                 if ($allfiles{$ref}) {
                   13728:                     my $newname =  $orig;
                   13729:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13730:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13731:                     if ($attrib_regexp =~ /:/) {
                   13732:                         $attrib_regexp =~ s/\:/|/g;
                   13733:                     }
                   13734:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13735:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13736:                         $count += $numchg;
1.1123    raeburn  13737:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13738:                         delete($allfiles{$ref});
1.987     raeburn  13739:                     }
                   13740:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13741:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13742:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13743:                         $codebasecount ++;
                   13744:                     }
                   13745:                 }
                   13746:             }
1.1123    raeburn  13747:             my $skiprewrites;
1.987     raeburn  13748:             if ($count || $codebasecount) {
                   13749:                 my $saveresult;
1.1071    raeburn  13750:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13751:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13752:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13753:                     if ($url eq $container) {
                   13754:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13755:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13756:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13757:                                             $fname.'</span>').'</p>';
1.987     raeburn  13758:                     } else {
                   13759:                          $output = '<p class="LC_error">'.
                   13760:                                    &mt('Error: update failed for: [_1].',
                   13761:                                    '<span class="LC_filename">'.
                   13762:                                    $container.'</span>').'</p>';
                   13763:                     }
1.1123    raeburn  13764:                     if ($context eq 'syllabus') {
                   13765:                         unless ($saveresult eq 'ok') {
                   13766:                             $skiprewrites = 1;
                   13767:                         }
                   13768:                     }
1.987     raeburn  13769:                 } else {
1.1317    raeburn  13770:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13771:                         print $fh $content;
                   13772:                         close($fh);
                   13773:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13774:                                   $count,'<span class="LC_filename">'.
                   13775:                                   $container.'</span>').'</p>';
1.661     raeburn  13776:                     } else {
1.987     raeburn  13777:                          $output = '<p class="LC_error">'.
                   13778:                                    &mt('Error: could not update [_1].',
                   13779:                                    '<span class="LC_filename">'.
                   13780:                                    $container.'</span>').'</p>';
1.661     raeburn  13781:                     }
                   13782:                 }
                   13783:             }
1.1123    raeburn  13784:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13785:                 my ($actionurl,$state);
                   13786:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13787:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13788:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13789:                                               \%codebase,
                   13790:                                               {'context' => 'rewrites',
                   13791:                                                'ignore_remote_references' => 1,});
                   13792:                 if (ref($mapping) eq 'HASH') {
                   13793:                     my $rewrites = 0;
                   13794:                     foreach my $key (keys(%{$mapping})) {
                   13795:                         next if ($key =~ m{^https?://});
                   13796:                         my $ref = $mapping->{$key};
                   13797:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13798:                         my $attrib;
                   13799:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13800:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13801:                         }
                   13802:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13803:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13804:                             $rewrites += $numchg;
                   13805:                         }
                   13806:                     }
                   13807:                     if ($rewrites) {
                   13808:                         my $saveresult; 
                   13809:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13810:                         if ($url eq $container) {
                   13811:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13812:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13813:                                             $count,'<span class="LC_filename">'.
                   13814:                                             $fname.'</span>').'</p>';
                   13815:                         } else {
                   13816:                             $output .= '<p class="LC_error">'.
                   13817:                                        &mt('Error: could not update links in [_1].',
                   13818:                                        '<span class="LC_filename">'.
                   13819:                                        $container.'</span>').'</p>';
                   13820: 
                   13821:                         }
                   13822:                     }
                   13823:                 }
                   13824:             }
1.987     raeburn  13825:         } else {
                   13826:             &logthis('Failed to parse '.$container.
                   13827:                      ' to modify references: '.$parse_result);
1.661     raeburn  13828:         }
                   13829:     }
1.1071    raeburn  13830:     if (wantarray) {
                   13831:         return ($output,$count,$codebasecount);
                   13832:     } else {
                   13833:         return $output;
                   13834:     }
1.661     raeburn  13835: }
                   13836: 
                   13837: sub check_for_existing {
                   13838:     my ($path,$fname,$element) = @_;
                   13839:     my ($state,$msg);
                   13840:     if (-d $path.'/'.$fname) {
                   13841:         $state = 'exists';
                   13842:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13843:     } elsif (-e $path.'/'.$fname) {
                   13844:         $state = 'exists';
                   13845:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13846:     }
                   13847:     if ($state eq 'exists') {
                   13848:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13849:     }
                   13850:     return ($state,$msg);
                   13851: }
                   13852: 
                   13853: sub check_for_upload {
                   13854:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13855:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13856:     my $filesize = length($env{'form.'.$element});
                   13857:     if (!$filesize) {
                   13858:         my $msg = '<span class="LC_error">'.
                   13859:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13860:                       '<span class="LC_filename">'.$fname.'</span>',
                   13861:                       $filesize).'<br />'.
1.1007    raeburn  13862:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13863:                   '</span>';
                   13864:         return ('zero_bytes',$msg);
                   13865:     }
                   13866:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13867:     my $getpropath = 1;
1.1021    raeburn  13868:     my ($dirlistref,$listerror) =
                   13869:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13870:     my $found_file = 0;
                   13871:     my $locked_file = 0;
1.991     raeburn  13872:     my @lockers;
                   13873:     my $navmap;
                   13874:     if ($env{'request.course.id'}) {
                   13875:         $navmap = Apache::lonnavmaps::navmap->new();
                   13876:     }
1.1021    raeburn  13877:     if (ref($dirlistref) eq 'ARRAY') {
                   13878:         foreach my $line (@{$dirlistref}) {
                   13879:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13880:             if ($file_name eq $fname){
                   13881:                 $file_name = $path.$file_name;
                   13882:                 if ($group ne '') {
                   13883:                     $file_name = $group.$file_name;
                   13884:                 }
                   13885:                 $found_file = 1;
                   13886:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13887:                     foreach my $lock (@lockers) {
                   13888:                         if (ref($lock) eq 'ARRAY') {
                   13889:                             my ($symb,$crsid) = @{$lock};
                   13890:                             if ($crsid eq $env{'request.course.id'}) {
                   13891:                                 if (ref($navmap)) {
                   13892:                                     my $res = $navmap->getBySymb($symb);
                   13893:                                     foreach my $part (@{$res->parts()}) { 
                   13894:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13895:                                         unless (($slot_status == $res->RESERVED) ||
                   13896:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13897:                                             $locked_file = 1;
                   13898:                                         }
1.991     raeburn  13899:                                     }
1.1021    raeburn  13900:                                 } else {
                   13901:                                     $locked_file = 1;
1.991     raeburn  13902:                                 }
                   13903:                             } else {
                   13904:                                 $locked_file = 1;
                   13905:                             }
                   13906:                         }
1.1021    raeburn  13907:                    }
                   13908:                 } else {
                   13909:                     my @info = split(/\&/,$rest);
                   13910:                     my $currsize = $info[6]/1000;
                   13911:                     if ($currsize < $filesize) {
                   13912:                         my $extra = $filesize - $currsize;
                   13913:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13914:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13915:                                       &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   13916:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13917:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13918:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13919:                             return ('will_exceed_quota',$msg);
                   13920:                         }
1.984     raeburn  13921:                     }
                   13922:                 }
1.661     raeburn  13923:             }
                   13924:         }
                   13925:     }
                   13926:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13927:         my $msg = '<p class="LC_warning">'.
                   13928:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13929:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13930:         return ('will_exceed_quota',$msg);
                   13931:     } elsif ($found_file) {
                   13932:         if ($locked_file) {
1.1179    bisitz   13933:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13934:             $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   13935:             $msg .= '</p>';
1.661     raeburn  13936:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13937:             return ('file_locked',$msg);
                   13938:         } else {
1.1179    bisitz   13939:             my $msg = '<p class="LC_error">';
1.984     raeburn  13940:             $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   13941:             $msg .= '</p>';
1.984     raeburn  13942:             return ('existingfile',$msg);
1.661     raeburn  13943:         }
                   13944:     }
                   13945: }
                   13946: 
1.987     raeburn  13947: sub check_for_traversal {
                   13948:     my ($path,$url,$toplevel) = @_;
                   13949:     my @parts=split(/\//,$path);
                   13950:     my $cleanpath;
                   13951:     my $fullpath = $url;
                   13952:     for (my $i=0;$i<@parts;$i++) {
                   13953:         next if ($parts[$i] eq '.');
                   13954:         if ($parts[$i] eq '..') {
                   13955:             $fullpath =~ s{([^/]+/)$}{};
                   13956:         } else {
                   13957:             $fullpath .= $parts[$i].'/';
                   13958:         }
                   13959:     }
                   13960:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13961:         $cleanpath = $1;
                   13962:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13963:         my $curr_toprel = $1;
                   13964:         my @parts = split(/\//,$curr_toprel);
                   13965:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13966:         my @urlparts = split(/\//,$url_toprel);
                   13967:         my $doubledots;
                   13968:         my $startdiff = -1;
                   13969:         for (my $i=0; $i<@urlparts; $i++) {
                   13970:             if ($startdiff == -1) {
                   13971:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13972:                     $startdiff = $i;
                   13973:                     $doubledots .= '../';
                   13974:                 }
                   13975:             } else {
                   13976:                 $doubledots .= '../';
                   13977:             }
                   13978:         }
                   13979:         if ($startdiff > -1) {
                   13980:             $cleanpath = $doubledots;
                   13981:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13982:                 $cleanpath .= $parts[$i].'/';
                   13983:             }
                   13984:         }
                   13985:     }
                   13986:     $cleanpath =~ s{(/)$}{};
                   13987:     return $cleanpath;
                   13988: }
1.31      albertel 13989: 
1.1053    raeburn  13990: sub is_archive_file {
                   13991:     my ($mimetype) = @_;
                   13992:     if (($mimetype eq 'application/octet-stream') ||
                   13993:         ($mimetype eq 'application/x-stuffit') ||
                   13994:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13995:         return 1;
                   13996:     }
                   13997:     return;
                   13998: }
                   13999: 
                   14000: sub decompress_form {
1.1065    raeburn  14001:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  14002:     my %lt = &Apache::lonlocal::texthash (
                   14003:         this => 'This file is an archive file.',
1.1067    raeburn  14004:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  14005:         itsc => 'Its contents are as follows:',
1.1053    raeburn  14006:         youm => 'You may wish to extract its contents.',
                   14007:         extr => 'Extract contents',
1.1067    raeburn  14008:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   14009:         proa => 'Process automatically?',
1.1053    raeburn  14010:         yes  => 'Yes',
                   14011:         no   => 'No',
1.1067    raeburn  14012:         fold => 'Title for folder containing movie',
                   14013:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  14014:     );
1.1065    raeburn  14015:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  14016:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  14017:     my $info = &list_archive_contents($fileloc,\@paths);
                   14018:     if (@paths) {
                   14019:         foreach my $path (@paths) {
                   14020:             $path =~ s{^/}{};
1.1067    raeburn  14021:             if ($path =~ m{^([^/]+)/$}) {
                   14022:                 $topdir = $1;
                   14023:             }
1.1065    raeburn  14024:             if ($path =~ m{^([^/]+)/}) {
                   14025:                 $toplevel{$1} = $path;
                   14026:             } else {
                   14027:                 $toplevel{$path} = $path;
                   14028:             }
                   14029:         }
                   14030:     }
1.1067    raeburn  14031:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  14032:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  14033:                         "$topdir/media/",
                   14034:                         "$topdir/media/$topdir.mp4",
                   14035:                         "$topdir/media/FirstFrame.png",
                   14036:                         "$topdir/media/player.swf",
                   14037:                         "$topdir/media/swfobject.js",
                   14038:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  14039:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  14040:                          "$topdir/$topdir.mp4",
                   14041:                          "$topdir/$topdir\_config.xml",
                   14042:                          "$topdir/$topdir\_controller.swf",
                   14043:                          "$topdir/$topdir\_embed.css",
                   14044:                          "$topdir/$topdir\_First_Frame.png",
                   14045:                          "$topdir/$topdir\_player.html",
                   14046:                          "$topdir/$topdir\_Thumbnails.png",
                   14047:                          "$topdir/playerProductInstall.swf",
                   14048:                          "$topdir/scripts/",
                   14049:                          "$topdir/scripts/config_xml.js",
                   14050:                          "$topdir/scripts/handlebars.js",
                   14051:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   14052:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   14053:                          "$topdir/scripts/modernizr.js",
                   14054:                          "$topdir/scripts/player-min.js",
                   14055:                          "$topdir/scripts/swfobject.js",
                   14056:                          "$topdir/skins/",
                   14057:                          "$topdir/skins/configuration_express.xml",
                   14058:                          "$topdir/skins/express_show/",
                   14059:                          "$topdir/skins/express_show/player-min.css",
                   14060:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  14061:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   14062:                          "$topdir/$topdir.mp4",
                   14063:                          "$topdir/$topdir\_config.xml",
                   14064:                          "$topdir/$topdir\_controller.swf",
                   14065:                          "$topdir/$topdir\_embed.css",
                   14066:                          "$topdir/$topdir\_First_Frame.png",
                   14067:                          "$topdir/$topdir\_player.html",
                   14068:                          "$topdir/$topdir\_Thumbnails.png",
                   14069:                          "$topdir/playerProductInstall.swf",
                   14070:                          "$topdir/scripts/",
                   14071:                          "$topdir/scripts/config_xml.js",
                   14072:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   14073:                          "$topdir/skins/",
                   14074:                          "$topdir/skins/configuration_express.xml",
                   14075:                          "$topdir/skins/express_show/",
                   14076:                          "$topdir/skins/express_show/spritesheet.min.css",
                   14077:                          "$topdir/skins/express_show/spritesheet.png",
                   14078:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  14079:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  14080:         if (@diffs == 0) {
1.1164    raeburn  14081:             $is_camtasia = 6;
                   14082:         } else {
1.1197    raeburn  14083:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  14084:             if (@diffs == 0) {
                   14085:                 $is_camtasia = 8;
1.1197    raeburn  14086:             } else {
                   14087:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   14088:                 if (@diffs == 0) {
                   14089:                     $is_camtasia = 8;
                   14090:                 }
1.1164    raeburn  14091:             }
1.1067    raeburn  14092:         }
                   14093:     }
                   14094:     my $output;
                   14095:     if ($is_camtasia) {
                   14096:         $output = <<"ENDCAM";
                   14097: <script type="text/javascript" language="Javascript">
                   14098: // <![CDATA[
                   14099: 
                   14100: function camtasiaToggle() {
                   14101:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   14102:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  14103:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  14104:                 document.getElementById('camtasia_titles').style.display='block';
                   14105:             } else {
                   14106:                 document.getElementById('camtasia_titles').style.display='none';
                   14107:             }
                   14108:         }
                   14109:     }
                   14110:     return;
                   14111: }
                   14112: 
                   14113: // ]]>
                   14114: </script>
                   14115: <p>$lt{'camt'}</p>
                   14116: ENDCAM
1.1065    raeburn  14117:     } else {
1.1067    raeburn  14118:         $output = '<p>'.$lt{'this'};
                   14119:         if ($info eq '') {
                   14120:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   14121:         } else {
                   14122:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   14123:                        '<div><pre>'.$info.'</pre></div>';
                   14124:         }
1.1065    raeburn  14125:     }
1.1067    raeburn  14126:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  14127:     my $duplicates;
                   14128:     my $num = 0;
                   14129:     if (ref($dirlist) eq 'ARRAY') {
                   14130:         foreach my $item (@{$dirlist}) {
                   14131:             if (ref($item) eq 'ARRAY') {
                   14132:                 if (exists($toplevel{$item->[0]})) {
                   14133:                     $duplicates .= 
                   14134:                         &start_data_table_row().
                   14135:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14136:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   14137:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14138:                         'value="1" />'.&mt('Yes').'</label>'.
                   14139:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   14140:                         '<td>'.$item->[0].'</td>';
                   14141:                     if ($item->[2]) {
                   14142:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   14143:                     } else {
                   14144:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   14145:                     }
                   14146:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   14147:                                    '<td>'.
                   14148:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   14149:                                    '</td>'.
                   14150:                                    &end_data_table_row();
                   14151:                     $num ++;
                   14152:                 }
                   14153:             }
                   14154:         }
                   14155:     }
                   14156:     my $itemcount;
                   14157:     if (@paths > 0) {
                   14158:         $itemcount = scalar(@paths);
                   14159:     } else {
                   14160:         $itemcount = 1;
                   14161:     }
1.1067    raeburn  14162:     if ($is_camtasia) {
                   14163:         $output .= $lt{'auto'}.'<br />'.
                   14164:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  14165:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  14166:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   14167:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   14168:                    $lt{'no'}.'</label></span><br />'.
                   14169:                    '<div id="camtasia_titles" style="display:block">'.
                   14170:                    &Apache::lonhtmlcommon::start_pick_box().
                   14171:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   14172:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   14173:                    &Apache::lonhtmlcommon::row_closure().
                   14174:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   14175:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   14176:                    &Apache::lonhtmlcommon::row_closure(1).
                   14177:                    &Apache::lonhtmlcommon::end_pick_box().
                   14178:                    '</div>';
                   14179:     }
1.1065    raeburn  14180:     $output .= 
                   14181:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  14182:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   14183:         "\n";
1.1065    raeburn  14184:     if ($duplicates ne '') {
                   14185:         $output .= '<p><span class="LC_warning">'.
                   14186:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   14187:                    &start_data_table().
                   14188:                    &start_data_table_header_row().
                   14189:                    '<th>'.&mt('Overwrite?').'</th>'.
                   14190:                    '<th>'.&mt('Name').'</th>'.
                   14191:                    '<th>'.&mt('Type').'</th>'.
                   14192:                    '<th>'.&mt('Size').'</th>'.
                   14193:                    '<th>'.&mt('Last modified').'</th>'.
                   14194:                    &end_data_table_header_row().
                   14195:                    $duplicates.
                   14196:                    &end_data_table().
                   14197:                    '</p>';
                   14198:     }
1.1067    raeburn  14199:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  14200:     if (ref($hiddenelements) eq 'HASH') {
                   14201:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   14202:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   14203:         }
                   14204:     }
                   14205:     $output .= <<"END";
1.1067    raeburn  14206: <br />
1.1053    raeburn  14207: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   14208: </form>
                   14209: $noextract
                   14210: END
                   14211:     return $output;
                   14212: }
                   14213: 
1.1065    raeburn  14214: sub decompression_utility {
                   14215:     my ($program) = @_;
                   14216:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   14217:     my $location;
                   14218:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   14219:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   14220:                          '/usr/sbin/') {
                   14221:             if (-x $dir.$program) {
                   14222:                 $location = $dir.$program;
                   14223:                 last;
                   14224:             }
                   14225:         }
                   14226:     }
                   14227:     return $location;
                   14228: }
                   14229: 
                   14230: sub list_archive_contents {
                   14231:     my ($file,$pathsref) = @_;
                   14232:     my (@cmd,$output);
                   14233:     my $needsregexp;
                   14234:     if ($file =~ /\.zip$/) {
                   14235:         @cmd = (&decompression_utility('unzip'),"-l");
                   14236:         $needsregexp = 1;
                   14237:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   14238:              ($file =~ /\.tgz$/)) {
                   14239:         @cmd = (&decompression_utility('tar'),"-ztf");
                   14240:     } elsif ($file =~ /\.tar\.bz2$/) {
                   14241:         @cmd = (&decompression_utility('tar'),"-jtf");
                   14242:     } elsif ($file =~ m|\.tar$|) {
                   14243:         @cmd = (&decompression_utility('tar'),"-tf");
                   14244:     }
                   14245:     if (@cmd) {
                   14246:         undef($!);
                   14247:         undef($@);
                   14248:         if (open(my $fh,"-|", @cmd, $file)) {
                   14249:             while (my $line = <$fh>) {
                   14250:                 $output .= $line;
                   14251:                 chomp($line);
                   14252:                 my $item;
                   14253:                 if ($needsregexp) {
                   14254:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   14255:                 } else {
                   14256:                     $item = $line;
                   14257:                 }
                   14258:                 if ($item ne '') {
                   14259:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   14260:                         push(@{$pathsref},$item);
                   14261:                     } 
                   14262:                 }
                   14263:             }
                   14264:             close($fh);
                   14265:         }
                   14266:     }
                   14267:     return $output;
                   14268: }
                   14269: 
1.1053    raeburn  14270: sub decompress_uploaded_file {
                   14271:     my ($file,$dir) = @_;
                   14272:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   14273:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   14274:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   14275:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   14276:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   14277:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   14278:     my $decompressed = $env{'cgi.decompressed'};
                   14279:     &Apache::lonnet::delenv('cgi.file');
                   14280:     &Apache::lonnet::delenv('cgi.dir');
                   14281:     &Apache::lonnet::delenv('cgi.decompressed');
                   14282:     return ($decompressed,$result);
                   14283: }
                   14284: 
1.1055    raeburn  14285: sub process_decompression {
                   14286:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  14287:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   14288:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14289:                &mt('Unexpected file path.').'</p>'."\n";
                   14290:     }
                   14291:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   14292:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14293:                &mt('Unexpected course context.').'</p>'."\n";
                   14294:     }
1.1293    raeburn  14295:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  14296:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14297:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   14298:     }
1.1055    raeburn  14299:     my ($dir,$error,$warning,$output);
1.1180    raeburn  14300:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   14301:         $error = &mt('Filename not a supported archive file type.').
                   14302:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  14303:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   14304:     } else {
                   14305:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14306:         if ($docuhome eq 'no_host') {
                   14307:             $error = &mt('Could not determine home server for course.');
                   14308:         } else {
                   14309:             my @ids=&Apache::lonnet::current_machine_ids();
                   14310:             my $currdir = "$dir_root/$destination";
                   14311:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14312:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   14313:                        "$dir_root/$destination";
                   14314:             } else {
                   14315:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   14316:                        "$dir_root/$docudom/$docuname/$destination";
                   14317:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   14318:                     $error = &mt('Archive file not found.');
                   14319:                 }
                   14320:             }
1.1065    raeburn  14321:             my (@to_overwrite,@to_skip);
                   14322:             if ($env{'form.archive_overwrite_total'} > 0) {
                   14323:                 my $total = $env{'form.archive_overwrite_total'};
                   14324:                 for (my $i=0; $i<$total; $i++) {
                   14325:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   14326:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   14327:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   14328:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   14329:                     }
                   14330:                 }
                   14331:             }
                   14332:             my $numskip = scalar(@to_skip);
1.1292    raeburn  14333:             my $numoverwrite = scalar(@to_overwrite);
                   14334:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  14335:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   14336:             } elsif ($dir eq '') {
1.1055    raeburn  14337:                 $error = &mt('Directory containing archive file unavailable.');
                   14338:             } elsif (!$error) {
1.1065    raeburn  14339:                 my ($decompressed,$display);
1.1292    raeburn  14340:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  14341:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   14342:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  14343:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   14344:                         ($decompressed,$display) = 
                   14345:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   14346:                         foreach my $item (@to_skip) {
                   14347:                             if (($item ne '') && ($item !~ /\.\./)) {
                   14348:                                 if (-f "$dir/$tempdir/$item") { 
                   14349:                                     unlink("$dir/$tempdir/$item");
                   14350:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  14351:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  14352:                                 }
                   14353:                             }
                   14354:                         }
                   14355:                         foreach my $item (@to_overwrite) {
                   14356:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   14357:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   14358:                                     if (-f "$dir/$item") {
                   14359:                                         unlink("$dir/$item");
                   14360:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  14361:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  14362:                                     }
                   14363:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   14364:                                 }
1.1065    raeburn  14365:                             }
                   14366:                         }
1.1292    raeburn  14367:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  14368:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  14369:                         }
1.1065    raeburn  14370:                     }
                   14371:                 } else {
                   14372:                     ($decompressed,$display) = 
                   14373:                         &decompress_uploaded_file($file,$dir);
                   14374:                 }
1.1055    raeburn  14375:                 if ($decompressed eq 'ok') {
1.1065    raeburn  14376:                     $output = '<p class="LC_info">'.
                   14377:                               &mt('Files extracted successfully from archive.').
                   14378:                               '</p>'."\n";
1.1055    raeburn  14379:                     my ($warning,$result,@contents);
                   14380:                     my ($newdirlistref,$newlisterror) =
                   14381:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   14382:                                                  $docuname,1);
                   14383:                     my (%is_dir,%changes,@newitems);
                   14384:                     my $dirptr = 16384;
1.1065    raeburn  14385:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  14386:                         foreach my $dir_line (@{$newdirlistref}) {
                   14387:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  14388:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  14389:                                 push(@newitems,$item);
                   14390:                                 if ($dirptr&$testdir) {
                   14391:                                     $is_dir{$item} = 1;
                   14392:                                 }
                   14393:                                 $changes{$item} = 1;
                   14394:                             }
                   14395:                         }
                   14396:                     }
                   14397:                     if (keys(%changes) > 0) {
                   14398:                         foreach my $item (sort(@newitems)) {
                   14399:                             if ($changes{$item}) {
                   14400:                                 push(@contents,$item);
                   14401:                             }
                   14402:                         }
                   14403:                     }
                   14404:                     if (@contents > 0) {
1.1067    raeburn  14405:                         my $wantform;
                   14406:                         unless ($env{'form.autoextract_camtasia'}) {
                   14407:                             $wantform = 1;
                   14408:                         }
1.1056    raeburn  14409:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  14410:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   14411:                                                                 $currdir,\%is_dir,
                   14412:                                                                 \%children,\%parent,
1.1056    raeburn  14413:                                                                 \@contents,\%dirorder,
                   14414:                                                                 \%titles,$wantform);
1.1055    raeburn  14415:                         if ($datatable ne '') {
                   14416:                             $output .= &archive_options_form('decompressed',$datatable,
                   14417:                                                              $count,$hiddenelem);
1.1065    raeburn  14418:                             my $startcount = 6;
1.1055    raeburn  14419:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  14420:                                                            \%titles,\%children);
1.1055    raeburn  14421:                         }
1.1067    raeburn  14422:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  14423:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  14424:                             my %displayed;
                   14425:                             my $total = 1;
                   14426:                             $env{'form.archive_directory'} = [];
                   14427:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   14428:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   14429:                                 $path =~ s{/$}{};
                   14430:                                 my $item;
                   14431:                                 if ($path ne '') {
                   14432:                                     $item = "$path/$titles{$i}";
                   14433:                                 } else {
                   14434:                                     $item = $titles{$i};
                   14435:                                 }
                   14436:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   14437:                                 if ($item eq $contents[0]) {
                   14438:                                     push(@{$env{'form.archive_directory'}},$i);
                   14439:                                     $env{'form.archive_'.$i} = 'display';
                   14440:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   14441:                                     $displayed{'folder'} = $i;
1.1164    raeburn  14442:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   14443:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  14444:                                     $env{'form.archive_'.$i} = 'display';
                   14445:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   14446:                                     $displayed{'web'} = $i;
                   14447:                                 } else {
1.1164    raeburn  14448:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   14449:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   14450:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  14451:                                         push(@{$env{'form.archive_directory'}},$i);
                   14452:                                     }
                   14453:                                     $env{'form.archive_'.$i} = 'dependency';
                   14454:                                 }
                   14455:                                 $total ++;
                   14456:                             }
                   14457:                             for (my $i=1; $i<$total; $i++) {
                   14458:                                 next if ($i == $displayed{'web'});
                   14459:                                 next if ($i == $displayed{'folder'});
                   14460:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   14461:                             }
                   14462:                             $env{'form.phase'} = 'decompress_cleanup';
                   14463:                             $env{'form.archivedelete'} = 1;
                   14464:                             $env{'form.archive_count'} = $total-1;
                   14465:                             $output .=
                   14466:                                 &process_extracted_files('coursedocs',$docudom,
                   14467:                                                          $docuname,$destination,
                   14468:                                                          $dir_root,$hiddenelem);
                   14469:                         }
1.1055    raeburn  14470:                     } else {
                   14471:                         $warning = &mt('No new items extracted from archive file.');
                   14472:                     }
                   14473:                 } else {
                   14474:                     $output = $display;
                   14475:                     $error = &mt('An error occurred during extraction from the archive file.');
                   14476:                 }
                   14477:             }
                   14478:         }
                   14479:     }
                   14480:     if ($error) {
                   14481:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14482:                    $error.'</p>'."\n";
                   14483:     }
                   14484:     if ($warning) {
                   14485:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14486:     }
                   14487:     return $output;
                   14488: }
                   14489: 
                   14490: sub get_extracted {
1.1056    raeburn  14491:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   14492:         $titles,$wantform) = @_;
1.1055    raeburn  14493:     my $count = 0;
                   14494:     my $depth = 0;
                   14495:     my $datatable;
1.1056    raeburn  14496:     my @hierarchy;
1.1055    raeburn  14497:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  14498:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   14499:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  14500:     foreach my $item (@{$contents}) {
                   14501:         $count ++;
1.1056    raeburn  14502:         @{$dirorder->{$count}} = @hierarchy;
                   14503:         $titles->{$count} = $item;
1.1055    raeburn  14504:         &archive_hierarchy($depth,$count,$parent,$children);
                   14505:         if ($wantform) {
                   14506:             $datatable .= &archive_row($is_dir->{$item},$item,
                   14507:                                        $currdir,$depth,$count);
                   14508:         }
                   14509:         if ($is_dir->{$item}) {
                   14510:             $depth ++;
1.1056    raeburn  14511:             push(@hierarchy,$count);
                   14512:             $parent->{$depth} = $count;
1.1055    raeburn  14513:             $datatable .=
                   14514:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  14515:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   14516:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  14517:             $depth --;
1.1056    raeburn  14518:             pop(@hierarchy);
1.1055    raeburn  14519:         }
                   14520:     }
                   14521:     return ($count,$datatable);
                   14522: }
                   14523: 
                   14524: sub recurse_extracted_archive {
1.1056    raeburn  14525:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   14526:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  14527:     my $result='';
1.1056    raeburn  14528:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   14529:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   14530:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  14531:         return $result;
                   14532:     }
                   14533:     my $dirptr = 16384;
                   14534:     my ($newdirlistref,$newlisterror) =
                   14535:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   14536:     if (ref($newdirlistref) eq 'ARRAY') {
                   14537:         foreach my $dir_line (@{$newdirlistref}) {
                   14538:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   14539:             unless ($item =~ /^\.+$/) {
                   14540:                 $$count ++;
1.1056    raeburn  14541:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   14542:                 $titles->{$$count} = $item;
1.1055    raeburn  14543:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  14544: 
1.1055    raeburn  14545:                 my $is_dir;
                   14546:                 if ($dirptr&$testdir) {
                   14547:                     $is_dir = 1;
                   14548:                 }
                   14549:                 if ($wantform) {
                   14550:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   14551:                 }
                   14552:                 if ($is_dir) {
                   14553:                     $$depth ++;
1.1056    raeburn  14554:                     push(@{$hierarchy},$$count);
                   14555:                     $parent->{$$depth} = $$count;
1.1055    raeburn  14556:                     $result .=
                   14557:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   14558:                                                    $docuname,$depth,$count,
1.1056    raeburn  14559:                                                    $hierarchy,$dirorder,$children,
                   14560:                                                    $parent,$titles,$wantform);
1.1055    raeburn  14561:                     $$depth --;
1.1056    raeburn  14562:                     pop(@{$hierarchy});
1.1055    raeburn  14563:                 }
                   14564:             }
                   14565:         }
                   14566:     }
                   14567:     return $result;
                   14568: }
                   14569: 
                   14570: sub archive_hierarchy {
                   14571:     my ($depth,$count,$parent,$children) =@_;
                   14572:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   14573:         if (exists($parent->{$depth})) {
                   14574:              $children->{$parent->{$depth}} .= $count.':';
                   14575:         }
                   14576:     }
                   14577:     return;
                   14578: }
                   14579: 
                   14580: sub archive_row {
                   14581:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   14582:     my ($name) = ($item =~ m{([^/]+)$});
                   14583:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  14584:                                        'display'    => 'Add as file',
1.1055    raeburn  14585:                                        'dependency' => 'Include as dependency',
                   14586:                                        'discard'    => 'Discard',
                   14587:                                       );
                   14588:     if ($is_dir) {
1.1059    raeburn  14589:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  14590:     }
1.1056    raeburn  14591:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   14592:     my $offset = 0;
1.1055    raeburn  14593:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  14594:         $offset ++;
1.1065    raeburn  14595:         if ($action ne 'display') {
                   14596:             $offset ++;
                   14597:         }  
1.1055    raeburn  14598:         $output .= '<td><span class="LC_nobreak">'.
                   14599:                    '<label><input type="radio" name="archive_'.$count.
                   14600:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   14601:         my $text = $choices{$action};
                   14602:         if ($is_dir) {
                   14603:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   14604:             if ($action eq 'display') {
1.1059    raeburn  14605:                 $text = &mt('Add as folder');
1.1055    raeburn  14606:             }
1.1056    raeburn  14607:         } else {
                   14608:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   14609: 
                   14610:         }
                   14611:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   14612:         if ($action eq 'dependency') {
                   14613:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   14614:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   14615:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   14616:                        '<option value=""></option>'."\n".
                   14617:                        '</select>'."\n".
                   14618:                        '</div>';
1.1059    raeburn  14619:         } elsif ($action eq 'display') {
                   14620:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   14621:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   14622:                        '</div>';
1.1055    raeburn  14623:         }
1.1056    raeburn  14624:         $output .= '</td>';
1.1055    raeburn  14625:     }
                   14626:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   14627:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   14628:     for (my $i=0; $i<$depth; $i++) {
                   14629:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   14630:     }
                   14631:     if ($is_dir) {
                   14632:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   14633:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   14634:     } else {
                   14635:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   14636:     }
                   14637:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   14638:                &end_data_table_row();
                   14639:     return $output;
                   14640: }
                   14641: 
                   14642: sub archive_options_form {
1.1065    raeburn  14643:     my ($form,$display,$count,$hiddenelem) = @_;
                   14644:     my %lt = &Apache::lonlocal::texthash(
                   14645:                perm => 'Permanently remove archive file?',
                   14646:                hows => 'How should each extracted item be incorporated in the course?',
                   14647:                cont => 'Content actions for all',
                   14648:                addf => 'Add as folder/file',
                   14649:                incd => 'Include as dependency for a displayed file',
                   14650:                disc => 'Discard',
                   14651:                no   => 'No',
                   14652:                yes  => 'Yes',
                   14653:                save => 'Save',
                   14654:     );
                   14655:     my $output = <<"END";
                   14656: <form name="$form" method="post" action="">
                   14657: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   14658: <label>
                   14659:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   14660: </label>
                   14661: &nbsp;
                   14662: <label>
                   14663:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   14664: </span>
                   14665: </p>
                   14666: <input type="hidden" name="phase" value="decompress_cleanup" />
                   14667: <br />$lt{'hows'}
                   14668: <div class="LC_columnSection">
                   14669:   <fieldset>
                   14670:     <legend>$lt{'cont'}</legend>
                   14671:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   14672:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   14673:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   14674:   </fieldset>
                   14675: </div>
                   14676: END
                   14677:     return $output.
1.1055    raeburn  14678:            &start_data_table()."\n".
1.1065    raeburn  14679:            $display."\n".
1.1055    raeburn  14680:            &end_data_table()."\n".
                   14681:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   14682:            $hiddenelem.
1.1065    raeburn  14683:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  14684:            '</form>';
                   14685: }
                   14686: 
                   14687: sub archive_javascript {
1.1056    raeburn  14688:     my ($startcount,$numitems,$titles,$children) = @_;
                   14689:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  14690:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  14691:     my $scripttag = <<START;
                   14692: <script type="text/javascript">
                   14693: // <![CDATA[
                   14694: 
                   14695: function checkAll(form,prefix) {
                   14696:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14697:     for (var i=0; i < form.elements.length; i++) {
                   14698:         var id = form.elements[i].id;
                   14699:         if ((id != '') && (id != undefined)) {
                   14700:             if (idstr.test(id)) {
                   14701:                 if (form.elements[i].type == 'radio') {
                   14702:                     form.elements[i].checked = true;
1.1056    raeburn  14703:                     var nostart = i-$startcount;
1.1059    raeburn  14704:                     var offset = nostart%7;
                   14705:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14706:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14707:                 }
                   14708:             }
                   14709:         }
                   14710:     }
                   14711: }
                   14712: 
                   14713: function propagateCheck(form,count) {
                   14714:     if (count > 0) {
1.1059    raeburn  14715:         var startelement = $startcount + ((count-1) * 7);
                   14716:         for (var j=1; j<6; j++) {
                   14717:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14718:                 var item = startelement + j; 
                   14719:                 if (form.elements[item].type == 'radio') {
                   14720:                     if (form.elements[item].checked) {
                   14721:                         containerCheck(form,count,j);
                   14722:                         break;
                   14723:                     }
1.1055    raeburn  14724:                 }
                   14725:             }
                   14726:         }
                   14727:     }
                   14728: }
                   14729: 
                   14730: numitems = $numitems
1.1056    raeburn  14731: var titles = new Array(numitems);
                   14732: var parents = new Array(numitems);
1.1055    raeburn  14733: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14734:     parents[i] = new Array;
1.1055    raeburn  14735: }
1.1059    raeburn  14736: var maintitle = '$maintitle';
1.1055    raeburn  14737: 
                   14738: START
                   14739: 
1.1056    raeburn  14740:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14741:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14742:         for (my $i=0; $i<@contents; $i ++) {
                   14743:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14744:         }
                   14745:     }
                   14746: 
1.1056    raeburn  14747:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14748:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14749:     }
                   14750: 
1.1055    raeburn  14751:     $scripttag .= <<END;
                   14752: 
                   14753: function containerCheck(form,count,offset) {
                   14754:     if (count > 0) {
1.1056    raeburn  14755:         dependencyCheck(form,count,offset);
1.1059    raeburn  14756:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14757:         form.elements[item].checked = true;
                   14758:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14759:             if (parents[count].length > 0) {
                   14760:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14761:                     containerCheck(form,parents[count][j],offset);
                   14762:                 }
                   14763:             }
                   14764:         }
                   14765:     }
                   14766: }
                   14767: 
                   14768: function dependencyCheck(form,count,offset) {
                   14769:     if (count > 0) {
1.1059    raeburn  14770:         var chosen = (offset+$startcount)+7*(count-1);
                   14771:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14772:         var currtype = form.elements[depitem].type;
                   14773:         if (form.elements[chosen].value == 'dependency') {
                   14774:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14775:             form.elements[depitem].options.length = 0;
                   14776:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14777:             for (var i=1; i<=numitems; i++) {
                   14778:                 if (i == count) {
                   14779:                     continue;
                   14780:                 }
1.1059    raeburn  14781:                 var startelement = $startcount + (i-1) * 7;
                   14782:                 for (var j=1; j<6; j++) {
                   14783:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14784:                         var item = startelement + j;
                   14785:                         if (form.elements[item].type == 'radio') {
                   14786:                             if (form.elements[item].checked) {
                   14787:                                 if (form.elements[item].value == 'display') {
                   14788:                                     var n = form.elements[depitem].options.length;
                   14789:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14790:                                 }
                   14791:                             }
                   14792:                         }
                   14793:                     }
                   14794:                 }
                   14795:             }
                   14796:         } else {
                   14797:             document.getElementById('arc_depon_'+count).style.display='none';
                   14798:             form.elements[depitem].options.length = 0;
                   14799:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14800:         }
1.1059    raeburn  14801:         titleCheck(form,count,offset);
1.1056    raeburn  14802:     }
                   14803: }
                   14804: 
                   14805: function propagateSelect(form,count,offset) {
                   14806:     if (count > 0) {
1.1065    raeburn  14807:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14808:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14809:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14810:             if (parents[count].length > 0) {
                   14811:                 for (var j=0; j<parents[count].length; j++) {
                   14812:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14813:                 }
                   14814:             }
                   14815:         }
                   14816:     }
                   14817: }
1.1056    raeburn  14818: 
                   14819: function containerSelect(form,count,offset,picked) {
                   14820:     if (count > 0) {
1.1065    raeburn  14821:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14822:         if (form.elements[item].type == 'radio') {
                   14823:             if (form.elements[item].value == 'dependency') {
                   14824:                 if (form.elements[item+1].type == 'select-one') {
                   14825:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14826:                         if (form.elements[item+1].options[i].value == picked) {
                   14827:                             form.elements[item+1].selectedIndex = i;
                   14828:                             break;
                   14829:                         }
                   14830:                     }
                   14831:                 }
                   14832:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14833:                     if (parents[count].length > 0) {
                   14834:                         for (var j=0; j<parents[count].length; j++) {
                   14835:                             containerSelect(form,parents[count][j],offset,picked);
                   14836:                         }
                   14837:                     }
                   14838:                 }
                   14839:             }
                   14840:         }
                   14841:     }
                   14842: }
                   14843: 
1.1059    raeburn  14844: function titleCheck(form,count,offset) {
                   14845:     if (count > 0) {
                   14846:         var chosen = (offset+$startcount)+7*(count-1);
                   14847:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14848:         var currtype = form.elements[depitem].type;
                   14849:         if (form.elements[chosen].value == 'display') {
                   14850:             document.getElementById('arc_title_'+count).style.display='block';
                   14851:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14852:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14853:             }
                   14854:         } else {
                   14855:             document.getElementById('arc_title_'+count).style.display='none';
                   14856:             if (currtype == 'text') { 
                   14857:                 document.getElementById('archive_title_'+count).value='';
                   14858:             }
                   14859:         }
                   14860:     }
                   14861:     return;
                   14862: }
                   14863: 
1.1055    raeburn  14864: // ]]>
                   14865: </script>
                   14866: END
                   14867:     return $scripttag;
                   14868: }
                   14869: 
                   14870: sub process_extracted_files {
1.1067    raeburn  14871:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14872:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14873:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14874:     my @ids=&Apache::lonnet::current_machine_ids();
                   14875:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14876:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14877:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14878:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14879:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14880:         $pathtocheck = "$dir_root/$destination";
                   14881:         $dir = $dir_root;
                   14882:         $ishome = 1;
                   14883:     } else {
                   14884:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14885:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14886:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14887:     }
                   14888:     my $currdir = "$dir_root/$destination";
                   14889:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14890:     if ($env{'form.folderpath'}) {
                   14891:         my @items = split('&',$env{'form.folderpath'});
                   14892:         $folders{'0'} = $items[-2];
1.1099    raeburn  14893:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14894:             $containers{'0'}='page';
                   14895:         } else {  
                   14896:             $containers{'0'}='sequence';
                   14897:         }
1.1055    raeburn  14898:     }
                   14899:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14900:     if ($numitems) {
                   14901:         for (my $i=1; $i<=$numitems; $i++) {
                   14902:             my $path = $env{'form.archive_content_'.$i};
                   14903:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14904:                 my $item = $1;
                   14905:                 $toplevelitems{$item} = $i;
                   14906:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14907:                     $is_dir{$item} = 1;
                   14908:                 }
                   14909:             }
                   14910:         }
                   14911:     }
1.1067    raeburn  14912:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14913:     if (keys(%toplevelitems) > 0) {
                   14914:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14915:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14916:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14917:     }
1.1066    raeburn  14918:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14919:     if ($numitems) {
                   14920:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14921:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14922:             my $path = $env{'form.archive_content_'.$i};
                   14923:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14924:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14925:                     if ($prefix ne '' && $path ne '') {
                   14926:                         if (-e $prefix.$path) {
1.1066    raeburn  14927:                             if ((@archdirs > 0) && 
                   14928:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14929:                                 $todeletedir{$prefix.$path} = 1;
                   14930:                             } else {
                   14931:                                 $todelete{$prefix.$path} = 1;
                   14932:                             }
1.1055    raeburn  14933:                         }
                   14934:                     }
                   14935:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14936:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14937:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14938:                     $docstitle = $env{'form.archive_title_'.$i};
                   14939:                     if ($docstitle eq '') {
                   14940:                         $docstitle = $title;
                   14941:                     }
1.1055    raeburn  14942:                     $outer = 0;
1.1056    raeburn  14943:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14944:                         if (@{$dirorder{$i}} > 0) {
                   14945:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14946:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14947:                                     $outer = $item;
                   14948:                                     last;
                   14949:                                 }
                   14950:                             }
                   14951:                         }
                   14952:                     }
                   14953:                     my ($errtext,$fatal) = 
                   14954:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14955:                                                '/'.$folders{$outer}.'.'.
                   14956:                                                $containers{$outer});
                   14957:                     next if ($fatal);
                   14958:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14959:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14960:                             $mapinner{$i} = time;
1.1055    raeburn  14961:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14962:                             $containers{$i} = 'sequence';
                   14963:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14964:                                       $folders{$i}.'.'.$containers{$i};
                   14965:                             my $newidx = &LONCAPA::map::getresidx();
                   14966:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14967:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14968:                             push(@LONCAPA::map::order,$newidx);
                   14969:                             my ($outtext,$errtext) =
                   14970:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14971:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14972:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14973:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14974:                             unless ($errtext) {
1.1294    raeburn  14975:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14976:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14977:                                             '</li>'."\n";
1.1067    raeburn  14978:                             }
1.1055    raeburn  14979:                         }
                   14980:                     } else {
                   14981:                         if ($context eq 'coursedocs') {
                   14982:                             my $newidx=&LONCAPA::map::getresidx();
                   14983:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14984:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14985:                                       $title;
1.1392    raeburn  14986:                             if (($outer !~ /\D/) &&
                   14987:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14988:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  14989:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14990:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14991:                                 }
                   14992:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14993:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14994:                                 }
                   14995:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14996:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14997:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14998:                                         unless ($ishome) {
                   14999:                                             my $fetch = "$newdest{$i}/$title";
                   15000:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   15001:                                             $prompttofetch{$fetch} = 1;
                   15002:                                         }
1.1292    raeburn  15003:                                     }
1.1067    raeburn  15004:                                 }
1.1294    raeburn  15005:                                 $LONCAPA::map::resources[$newidx]=
                   15006:                                     $docstitle.':'.$url.':false:normal:res';
                   15007:                                 push(@LONCAPA::map::order, $newidx);
                   15008:                                 my ($outtext,$errtext)=
                   15009:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   15010:                                                             $docuname.'/'.$folders{$outer}.
                   15011:                                                             '.'.$containers{$outer},1,1);
                   15012:                                 unless ($errtext) {
                   15013:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   15014:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   15015:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   15016:                                                    '</li>'."\n";
                   15017:                                     }
1.1067    raeburn  15018:                                 }
1.1294    raeburn  15019:                             } else {
                   15020:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   15021:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  15022:                             }
1.1055    raeburn  15023:                         }
                   15024:                     }
1.1086    raeburn  15025:                 }
                   15026:             } else {
1.1294    raeburn  15027:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   15028:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  15029:             }
                   15030:         }
                   15031:         for (my $i=1; $i<=$numitems; $i++) {
                   15032:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   15033:             my $path = $env{'form.archive_content_'.$i};
                   15034:             if ($path =~ /^\Q$pathtocheck\E/) {
                   15035:                 my ($title) = ($path =~ m{/([^/]+)$});
                   15036:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   15037:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   15038:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   15039:                         my ($itemidx,$fullpath,$relpath);
                   15040:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   15041:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  15042:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  15043:                                 if ($dirorder{$i}->[$j] eq $container) {
                   15044:                                     $itemidx = $j;
1.1056    raeburn  15045:                                 }
                   15046:                             }
1.1086    raeburn  15047:                         }
                   15048:                         if ($itemidx eq '') {
                   15049:                             $itemidx =  0;
                   15050:                         } 
                   15051:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   15052:                             if ($mapinner{$referrer{$i}}) {
                   15053:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   15054:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15055:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15056:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15057:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15058:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15059:                                             if (!-e $fullpath) {
                   15060:                                                 mkdir($fullpath,0755);
1.1056    raeburn  15061:                                             }
                   15062:                                         }
1.1086    raeburn  15063:                                     } else {
                   15064:                                         last;
1.1056    raeburn  15065:                                     }
1.1086    raeburn  15066:                                 }
                   15067:                             }
                   15068:                         } elsif ($newdest{$referrer{$i}}) {
                   15069:                             $fullpath = $newdest{$referrer{$i}};
                   15070:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15071:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   15072:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   15073:                                     last;
                   15074:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15075:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15076:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15077:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15078:                                         if (!-e $fullpath) {
                   15079:                                             mkdir($fullpath,0755);
1.1056    raeburn  15080:                                         }
                   15081:                                     }
1.1086    raeburn  15082:                                 } else {
                   15083:                                     last;
1.1056    raeburn  15084:                                 }
1.1055    raeburn  15085:                             }
                   15086:                         }
1.1086    raeburn  15087:                         if ($fullpath ne '') {
                   15088:                             if (-e "$prefix$path") {
1.1292    raeburn  15089:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   15090:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   15091:                                 }
1.1086    raeburn  15092:                             }
                   15093:                             if (-e "$fullpath/$title") {
                   15094:                                 my $showpath;
                   15095:                                 if ($relpath ne '') {
                   15096:                                     $showpath = "$relpath/$title";
                   15097:                                 } else {
                   15098:                                     $showpath = "/$title";
                   15099:                                 } 
1.1294    raeburn  15100:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   15101:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   15102:                                            '</li>'."\n";
1.1292    raeburn  15103:                                 unless ($ishome) {
                   15104:                                     my $fetch = "$fullpath/$title";
                   15105:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   15106:                                     $prompttofetch{$fetch} = 1;
                   15107:                                 }
1.1086    raeburn  15108:                             }
                   15109:                         }
1.1055    raeburn  15110:                     }
1.1086    raeburn  15111:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   15112:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  15113:                                     &HTML::Entities::encode($path,'<>&"'),
                   15114:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   15115:                                 '<br />';
1.1055    raeburn  15116:                 }
                   15117:             } else {
1.1294    raeburn  15118:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  15119:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  15120:             }
                   15121:         }
                   15122:         if (keys(%todelete)) {
                   15123:             foreach my $key (keys(%todelete)) {
                   15124:                 unlink($key);
1.1066    raeburn  15125:             }
                   15126:         }
                   15127:         if (keys(%todeletedir)) {
                   15128:             foreach my $key (keys(%todeletedir)) {
                   15129:                 rmdir($key);
                   15130:             }
                   15131:         }
                   15132:         foreach my $dir (sort(keys(%is_dir))) {
                   15133:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   15134:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  15135:             }
                   15136:         }
1.1067    raeburn  15137:         if ($result ne '') {
                   15138:             $output .= '<ul>'."\n".
                   15139:                        $result."\n".
                   15140:                        '</ul>';
                   15141:         }
                   15142:         unless ($ishome) {
                   15143:             my $replicationfail;
                   15144:             foreach my $item (keys(%prompttofetch)) {
                   15145:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   15146:                 unless ($fetchresult eq 'ok') {
                   15147:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   15148:                 }
                   15149:             }
                   15150:             if ($replicationfail) {
                   15151:                 $output .= '<p class="LC_error">'.
                   15152:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   15153:                            $replicationfail.
                   15154:                            '</ul></p>';
                   15155:             }
                   15156:         }
1.1055    raeburn  15157:     } else {
                   15158:         $warning = &mt('No items found in archive.');
                   15159:     }
                   15160:     if ($error) {
                   15161:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   15162:                    $error.'</p>'."\n";
                   15163:     }
                   15164:     if ($warning) {
                   15165:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   15166:     }
                   15167:     return $output;
                   15168: }
                   15169: 
1.1066    raeburn  15170: sub cleanup_empty_dirs {
                   15171:     my ($path) = @_;
                   15172:     if (($path ne '') && (-d $path)) {
                   15173:         if (opendir(my $dirh,$path)) {
                   15174:             my @dircontents = grep(!/^\./,readdir($dirh));
                   15175:             my $numitems = 0;
                   15176:             foreach my $item (@dircontents) {
                   15177:                 if (-d "$path/$item") {
1.1111    raeburn  15178:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  15179:                     if (-e "$path/$item") {
                   15180:                         $numitems ++;
                   15181:                     }
                   15182:                 } else {
                   15183:                     $numitems ++;
                   15184:                 }
                   15185:             }
                   15186:             if ($numitems == 0) {
                   15187:                 rmdir($path);
                   15188:             }
                   15189:             closedir($dirh);
                   15190:         }
                   15191:     }
                   15192:     return;
                   15193: }
                   15194: 
1.41      ng       15195: =pod
1.45      matthew  15196: 
1.1162    raeburn  15197: =item * &get_folder_hierarchy()
1.1068    raeburn  15198: 
                   15199: Provides hierarchy of names of folders/sub-folders containing the current
                   15200: item,
                   15201: 
                   15202: Inputs: 3
                   15203:      - $navmap - navmaps object
                   15204: 
                   15205:      - $map - url for map (either the trigger itself, or map containing
                   15206:                            the resource, which is the trigger).
                   15207: 
                   15208:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   15209: 
                   15210: Outputs: 1 @pathitems - array of folder/subfolder names.
                   15211: 
                   15212: =cut
                   15213: 
                   15214: sub get_folder_hierarchy {
                   15215:     my ($navmap,$map,$showitem) = @_;
                   15216:     my @pathitems;
                   15217:     if (ref($navmap)) {
                   15218:         my $mapres = $navmap->getResourceByUrl($map);
                   15219:         if (ref($mapres)) {
                   15220:             my $pcslist = $mapres->map_hierarchy();
                   15221:             if ($pcslist ne '') {
                   15222:                 my @pcs = split(/,/,$pcslist);
                   15223:                 foreach my $pc (@pcs) {
                   15224:                     if ($pc == 1) {
1.1129    raeburn  15225:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  15226:                     } else {
                   15227:                         my $res = $navmap->getByMapPc($pc);
                   15228:                         if (ref($res)) {
                   15229:                             my $title = $res->compTitle();
                   15230:                             $title =~ s/\W+/_/g;
                   15231:                             if ($title ne '') {
                   15232:                                 push(@pathitems,$title);
                   15233:                             }
                   15234:                         }
                   15235:                     }
                   15236:                 }
                   15237:             }
1.1071    raeburn  15238:             if ($showitem) {
                   15239:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  15240:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  15241:                 } else {
                   15242:                     my $maptitle = $mapres->compTitle();
                   15243:                     $maptitle =~ s/\W+/_/g;
                   15244:                     if ($maptitle ne '') {
                   15245:                         push(@pathitems,$maptitle);
                   15246:                     }
1.1068    raeburn  15247:                 }
                   15248:             }
                   15249:         }
                   15250:     }
                   15251:     return @pathitems;
                   15252: }
                   15253: 
                   15254: =pod
                   15255: 
1.1015    raeburn  15256: =item * &get_turnedin_filepath()
                   15257: 
                   15258: Determines path in a user's portfolio file for storage of files uploaded
                   15259: to a specific essayresponse or dropbox item.
                   15260: 
                   15261: Inputs: 3 required + 1 optional.
                   15262: $symb is symb for resource, $uname and $udom are for current user (required).
                   15263: $caller is optional (can be "submission", if routine is called when storing
                   15264: an upoaded file when "Submit Answer" button was pressed).
                   15265: 
                   15266: Returns array containing $path and $multiresp. 
                   15267: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   15268: than one file upload item.  Callers of routine should append partid as a 
                   15269: subdirectory to $path in cases where $multiresp is 1.
                   15270: 
                   15271: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   15272: 
                   15273: =cut
                   15274: 
                   15275: sub get_turnedin_filepath {
                   15276:     my ($symb,$uname,$udom,$caller) = @_;
                   15277:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   15278:     my $turnindir;
                   15279:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   15280:     $turnindir = $userhash{'turnindir'};
                   15281:     my ($path,$multiresp);
                   15282:     if ($turnindir eq '') {
                   15283:         if ($caller eq 'submission') {
                   15284:             $turnindir = &mt('turned in');
                   15285:             $turnindir =~ s/\W+/_/g;
                   15286:             my %newhash = (
                   15287:                             'turnindir' => $turnindir,
                   15288:                           );
                   15289:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   15290:         }
                   15291:     }
                   15292:     if ($turnindir ne '') {
                   15293:         $path = '/'.$turnindir.'/';
                   15294:         my ($multipart,$turnin,@pathitems);
                   15295:         my $navmap = Apache::lonnavmaps::navmap->new();
                   15296:         if (defined($navmap)) {
                   15297:             my $mapres = $navmap->getResourceByUrl($map);
                   15298:             if (ref($mapres)) {
                   15299:                 my $pcslist = $mapres->map_hierarchy();
                   15300:                 if ($pcslist ne '') {
                   15301:                     foreach my $pc (split(/,/,$pcslist)) {
                   15302:                         my $res = $navmap->getByMapPc($pc);
                   15303:                         if (ref($res)) {
                   15304:                             my $title = $res->compTitle();
                   15305:                             $title =~ s/\W+/_/g;
                   15306:                             if ($title ne '') {
1.1149    raeburn  15307:                                 if (($pc > 1) && (length($title) > 12)) {
                   15308:                                     $title = substr($title,0,12);
                   15309:                                 }
1.1015    raeburn  15310:                                 push(@pathitems,$title);
                   15311:                             }
                   15312:                         }
                   15313:                     }
                   15314:                 }
                   15315:                 my $maptitle = $mapres->compTitle();
                   15316:                 $maptitle =~ s/\W+/_/g;
                   15317:                 if ($maptitle ne '') {
1.1149    raeburn  15318:                     if (length($maptitle) > 12) {
                   15319:                         $maptitle = substr($maptitle,0,12);
                   15320:                     }
1.1015    raeburn  15321:                     push(@pathitems,$maptitle);
                   15322:                 }
                   15323:                 unless ($env{'request.state'} eq 'construct') {
                   15324:                     my $res = $navmap->getBySymb($symb);
                   15325:                     if (ref($res)) {
                   15326:                         my $partlist = $res->parts();
                   15327:                         my $totaluploads = 0;
                   15328:                         if (ref($partlist) eq 'ARRAY') {
                   15329:                             foreach my $part (@{$partlist}) {
                   15330:                                 my @types = $res->responseType($part);
                   15331:                                 my @ids = $res->responseIds($part);
                   15332:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   15333:                                     if ($types[$i] eq 'essay') {
                   15334:                                         my $partid = $part.'_'.$ids[$i];
                   15335:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   15336:                                             $totaluploads ++;
                   15337:                                         }
                   15338:                                     }
                   15339:                                 }
                   15340:                             }
                   15341:                             if ($totaluploads > 1) {
                   15342:                                 $multiresp = 1;
                   15343:                             }
                   15344:                         }
                   15345:                     }
                   15346:                 }
                   15347:             } else {
                   15348:                 return;
                   15349:             }
                   15350:         } else {
                   15351:             return;
                   15352:         }
                   15353:         my $restitle=&Apache::lonnet::gettitle($symb);
                   15354:         $restitle =~ s/\W+/_/g;
                   15355:         if ($restitle eq '') {
                   15356:             $restitle = ($resurl =~ m{/[^/]+$});
                   15357:             if ($restitle eq '') {
                   15358:                 $restitle = time;
                   15359:             }
                   15360:         }
1.1149    raeburn  15361:         if (length($restitle) > 12) {
                   15362:             $restitle = substr($restitle,0,12);
                   15363:         }
1.1015    raeburn  15364:         push(@pathitems,$restitle);
                   15365:         $path .= join('/',@pathitems);
                   15366:     }
                   15367:     return ($path,$multiresp);
                   15368: }
                   15369: 
                   15370: =pod
                   15371: 
1.464     albertel 15372: =back
1.41      ng       15373: 
1.112     bowersj2 15374: =head1 CSV Upload/Handling functions
1.38      albertel 15375: 
1.41      ng       15376: =over 4
                   15377: 
1.648     raeburn  15378: =item * &upfile_store($r)
1.41      ng       15379: 
                   15380: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 15381: needs $env{'form.upfile'}
1.41      ng       15382: returns $datatoken to be put into hidden field
                   15383: 
                   15384: =cut
1.31      albertel 15385: 
                   15386: sub upfile_store {
                   15387:     my $r=shift;
1.258     albertel 15388:     $env{'form.upfile'}=~s/\r/\n/gs;
                   15389:     $env{'form.upfile'}=~s/\f/\n/gs;
                   15390:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   15391:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 15392: 
1.1299    raeburn  15393:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   15394:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   15395:                                      time.'_'.$$);
                   15396:     return if ($datatoken eq '');
                   15397: 
1.31      albertel 15398:     {
1.158     raeburn  15399:         my $datafile = $r->dir_config('lonDaemons').
                   15400:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15401:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 15402:             print $fh $env{'form.upfile'};
1.158     raeburn  15403:             close($fh);
                   15404:         }
1.31      albertel 15405:     }
                   15406:     return $datatoken;
                   15407: }
                   15408: 
1.56      matthew  15409: =pod
                   15410: 
1.1290    raeburn  15411: =item * &load_tmp_file($r,$datatoken)
1.41      ng       15412: 
                   15413: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  15414: $datatoken is the name to assign to the temporary file.
1.258     albertel 15415: sets $env{'form.upfile'} to the contents of the file
1.41      ng       15416: 
                   15417: =cut
1.31      albertel 15418: 
                   15419: sub load_tmp_file {
1.1290    raeburn  15420:     my ($r,$datatoken) = @_;
                   15421:     return if ($datatoken eq '');
1.31      albertel 15422:     my @studentdata=();
                   15423:     {
1.158     raeburn  15424:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  15425:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15426:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  15427:             @studentdata=<$fh>;
                   15428:             close($fh);
                   15429:         }
1.31      albertel 15430:     }
1.258     albertel 15431:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 15432: }
                   15433: 
1.1290    raeburn  15434: sub valid_datatoken {
                   15435:     my ($datatoken) = @_;
1.1325    raeburn  15436:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  15437:         return $datatoken;
                   15438:     }
                   15439:     return;
                   15440: }
                   15441: 
1.56      matthew  15442: =pod
                   15443: 
1.648     raeburn  15444: =item * &upfile_record_sep()
1.41      ng       15445: 
                   15446: Separate uploaded file into records
                   15447: returns array of records,
1.258     albertel 15448: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       15449: 
                   15450: =cut
1.31      albertel 15451: 
                   15452: sub upfile_record_sep {
1.258     albertel 15453:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 15454:     } else {
1.248     albertel 15455: 	my @records;
1.258     albertel 15456: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 15457: 	    if ($line=~/^\s*$/) { next; }
                   15458: 	    push(@records,$line);
                   15459: 	}
                   15460: 	return @records;
1.31      albertel 15461:     }
                   15462: }
                   15463: 
1.56      matthew  15464: =pod
                   15465: 
1.648     raeburn  15466: =item * &record_sep($record)
1.41      ng       15467: 
1.258     albertel 15468: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       15469: 
                   15470: =cut
                   15471: 
1.263     www      15472: sub takeleft {
                   15473:     my $index=shift;
                   15474:     return substr('0000'.$index,-4,4);
                   15475: }
                   15476: 
1.31      albertel 15477: sub record_sep {
                   15478:     my $record=shift;
                   15479:     my %components=();
1.258     albertel 15480:     if ($env{'form.upfiletype'} eq 'xml') {
                   15481:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 15482:         my $i=0;
1.356     albertel 15483:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 15484:             $field=~s/^(\"|\')//;
                   15485:             $field=~s/(\"|\')$//;
1.263     www      15486:             $components{&takeleft($i)}=$field;
1.31      albertel 15487:             $i++;
                   15488:         }
1.258     albertel 15489:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 15490:         my $i=0;
1.356     albertel 15491:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 15492:             $field=~s/^(\"|\')//;
                   15493:             $field=~s/(\"|\')$//;
1.263     www      15494:             $components{&takeleft($i)}=$field;
1.31      albertel 15495:             $i++;
                   15496:         }
                   15497:     } else {
1.561     www      15498:         my $separator=',';
1.480     banghart 15499:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      15500:             $separator=';';
1.480     banghart 15501:         }
1.31      albertel 15502:         my $i=0;
1.561     www      15503: # the character we are looking for to indicate the end of a quote or a record 
                   15504:         my $looking_for=$separator;
                   15505: # do not add the characters to the fields
                   15506:         my $ignore=0;
                   15507: # we just encountered a separator (or the beginning of the record)
                   15508:         my $just_found_separator=1;
                   15509: # store the field we are working on here
                   15510:         my $field='';
                   15511: # work our way through all characters in record
                   15512:         foreach my $character ($record=~/(.)/g) {
                   15513:             if ($character eq $looking_for) {
                   15514:                if ($character ne $separator) {
                   15515: # Found the end of a quote, again looking for separator
                   15516:                   $looking_for=$separator;
                   15517:                   $ignore=1;
                   15518:                } else {
                   15519: # Found a separator, store away what we got
                   15520:                   $components{&takeleft($i)}=$field;
                   15521: 	          $i++;
                   15522:                   $just_found_separator=1;
                   15523:                   $ignore=0;
                   15524:                   $field='';
                   15525:                }
                   15526:                next;
                   15527:             }
                   15528: # single or double quotation marks after a separator indicate beginning of a quote
                   15529: # we are now looking for the end of the quote and need to ignore separators
                   15530:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   15531:                $looking_for=$character;
                   15532:                next;
                   15533:             }
                   15534: # ignore would be true after we reached the end of a quote
                   15535:             if ($ignore) { next; }
                   15536:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   15537:             $field.=$character;
                   15538:             $just_found_separator=0; 
1.31      albertel 15539:         }
1.561     www      15540: # catch the very last entry, since we never encountered the separator
                   15541:         $components{&takeleft($i)}=$field;
1.31      albertel 15542:     }
                   15543:     return %components;
                   15544: }
                   15545: 
1.144     matthew  15546: ######################################################
                   15547: ######################################################
                   15548: 
1.56      matthew  15549: =pod
                   15550: 
1.648     raeburn  15551: =item * &upfile_select_html()
1.41      ng       15552: 
1.144     matthew  15553: Return HTML code to select a file from the users machine and specify 
                   15554: the file type.
1.41      ng       15555: 
                   15556: =cut
                   15557: 
1.144     matthew  15558: ######################################################
                   15559: ######################################################
1.31      albertel 15560: sub upfile_select_html {
1.144     matthew  15561:     my %Types = (
                   15562:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 15563:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  15564:                  space => &mt('Space separated'),
                   15565:                  tab   => &mt('Tabulator separated'),
                   15566: #                 xml   => &mt('HTML/XML'),
                   15567:                  );
                   15568:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  15569:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  15570:     foreach my $type (sort(keys(%Types))) {
                   15571:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   15572:     }
                   15573:     $Str .= "</select>\n";
                   15574:     return $Str;
1.31      albertel 15575: }
                   15576: 
1.301     albertel 15577: sub get_samples {
                   15578:     my ($records,$toget) = @_;
                   15579:     my @samples=({});
                   15580:     my $got=0;
                   15581:     foreach my $rec (@$records) {
                   15582: 	my %temp = &record_sep($rec);
                   15583: 	if (! grep(/\S/, values(%temp))) { next; }
                   15584: 	if (%temp) {
                   15585: 	    $samples[$got]=\%temp;
                   15586: 	    $got++;
                   15587: 	    if ($got == $toget) { last; }
                   15588: 	}
                   15589:     }
                   15590:     return \@samples;
                   15591: }
                   15592: 
1.144     matthew  15593: ######################################################
                   15594: ######################################################
                   15595: 
1.56      matthew  15596: =pod
                   15597: 
1.648     raeburn  15598: =item * &csv_print_samples($r,$records)
1.41      ng       15599: 
                   15600: Prints a table of sample values from each column uploaded $r is an
                   15601: Apache Request ref, $records is an arrayref from
                   15602: &Apache::loncommon::upfile_record_sep
                   15603: 
                   15604: =cut
                   15605: 
1.144     matthew  15606: ######################################################
                   15607: ######################################################
1.31      albertel 15608: sub csv_print_samples {
                   15609:     my ($r,$records) = @_;
1.662     bisitz   15610:     my $samples = &get_samples($records,5);
1.301     albertel 15611: 
1.594     raeburn  15612:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   15613:               &start_data_table_header_row());
1.356     albertel 15614:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   15615:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  15616:     $r->print(&end_data_table_header_row());
1.301     albertel 15617:     foreach my $hash (@$samples) {
1.594     raeburn  15618: 	$r->print(&start_data_table_row());
1.356     albertel 15619: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 15620: 	    $r->print('<td>');
1.356     albertel 15621: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 15622: 	    $r->print('</td>');
                   15623: 	}
1.594     raeburn  15624: 	$r->print(&end_data_table_row());
1.31      albertel 15625:     }
1.594     raeburn  15626:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 15627: }
                   15628: 
1.144     matthew  15629: ######################################################
                   15630: ######################################################
                   15631: 
1.56      matthew  15632: =pod
                   15633: 
1.648     raeburn  15634: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       15635: 
                   15636: Prints a table to create associations between values and table columns.
1.144     matthew  15637: 
1.41      ng       15638: $r is an Apache Request ref,
                   15639: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  15640: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       15641: 
                   15642: =cut
                   15643: 
1.144     matthew  15644: ######################################################
                   15645: ######################################################
1.31      albertel 15646: sub csv_print_select_table {
                   15647:     my ($r,$records,$d) = @_;
1.301     albertel 15648:     my $i=0;
                   15649:     my $samples = &get_samples($records,1);
1.144     matthew  15650:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  15651: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  15652:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  15653:               '<th>'.&mt('Column').'</th>'.
                   15654:               &end_data_table_header_row()."\n");
1.356     albertel 15655:     foreach my $array_ref (@$d) {
                   15656: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  15657: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 15658: 
1.875     bisitz   15659: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  15660: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 15661: 	$r->print('<option value="none"></option>');
1.356     albertel 15662: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   15663: 	    $r->print('<option value="'.$sample.'"'.
                   15664:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   15665:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 15666: 	}
1.594     raeburn  15667: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 15668: 	$i++;
                   15669:     }
1.594     raeburn  15670:     $r->print(&end_data_table());
1.31      albertel 15671:     $i--;
                   15672:     return $i;
                   15673: }
1.56      matthew  15674: 
1.144     matthew  15675: ######################################################
                   15676: ######################################################
                   15677: 
1.56      matthew  15678: =pod
1.31      albertel 15679: 
1.648     raeburn  15680: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       15681: 
                   15682: Prints a table of sample values from the upload and can make associate samples to internal names.
                   15683: 
                   15684: $r is an Apache Request ref,
                   15685: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   15686: $d is an array of 2 element arrays (internal name, displayed name)
                   15687: 
                   15688: =cut
                   15689: 
1.144     matthew  15690: ######################################################
                   15691: ######################################################
1.31      albertel 15692: sub csv_samples_select_table {
                   15693:     my ($r,$records,$d) = @_;
                   15694:     my $i=0;
1.144     matthew  15695:     #
1.662     bisitz   15696:     my $max_samples = 5;
                   15697:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15698:     $r->print(&start_data_table().
                   15699:               &start_data_table_header_row().'<th>'.
                   15700:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15701:               &end_data_table_header_row());
1.301     albertel 15702: 
                   15703:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15704: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15705: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15706: 	foreach my $option (@$d) {
                   15707: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15708: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15709:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15710:                       $display.'</option>');
1.31      albertel 15711: 	}
                   15712: 	$r->print('</select></td><td>');
1.662     bisitz   15713: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15714: 	    if (defined($samples->[$line]{$key})) { 
                   15715: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15716: 	    }
                   15717: 	}
1.594     raeburn  15718: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15719: 	$i++;
                   15720:     }
1.594     raeburn  15721:     $r->print(&end_data_table());
1.31      albertel 15722:     $i--;
                   15723:     return($i);
1.115     matthew  15724: }
                   15725: 
1.144     matthew  15726: ######################################################
                   15727: ######################################################
                   15728: 
1.115     matthew  15729: =pod
                   15730: 
1.648     raeburn  15731: =item * &clean_excel_name($name)
1.115     matthew  15732: 
                   15733: Returns a replacement for $name which does not contain any illegal characters.
                   15734: 
                   15735: =cut
                   15736: 
1.144     matthew  15737: ######################################################
                   15738: ######################################################
1.115     matthew  15739: sub clean_excel_name {
                   15740:     my ($name) = @_;
                   15741:     $name =~ s/[:\*\?\/\\]//g;
                   15742:     if (length($name) > 31) {
                   15743:         $name = substr($name,0,31);
                   15744:     }
                   15745:     return $name;
1.25      albertel 15746: }
1.84      albertel 15747: 
1.85      albertel 15748: =pod
                   15749: 
1.648     raeburn  15750: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15751: 
                   15752: Returns either 1 or undef
                   15753: 
                   15754: 1 if the part is to be hidden, undef if it is to be shown
                   15755: 
                   15756: Arguments are:
                   15757: 
                   15758: $id the id of the part to be checked
                   15759: $symb, optional the symb of the resource to check
                   15760: $udom, optional the domain of the user to check for
                   15761: $uname, optional the username of the user to check for
                   15762: 
                   15763: =cut
1.84      albertel 15764: 
                   15765: sub check_if_partid_hidden {
                   15766:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15767:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15768: 					 $symb,$udom,$uname);
1.141     albertel 15769:     my $truth=1;
                   15770:     #if the string starts with !, then the list is the list to show not hide
                   15771:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15772:     my @hiddenlist=split(/,/,$hiddenparts);
                   15773:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15774: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15775:     }
1.141     albertel 15776:     return !$truth;
1.84      albertel 15777: }
1.127     matthew  15778: 
1.138     matthew  15779: 
                   15780: ############################################################
                   15781: ############################################################
                   15782: 
                   15783: =pod
                   15784: 
1.157     matthew  15785: =back 
                   15786: 
1.138     matthew  15787: =head1 cgi-bin script and graphing routines
                   15788: 
1.157     matthew  15789: =over 4
                   15790: 
1.648     raeburn  15791: =item * &get_cgi_id()
1.138     matthew  15792: 
                   15793: Inputs: none
                   15794: 
                   15795: Returns an id which can be used to pass environment variables
                   15796: to various cgi-bin scripts.  These environment variables will
                   15797: be removed from the users environment after a given time by
                   15798: the routine &Apache::lonnet::transfer_profile_to_env.
                   15799: 
                   15800: =cut
                   15801: 
                   15802: ############################################################
                   15803: ############################################################
1.152     albertel 15804: my $uniq=0;
1.136     matthew  15805: sub get_cgi_id {
1.154     albertel 15806:     $uniq=($uniq+1)%100000;
1.280     albertel 15807:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15808: }
                   15809: 
1.127     matthew  15810: ############################################################
                   15811: ############################################################
                   15812: 
                   15813: =pod
                   15814: 
1.648     raeburn  15815: =item * &DrawBarGraph()
1.127     matthew  15816: 
1.138     matthew  15817: Facilitates the plotting of data in a (stacked) bar graph.
                   15818: Puts plot definition data into the users environment in order for 
                   15819: graph.png to plot it.  Returns an <img> tag for the plot.
                   15820: The bars on the plot are labeled '1','2',...,'n'.
                   15821: 
                   15822: Inputs:
                   15823: 
                   15824: =over 4
                   15825: 
                   15826: =item $Title: string, the title of the plot
                   15827: 
                   15828: =item $xlabel: string, text describing the X-axis of the plot
                   15829: 
                   15830: =item $ylabel: string, text describing the Y-axis of the plot
                   15831: 
                   15832: =item $Max: scalar, the maximum Y value to use in the plot
                   15833: If $Max is < any data point, the graph will not be rendered.
                   15834: 
1.140     matthew  15835: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15836: they are plotted.  If undefined, default values will be used.
                   15837: 
1.178     matthew  15838: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15839: 
1.138     matthew  15840: =item @Values: An array of array references.  Each array reference holds data
                   15841: to be plotted in a stacked bar chart.
                   15842: 
1.239     matthew  15843: =item If the final element of @Values is a hash reference the key/value
                   15844: pairs will be added to the graph definition.
                   15845: 
1.138     matthew  15846: =back
                   15847: 
                   15848: Returns:
                   15849: 
                   15850: An <img> tag which references graph.png and the appropriate identifying
                   15851: information for the plot.
                   15852: 
1.127     matthew  15853: =cut
                   15854: 
                   15855: ############################################################
                   15856: ############################################################
1.134     matthew  15857: sub DrawBarGraph {
1.178     matthew  15858:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15859:     #
                   15860:     if (! defined($colors)) {
                   15861:         $colors = ['#33ff00', 
                   15862:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15863:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15864:                   ]; 
                   15865:     }
1.228     matthew  15866:     my $extra_settings = {};
                   15867:     if (ref($Values[-1]) eq 'HASH') {
                   15868:         $extra_settings = pop(@Values);
                   15869:     }
1.127     matthew  15870:     #
1.136     matthew  15871:     my $identifier = &get_cgi_id();
                   15872:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15873:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15874:         return '';
                   15875:     }
1.225     matthew  15876:     #
                   15877:     my @Labels;
                   15878:     if (defined($labels)) {
                   15879:         @Labels = @$labels;
                   15880:     } else {
                   15881:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15882:             push(@Labels,$i+1);
1.225     matthew  15883:         }
                   15884:     }
                   15885:     #
1.129     matthew  15886:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15887:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15888:     my %ValuesHash;
                   15889:     my $NumSets=1;
                   15890:     foreach my $array (@Values) {
                   15891:         next if (! ref($array));
1.136     matthew  15892:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15893:             join(',',@$array);
1.129     matthew  15894:     }
1.127     matthew  15895:     #
1.136     matthew  15896:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15897:     if ($NumBars < 3) {
                   15898:         $width = 120+$NumBars*32;
1.220     matthew  15899:         $xskip = 1;
1.225     matthew  15900:         $bar_width = 30;
                   15901:     } elsif ($NumBars < 5) {
                   15902:         $width = 120+$NumBars*20;
                   15903:         $xskip = 1;
                   15904:         $bar_width = 20;
1.220     matthew  15905:     } elsif ($NumBars < 10) {
1.136     matthew  15906:         $width = 120+$NumBars*15;
                   15907:         $xskip = 1;
                   15908:         $bar_width = 15;
                   15909:     } elsif ($NumBars <= 25) {
                   15910:         $width = 120+$NumBars*11;
                   15911:         $xskip = 5;
                   15912:         $bar_width = 8;
                   15913:     } elsif ($NumBars <= 50) {
                   15914:         $width = 120+$NumBars*8;
                   15915:         $xskip = 5;
                   15916:         $bar_width = 4;
                   15917:     } else {
                   15918:         $width = 120+$NumBars*8;
                   15919:         $xskip = 5;
                   15920:         $bar_width = 4;
                   15921:     }
                   15922:     #
1.137     matthew  15923:     $Max = 1 if ($Max < 1);
                   15924:     if ( int($Max) < $Max ) {
                   15925:         $Max++;
                   15926:         $Max = int($Max);
                   15927:     }
1.127     matthew  15928:     $Title  = '' if (! defined($Title));
                   15929:     $xlabel = '' if (! defined($xlabel));
                   15930:     $ylabel = '' if (! defined($ylabel));
1.369     www      15931:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15932:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15933:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15934:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15935:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15936:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15937:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15938:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15939:     $ValuesHash{$id.'.height'}   = $height;
                   15940:     $ValuesHash{$id.'.width'}    = $width;
                   15941:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15942:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15943:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15944:     #
1.228     matthew  15945:     # Deal with other parameters
                   15946:     while (my ($key,$value) = each(%$extra_settings)) {
                   15947:         $ValuesHash{$id.'.'.$key} = $value;
                   15948:     }
                   15949:     #
1.646     raeburn  15950:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15951:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15952: }
                   15953: 
                   15954: ############################################################
                   15955: ############################################################
                   15956: 
                   15957: =pod
                   15958: 
1.648     raeburn  15959: =item * &DrawXYGraph()
1.137     matthew  15960: 
1.138     matthew  15961: Facilitates the plotting of data in an XY graph.
                   15962: Puts plot definition data into the users environment in order for 
                   15963: graph.png to plot it.  Returns an <img> tag for the plot.
                   15964: 
                   15965: Inputs:
                   15966: 
                   15967: =over 4
                   15968: 
                   15969: =item $Title: string, the title of the plot
                   15970: 
                   15971: =item $xlabel: string, text describing the X-axis of the plot
                   15972: 
                   15973: =item $ylabel: string, text describing the Y-axis of the plot
                   15974: 
                   15975: =item $Max: scalar, the maximum Y value to use in the plot
                   15976: If $Max is < any data point, the graph will not be rendered.
                   15977: 
                   15978: =item $colors: Array ref containing the hex color codes for the data to be 
                   15979: plotted in.  If undefined, default values will be used.
                   15980: 
                   15981: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15982: 
                   15983: =item $Ydata: Array ref containing Array refs.  
1.185     www      15984: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15985: 
                   15986: =item %Values: hash indicating or overriding any default values which are 
                   15987: passed to graph.png.  
                   15988: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15989: 
                   15990: =back
                   15991: 
                   15992: Returns:
                   15993: 
                   15994: An <img> tag which references graph.png and the appropriate identifying
                   15995: information for the plot.
                   15996: 
1.137     matthew  15997: =cut
                   15998: 
                   15999: ############################################################
                   16000: ############################################################
                   16001: sub DrawXYGraph {
                   16002:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   16003:     #
                   16004:     # Create the identifier for the graph
                   16005:     my $identifier = &get_cgi_id();
                   16006:     my $id = 'cgi.'.$identifier;
                   16007:     #
                   16008:     $Title  = '' if (! defined($Title));
                   16009:     $xlabel = '' if (! defined($xlabel));
                   16010:     $ylabel = '' if (! defined($ylabel));
                   16011:     my %ValuesHash = 
                   16012:         (
1.369     www      16013:          $id.'.title'  => &escape($Title),
                   16014:          $id.'.xlabel' => &escape($xlabel),
                   16015:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  16016:          $id.'.y_max_value'=> $Max,
                   16017:          $id.'.labels'     => join(',',@$Xlabels),
                   16018:          $id.'.PlotType'   => 'XY',
                   16019:          );
                   16020:     #
                   16021:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16022:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16023:     }
                   16024:     #
                   16025:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   16026:         return '';
                   16027:     }
                   16028:     my $NumSets=1;
1.138     matthew  16029:     foreach my $array (@{$Ydata}){
1.137     matthew  16030:         next if (! ref($array));
                   16031:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   16032:     }
1.138     matthew  16033:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  16034:     #
                   16035:     # Deal with other parameters
                   16036:     while (my ($key,$value) = each(%Values)) {
                   16037:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  16038:     }
                   16039:     #
1.646     raeburn  16040:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  16041:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   16042: }
                   16043: 
                   16044: ############################################################
                   16045: ############################################################
                   16046: 
                   16047: =pod
                   16048: 
1.648     raeburn  16049: =item * &DrawXYYGraph()
1.138     matthew  16050: 
                   16051: Facilitates the plotting of data in an XY graph with two Y axes.
                   16052: Puts plot definition data into the users environment in order for 
                   16053: graph.png to plot it.  Returns an <img> tag for the plot.
                   16054: 
                   16055: Inputs:
                   16056: 
                   16057: =over 4
                   16058: 
                   16059: =item $Title: string, the title of the plot
                   16060: 
                   16061: =item $xlabel: string, text describing the X-axis of the plot
                   16062: 
                   16063: =item $ylabel: string, text describing the Y-axis of the plot
                   16064: 
                   16065: =item $colors: Array ref containing the hex color codes for the data to be 
                   16066: plotted in.  If undefined, default values will be used.
                   16067: 
                   16068: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   16069: 
                   16070: =item $Ydata1: The first data set
                   16071: 
                   16072: =item $Min1: The minimum value of the left Y-axis
                   16073: 
                   16074: =item $Max1: The maximum value of the left Y-axis
                   16075: 
                   16076: =item $Ydata2: The second data set
                   16077: 
                   16078: =item $Min2: The minimum value of the right Y-axis
                   16079: 
                   16080: =item $Max2: The maximum value of the left Y-axis
                   16081: 
                   16082: =item %Values: hash indicating or overriding any default values which are 
                   16083: passed to graph.png.  
                   16084: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   16085: 
                   16086: =back
                   16087: 
                   16088: Returns:
                   16089: 
                   16090: An <img> tag which references graph.png and the appropriate identifying
                   16091: information for the plot.
1.136     matthew  16092: 
                   16093: =cut
                   16094: 
                   16095: ############################################################
                   16096: ############################################################
1.137     matthew  16097: sub DrawXYYGraph {
                   16098:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   16099:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  16100:     #
                   16101:     # Create the identifier for the graph
                   16102:     my $identifier = &get_cgi_id();
                   16103:     my $id = 'cgi.'.$identifier;
                   16104:     #
                   16105:     $Title  = '' if (! defined($Title));
                   16106:     $xlabel = '' if (! defined($xlabel));
                   16107:     $ylabel = '' if (! defined($ylabel));
                   16108:     my %ValuesHash = 
                   16109:         (
1.369     www      16110:          $id.'.title'  => &escape($Title),
                   16111:          $id.'.xlabel' => &escape($xlabel),
                   16112:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  16113:          $id.'.labels' => join(',',@$Xlabels),
                   16114:          $id.'.PlotType' => 'XY',
                   16115:          $id.'.NumSets' => 2,
1.137     matthew  16116:          $id.'.two_axes' => 1,
                   16117:          $id.'.y1_max_value' => $Max1,
                   16118:          $id.'.y1_min_value' => $Min1,
                   16119:          $id.'.y2_max_value' => $Max2,
                   16120:          $id.'.y2_min_value' => $Min2,
1.136     matthew  16121:          );
                   16122:     #
1.137     matthew  16123:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16124:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16125:     }
                   16126:     #
                   16127:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   16128:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  16129:         return '';
                   16130:     }
                   16131:     my $NumSets=1;
1.137     matthew  16132:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  16133:         next if (! ref($array));
                   16134:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  16135:     }
                   16136:     #
                   16137:     # Deal with other parameters
                   16138:     while (my ($key,$value) = each(%Values)) {
                   16139:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  16140:     }
                   16141:     #
1.646     raeburn  16142:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 16143:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  16144: }
                   16145: 
                   16146: ############################################################
                   16147: ############################################################
                   16148: 
                   16149: =pod
                   16150: 
1.157     matthew  16151: =back 
                   16152: 
1.139     matthew  16153: =head1 Statistics helper routines?  
                   16154: 
                   16155: Bad place for them but what the hell.
                   16156: 
1.157     matthew  16157: =over 4
                   16158: 
1.648     raeburn  16159: =item * &chartlink()
1.139     matthew  16160: 
                   16161: Returns a link to the chart for a specific student.  
                   16162: 
                   16163: Inputs:
                   16164: 
                   16165: =over 4
                   16166: 
                   16167: =item $linktext: The text of the link
                   16168: 
                   16169: =item $sname: The students username
                   16170: 
                   16171: =item $sdomain: The students domain
                   16172: 
                   16173: =back
                   16174: 
1.157     matthew  16175: =back
                   16176: 
1.139     matthew  16177: =cut
                   16178: 
                   16179: ############################################################
                   16180: ############################################################
                   16181: sub chartlink {
                   16182:     my ($linktext, $sname, $sdomain) = @_;
                   16183:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      16184:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 16185:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  16186:        '">'.$linktext.'</a>';
1.153     matthew  16187: }
                   16188: 
                   16189: #######################################################
                   16190: #######################################################
                   16191: 
                   16192: =pod
                   16193: 
                   16194: =head1 Course Environment Routines
1.157     matthew  16195: 
                   16196: =over 4
1.153     matthew  16197: 
1.648     raeburn  16198: =item * &restore_course_settings()
1.153     matthew  16199: 
1.648     raeburn  16200: =item * &store_course_settings()
1.153     matthew  16201: 
                   16202: Restores/Store indicated form parameters from the course environment.
                   16203: Will not overwrite existing values of the form parameters.
                   16204: 
                   16205: Inputs: 
                   16206: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   16207: 
                   16208: a hash ref describing the data to be stored.  For example:
                   16209:    
                   16210: %Save_Parameters = ('Status' => 'scalar',
                   16211:     'chartoutputmode' => 'scalar',
                   16212:     'chartoutputdata' => 'scalar',
                   16213:     'Section' => 'array',
1.373     raeburn  16214:     'Group' => 'array',
1.153     matthew  16215:     'StudentData' => 'array',
                   16216:     'Maps' => 'array');
                   16217: 
                   16218: Returns: both routines return nothing
                   16219: 
1.631     raeburn  16220: =back
                   16221: 
1.153     matthew  16222: =cut
                   16223: 
                   16224: #######################################################
                   16225: #######################################################
                   16226: sub store_course_settings {
1.496     albertel 16227:     return &store_settings($env{'request.course.id'},@_);
                   16228: }
                   16229: 
                   16230: sub store_settings {
1.153     matthew  16231:     # save to the environment
                   16232:     # appenv the same items, just to be safe
1.300     albertel 16233:     my $udom  = $env{'user.domain'};
                   16234:     my $uname = $env{'user.name'};
1.496     albertel 16235:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16236:     my %SaveHash;
                   16237:     my %AppHash;
                   16238:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 16239:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 16240:         my $envname = 'environment.'.$basename;
1.258     albertel 16241:         if (exists($env{'form.'.$setting})) {
1.153     matthew  16242:             # Save this value away
                   16243:             if ($type eq 'scalar' &&
1.258     albertel 16244:                 (! exists($env{$envname}) || 
                   16245:                  $env{$envname} ne $env{'form.'.$setting})) {
                   16246:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   16247:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  16248:             } elsif ($type eq 'array') {
                   16249:                 my $stored_form;
1.258     albertel 16250:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  16251:                     $stored_form = join(',',
                   16252:                                         map {
1.369     www      16253:                                             &escape($_);
1.258     albertel 16254:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  16255:                 } else {
                   16256:                     $stored_form = 
1.369     www      16257:                         &escape($env{'form.'.$setting});
1.153     matthew  16258:                 }
                   16259:                 # Determine if the array contents are the same.
1.258     albertel 16260:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  16261:                     $SaveHash{$basename} = $stored_form;
                   16262:                     $AppHash{$envname}   = $stored_form;
                   16263:                 }
                   16264:             }
                   16265:         }
                   16266:     }
                   16267:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 16268:                                           $udom,$uname);
1.153     matthew  16269:     if ($put_result !~ /^(ok|delayed)/) {
                   16270:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   16271:                                  'got error:'.$put_result);
                   16272:     }
                   16273:     # Make sure these settings stick around in this session, too
1.646     raeburn  16274:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  16275:     return;
                   16276: }
                   16277: 
                   16278: sub restore_course_settings {
1.499     albertel 16279:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 16280: }
                   16281: 
                   16282: sub restore_settings {
                   16283:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16284:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 16285:         next if (exists($env{'form.'.$setting}));
1.496     albertel 16286:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  16287:             '.'.$setting;
1.258     albertel 16288:         if (exists($env{$envname})) {
1.153     matthew  16289:             if ($type eq 'scalar') {
1.258     albertel 16290:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  16291:             } elsif ($type eq 'array') {
1.258     albertel 16292:                 $env{'form.'.$setting} = [ 
1.153     matthew  16293:                                            map { 
1.369     www      16294:                                                &unescape($_); 
1.258     albertel 16295:                                            } split(',',$env{$envname})
1.153     matthew  16296:                                            ];
                   16297:             }
                   16298:         }
                   16299:     }
1.127     matthew  16300: }
                   16301: 
1.618     raeburn  16302: #######################################################
                   16303: #######################################################
                   16304: 
                   16305: =pod
                   16306: 
                   16307: =head1 Domain E-mail Routines  
                   16308: 
                   16309: =over 4
                   16310: 
1.648     raeburn  16311: =item * &build_recipient_list()
1.618     raeburn  16312: 
1.1144    raeburn  16313: Build recipient lists for following types of e-mail:
1.766     raeburn  16314: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  16315: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   16316: module change checking, student/employee ID conflict checks, as
                   16317: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   16318: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  16319: 
                   16320: Inputs:
1.619     raeburn  16321: defmail (scalar - email address of default recipient), 
1.1144    raeburn  16322: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   16323: requestsmail, updatesmail, or idconflictsmail).
                   16324: 
1.619     raeburn  16325: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  16326: 
1.619     raeburn  16327: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  16328: i.e., predates configuration by DC via domainprefs.pm
                   16329: 
                   16330: $requname username of requester (if mailing type is helpdeskmail)
                   16331: 
                   16332: $requdom domain of requester (if mailing type is helpdeskmail)
                   16333: 
                   16334: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   16335: 
1.618     raeburn  16336: 
1.655     raeburn  16337: Returns: comma separated list of addresses to which to send e-mail.
                   16338: 
                   16339: =back
1.618     raeburn  16340: 
                   16341: =cut
                   16342: 
                   16343: ############################################################
                   16344: ############################################################
                   16345: sub build_recipient_list {
1.1297    raeburn  16346:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  16347:     my @recipients;
1.1270    raeburn  16348:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  16349:     my %domconfig =
1.1270    raeburn  16350:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  16351:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  16352:         if (exists($domconfig{'contacts'}{$mailing})) {
                   16353:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   16354:                 my @contacts = ('adminemail','supportemail');
                   16355:                 foreach my $item (@contacts) {
                   16356:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   16357:                         my $addr = $domconfig{'contacts'}{$item}; 
                   16358:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16359:                             push(@recipients,$addr);
                   16360:                         }
1.619     raeburn  16361:                     }
1.1270    raeburn  16362:                 }
                   16363:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   16364:                 if ($mailing eq 'helpdeskmail') {
                   16365:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   16366:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   16367:                         my @ok_bccs;
                   16368:                         foreach my $bcc (@bccs) {
                   16369:                             $bcc =~ s/^\s+//g;
                   16370:                             $bcc =~ s/\s+$//g;
                   16371:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16372:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16373:                                     push(@ok_bccs,$bcc);
                   16374:                                 }
                   16375:                             }
                   16376:                         }
                   16377:                         if (@ok_bccs > 0) {
                   16378:                             $allbcc = join(', ',@ok_bccs);
                   16379:                         }
                   16380:                     }
                   16381:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  16382:                 }
                   16383:             }
1.766     raeburn  16384:         } elsif ($origmail ne '') {
1.1270    raeburn  16385:             $lastresort = $origmail;
1.618     raeburn  16386:         }
1.1297    raeburn  16387:         if ($mailing eq 'helpdeskmail') {
                   16388:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   16389:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   16390:                 my ($inststatus,$inststatus_checked);
                   16391:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   16392:                     ($env{'user.domain'} ne 'public')) {
                   16393:                     $inststatus_checked = 1;
                   16394:                     $inststatus = $env{'environment.inststatus'};
                   16395:                 }
                   16396:                 unless ($inststatus_checked) {
                   16397:                     if (($requname ne '') && ($requdom ne '')) {
                   16398:                         if (($requname =~ /^$match_username$/) &&
                   16399:                             ($requdom =~ /^$match_domain$/) &&
                   16400:                             (&Apache::lonnet::domain($requdom))) {
                   16401:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   16402:                                                                       $requdom);
                   16403:                             unless ($requhome eq 'no_host') {
                   16404:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   16405:                                 $inststatus = $userenv{'inststatus'};
                   16406:                                 $inststatus_checked = 1;
                   16407:                             }
                   16408:                         }
                   16409:                     }
                   16410:                 }
                   16411:                 unless ($inststatus_checked) {
                   16412:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   16413:                         my %srch = (srchby     => 'email',
                   16414:                                     srchdomain => $defdom,
                   16415:                                     srchterm   => $reqemail,
                   16416:                                     srchtype   => 'exact');
                   16417:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   16418:                         foreach my $uname (keys(%srch_results)) {
                   16419:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16420:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16421:                                 $inststatus_checked = 1;
                   16422:                                 last;
                   16423:                             }
                   16424:                         }
                   16425:                         unless ($inststatus_checked) {
                   16426:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   16427:                             if ($dirsrchres eq 'ok') {
                   16428:                                 foreach my $uname (keys(%srch_results)) {
                   16429:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16430:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16431:                                         $inststatus_checked = 1;
                   16432:                                         last;
                   16433:                                     }
                   16434:                                 }
                   16435:                             }
                   16436:                         }
                   16437:                     }
                   16438:                 }
                   16439:                 if ($inststatus ne '') {
                   16440:                     foreach my $status (split(/\:/,$inststatus)) {
                   16441:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   16442:                             my @contacts = ('adminemail','supportemail');
                   16443:                             foreach my $item (@contacts) {
                   16444:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   16445:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   16446:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16447:                                         push(@recipients,$addr);
                   16448:                                     }
                   16449:                                 }
                   16450:                             }
                   16451:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   16452:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   16453:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   16454:                                 my @ok_bccs;
                   16455:                                 foreach my $bcc (@bccs) {
                   16456:                                     $bcc =~ s/^\s+//g;
                   16457:                                     $bcc =~ s/\s+$//g;
                   16458:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16459:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16460:                                             push(@ok_bccs,$bcc);
                   16461:                                         }
                   16462:                                     }
                   16463:                                 }
                   16464:                                 if (@ok_bccs > 0) {
                   16465:                                     $allbcc = join(', ',@ok_bccs);
                   16466:                                 }
                   16467:                             }
                   16468:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   16469:                             last;
                   16470:                         }
                   16471:                     }
                   16472:                 }
                   16473:             }
                   16474:         }
1.619     raeburn  16475:     } elsif ($origmail ne '') {
1.1270    raeburn  16476:         $lastresort = $origmail;
                   16477:     }
1.1297    raeburn  16478:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  16479:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   16480:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   16481:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   16482:             my %what = (
                   16483:                           perlvar => 1,
                   16484:                        );
                   16485:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   16486:             if ($primary) {
                   16487:                 my $gotaddr;
                   16488:                 my ($result,$returnhash) =
                   16489:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   16490:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   16491:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   16492:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   16493:                         $gotaddr = 1;
                   16494:                     }
                   16495:                 }
                   16496:                 unless ($gotaddr) {
                   16497:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   16498:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   16499:                     unless ($uintdom eq $intdom) {
                   16500:                         my %domconfig =
                   16501:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   16502:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   16503:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   16504:                                 my @contacts = ('adminemail','supportemail');
                   16505:                                 foreach my $item (@contacts) {
                   16506:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   16507:                                         my $addr = $domconfig{'contacts'}{$item};
                   16508:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16509:                                             push(@recipients,$addr);
                   16510:                                         }
                   16511:                                     }
                   16512:                                 }
                   16513:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   16514:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   16515:                                 }
                   16516:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   16517:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   16518:                                     my @ok_bccs;
                   16519:                                     foreach my $bcc (@bccs) {
                   16520:                                         $bcc =~ s/^\s+//g;
                   16521:                                         $bcc =~ s/\s+$//g;
                   16522:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16523:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16524:                                                 push(@ok_bccs,$bcc);
                   16525:                                             }
                   16526:                                         }
                   16527:                                     }
                   16528:                                     if (@ok_bccs > 0) {
                   16529:                                         $allbcc = join(', ',@ok_bccs);
                   16530:                                     }
                   16531:                                 }
                   16532:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   16533:                             }
                   16534:                         }
                   16535:                     }
                   16536:                 }
                   16537:             }
                   16538:         }
1.618     raeburn  16539:     }
1.688     raeburn  16540:     if (defined($defmail)) {
                   16541:         if ($defmail ne '') {
                   16542:             push(@recipients,$defmail);
                   16543:         }
1.618     raeburn  16544:     }
                   16545:     if ($otheremails) {
1.619     raeburn  16546:         my @others;
                   16547:         if ($otheremails =~ /,/) {
                   16548:             @others = split(/,/,$otheremails);
1.618     raeburn  16549:         } else {
1.619     raeburn  16550:             push(@others,$otheremails);
                   16551:         }
                   16552:         foreach my $addr (@others) {
                   16553:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16554:                 push(@recipients,$addr);
                   16555:             }
1.618     raeburn  16556:         }
                   16557:     }
1.1298    raeburn  16558:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  16559:         if ((!@recipients) && ($lastresort ne '')) {
                   16560:             push(@recipients,$lastresort);
                   16561:         }
                   16562:     } elsif ($lastresort ne '') {
                   16563:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   16564:             push(@recipients,$lastresort);
                   16565:         }
                   16566:     }
1.1271    raeburn  16567:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  16568:     if (wantarray) {
                   16569:         return ($recipientlist,$allbcc,$addtext);
                   16570:     } else {
                   16571:         return $recipientlist;
                   16572:     }
1.618     raeburn  16573: }
                   16574: 
1.127     matthew  16575: ############################################################
                   16576: ############################################################
1.154     albertel 16577: 
1.655     raeburn  16578: =pod
                   16579: 
1.1224    musolffc 16580: =over 4
                   16581: 
1.1223    musolffc 16582: =item * &mime_email()
                   16583: 
                   16584: Sends an email with a possible attachment
                   16585: 
                   16586: Inputs:
                   16587: 
                   16588: =over 4
                   16589: 
                   16590: from -              Sender's email address
                   16591: 
1.1343    raeburn  16592: replyto -           Reply-To email address
                   16593: 
1.1223    musolffc 16594: to -                Email address of recipient
                   16595: 
                   16596: subject -           Subject of email
                   16597: 
                   16598: body -              Body of email
                   16599: 
                   16600: cc_string -         Carbon copy email address
                   16601: 
                   16602: bcc -               Blind carbon copy email address
                   16603: 
                   16604: attachment_path -   Path of file to be attached
                   16605: 
                   16606: file_name -         Name of file to be attached
                   16607: 
                   16608: attachment_text -   The body of an attachment of type "TEXT"
                   16609: 
                   16610: =back
                   16611: 
                   16612: =back
                   16613: 
                   16614: =cut
                   16615: 
                   16616: ############################################################
                   16617: ############################################################
                   16618: 
                   16619: sub mime_email {
1.1343    raeburn  16620:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   16621:         $file_name,$attachment_text) = @_;
                   16622:  
1.1223    musolffc 16623:     my $msg = MIME::Lite->new(
                   16624:              From    => $from,
                   16625:              To      => $to,
                   16626:              Subject => $subject,
                   16627:              Type    =>'TEXT',
                   16628:              Data    => $body,
                   16629:              );
1.1343    raeburn  16630:     if ($replyto ne '') {
                   16631:         $msg->add("Reply-To" => $replyto);
                   16632:     }
1.1223    musolffc 16633:     if ($cc_string ne '') {
                   16634:         $msg->add("Cc" => $cc_string);
                   16635:     }
                   16636:     if ($bcc ne '') {
                   16637:         $msg->add("Bcc" => $bcc);
                   16638:     }
                   16639:     $msg->attr("content-type"         => "text/plain");
                   16640:     $msg->attr("content-type.charset" => "UTF-8");
                   16641:     # Attach file if given
                   16642:     if ($attachment_path) {
                   16643:         unless ($file_name) {
                   16644:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   16645:         }
                   16646:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   16647:         $msg->attach(Type     => $type,
                   16648:                      Path     => $attachment_path,
                   16649:                      Filename => $file_name
                   16650:                      );
                   16651:     # Otherwise attach text if given
                   16652:     } elsif ($attachment_text) {
                   16653:         $msg->attach(Type => 'TEXT',
                   16654:                      Data => $attachment_text);
                   16655:     }
                   16656:     # Send it
                   16657:     $msg->send('sendmail');
                   16658: }
                   16659: 
                   16660: ############################################################
                   16661: ############################################################
                   16662: 
                   16663: =pod
                   16664: 
1.655     raeburn  16665: =head1 Course Catalog Routines
                   16666: 
                   16667: =over 4
                   16668: 
                   16669: =item * &gather_categories()
                   16670: 
                   16671: Converts category definitions - keys of categories hash stored in  
                   16672: coursecategories in configuration.db on the primary library server in a 
                   16673: domain - to an array.  Also generates javascript and idx hash used to 
                   16674: generate Domain Coordinator interface for editing Course Categories.
                   16675: 
                   16676: Inputs:
1.663     raeburn  16677: 
1.655     raeburn  16678: categories (reference to hash of category definitions).
1.663     raeburn  16679: 
1.655     raeburn  16680: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16681:       categories and subcategories).
1.663     raeburn  16682: 
1.655     raeburn  16683: idx (reference to hash of counters used in Domain Coordinator interface for 
                   16684:       editing Course Categories).
1.663     raeburn  16685: 
1.655     raeburn  16686: jsarray (reference to array of categories used to create Javascript arrays for
                   16687:          Domain Coordinator interface for editing Course Categories).
                   16688: 
                   16689: Returns: nothing
                   16690: 
                   16691: Side effects: populates cats, idx and jsarray. 
                   16692: 
                   16693: =cut
                   16694: 
                   16695: sub gather_categories {
                   16696:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16697:     my %counters;
                   16698:     my $num = 0;
                   16699:     foreach my $item (keys(%{$categories})) {
                   16700:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16701:         if ($container eq '' && $depth == 0) {
                   16702:             $cats->[$depth][$categories->{$item}] = $cat;
                   16703:         } else {
                   16704:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16705:         }
                   16706:         my ($escitem,$tail) = split(/:/,$item,2);
                   16707:         if ($counters{$tail} eq '') {
                   16708:             $counters{$tail} = $num;
                   16709:             $num ++;
                   16710:         }
                   16711:         if (ref($idx) eq 'HASH') {
                   16712:             $idx->{$item} = $counters{$tail};
                   16713:         }
                   16714:         if (ref($jsarray) eq 'ARRAY') {
                   16715:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16716:         }
                   16717:     }
                   16718:     return;
                   16719: }
                   16720: 
                   16721: =pod
                   16722: 
                   16723: =item * &extract_categories()
                   16724: 
                   16725: Used to generate breadcrumb trails for course categories.
                   16726: 
                   16727: Inputs:
1.663     raeburn  16728: 
1.655     raeburn  16729: categories (reference to hash of category definitions).
1.663     raeburn  16730: 
1.655     raeburn  16731: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16732:       categories and subcategories).
1.663     raeburn  16733: 
1.655     raeburn  16734: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16735: 
1.655     raeburn  16736: allitems (reference to hash - key is category key 
                   16737:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16738: 
1.655     raeburn  16739: idx (reference to hash of counters used in Domain Coordinator interface for
                   16740:       editing Course Categories).
1.663     raeburn  16741: 
1.655     raeburn  16742: jsarray (reference to array of categories used to create Javascript arrays for
                   16743:          Domain Coordinator interface for editing Course Categories).
                   16744: 
1.665     raeburn  16745: subcats (reference to hash of arrays containing all subcategories within each 
                   16746:          category, -recursive)
                   16747: 
1.1321    raeburn  16748: maxd (reference to hash used to hold max depth for all top-level categories).
                   16749: 
1.655     raeburn  16750: Returns: nothing
                   16751: 
                   16752: Side effects: populates trails and allitems hash references.
                   16753: 
                   16754: =cut
                   16755: 
                   16756: sub extract_categories {
1.1321    raeburn  16757:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16758:     if (ref($categories) eq 'HASH') {
                   16759:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16760:         if (ref($cats->[0]) eq 'ARRAY') {
                   16761:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16762:                 my $name = $cats->[0][$i];
                   16763:                 my $item = &escape($name).'::0';
                   16764:                 my $trailstr;
                   16765:                 if ($name eq 'instcode') {
                   16766:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16767:                 } elsif ($name eq 'communities') {
                   16768:                     $trailstr = &mt('Communities');
1.1239    raeburn  16769:                 } elsif ($name eq 'placement') {
                   16770:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16771:                 } else {
                   16772:                     $trailstr = $name;
                   16773:                 }
                   16774:                 if ($allitems->{$item} eq '') {
                   16775:                     push(@{$trails},$trailstr);
                   16776:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16777:                 }
                   16778:                 my @parents = ($name);
                   16779:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16780:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16781:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16782:                         if (ref($subcats) eq 'HASH') {
                   16783:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16784:                         }
1.1321    raeburn  16785:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16786:                     }
                   16787:                 } else {
                   16788:                     if (ref($subcats) eq 'HASH') {
                   16789:                         $subcats->{$item} = [];
1.655     raeburn  16790:                     }
1.1321    raeburn  16791:                     if (ref($maxd) eq 'HASH') {
                   16792:                         $maxd->{$name} = 1;
                   16793:                     }
1.655     raeburn  16794:                 }
                   16795:             }
                   16796:         }
                   16797:     }
                   16798:     return;
                   16799: }
                   16800: 
                   16801: =pod
                   16802: 
1.1162    raeburn  16803: =item * &recurse_categories()
1.655     raeburn  16804: 
                   16805: Recursively used to generate breadcrumb trails for course categories.
                   16806: 
                   16807: Inputs:
1.663     raeburn  16808: 
1.655     raeburn  16809: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16810:       categories and subcategories).
1.663     raeburn  16811: 
1.655     raeburn  16812: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16813: 
                   16814: category (current course category, for which breadcrumb trail is being generated).
                   16815: 
                   16816: trails (reference to array of breadcrumb trails for each category).
                   16817: 
1.655     raeburn  16818: allitems (reference to hash - key is category key
                   16819:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16820: 
1.655     raeburn  16821: parents (array containing containers directories for current category, 
                   16822:          back to top level). 
                   16823: 
                   16824: Returns: nothing
                   16825: 
                   16826: Side effects: populates trails and allitems hash references
                   16827: 
                   16828: =cut
                   16829: 
                   16830: sub recurse_categories {
1.1321    raeburn  16831:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16832:     my $shallower = $depth - 1;
                   16833:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16834:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16835:             my $name = $cats->[$depth]{$category}[$k];
                   16836:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16837:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16838:             if ($allitems->{$item} eq '') {
                   16839:                 push(@{$trails},$trailstr);
                   16840:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16841:             }
                   16842:             my $deeper = $depth+1;
                   16843:             push(@{$parents},$category);
1.665     raeburn  16844:             if (ref($subcats) eq 'HASH') {
                   16845:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16846:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16847:                     my $higher;
                   16848:                     if ($j > 0) {
                   16849:                         $higher = &escape($parents->[$j]).':'.
                   16850:                                   &escape($parents->[$j-1]).':'.$j;
                   16851:                     } else {
                   16852:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16853:                     }
                   16854:                     push(@{$subcats->{$higher}},$subcat);
                   16855:                 }
                   16856:             }
                   16857:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16858:                                 $subcats,$maxd);
1.655     raeburn  16859:             pop(@{$parents});
                   16860:         }
                   16861:     } else {
                   16862:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16863:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16864:         if ($allitems->{$item} eq '') {
                   16865:             push(@{$trails},$trailstr);
                   16866:             $allitems->{$item} = scalar(@{$trails})-1;
                   16867:         }
1.1321    raeburn  16868:         if (ref($maxd) eq 'HASH') {
                   16869:             if ($depth > $maxd->{$parents->[0]}) {
                   16870:                 $maxd->{$parents->[0]} = $depth;
                   16871:             }
                   16872:         }
1.655     raeburn  16873:     }
                   16874:     return;
                   16875: }
                   16876: 
1.663     raeburn  16877: =pod
                   16878: 
1.1162    raeburn  16879: =item * &assign_categories_table()
1.663     raeburn  16880: 
                   16881: Create a datatable for display of hierarchical categories in a domain,
                   16882: with checkboxes to allow a course to be categorized. 
                   16883: 
                   16884: Inputs:
                   16885: 
                   16886: cathash - reference to hash of categories defined for the domain (from
                   16887:           configuration.db)
                   16888: 
                   16889: currcat - scalar with an & separated list of categories assigned to a course. 
                   16890: 
1.919     raeburn  16891: type    - scalar contains course type (Course or Community).
                   16892: 
1.1260    raeburn  16893: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16894:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16895: 
1.663     raeburn  16896: Returns: $output (markup to be displayed) 
                   16897: 
                   16898: =cut
                   16899: 
                   16900: sub assign_categories_table {
1.1259    raeburn  16901:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16902:     my $output;
                   16903:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16904:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16905:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16906:         $maxdepth = scalar(@cats);
                   16907:         if (@cats > 0) {
                   16908:             my $itemcount = 0;
                   16909:             if (ref($cats[0]) eq 'ARRAY') {
                   16910:                 my @currcategories;
                   16911:                 if ($currcat ne '') {
                   16912:                     @currcategories = split('&',$currcat);
                   16913:                 }
1.919     raeburn  16914:                 my $table;
1.663     raeburn  16915:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16916:                     my $parent = $cats[0][$i];
1.919     raeburn  16917:                     next if ($parent eq 'instcode');
                   16918:                     if ($type eq 'Community') {
                   16919:                         next unless ($parent eq 'communities');
1.1239    raeburn  16920:                     } elsif ($type eq 'Placement') {
                   16921:                         next unless ($parent eq 'placement');
1.919     raeburn  16922:                     } else {
1.1239    raeburn  16923:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16924:                     }
1.663     raeburn  16925:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16926:                     my $item = &escape($parent).'::0';
                   16927:                     my $checked = '';
                   16928:                     if (@currcategories > 0) {
                   16929:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16930:                             $checked = ' checked="checked"';
1.663     raeburn  16931:                         }
                   16932:                     }
1.919     raeburn  16933:                     my $parent_title = $parent;
                   16934:                     if ($parent eq 'communities') {
                   16935:                         $parent_title = &mt('Communities');
1.1239    raeburn  16936:                     } elsif ($parent eq 'placement') {
                   16937:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16938:                     }
                   16939:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16940:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16941:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16942:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16943:                     my $depth = 1;
                   16944:                     push(@path,$parent);
1.1259    raeburn  16945:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16946:                     pop(@path);
1.919     raeburn  16947:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16948:                     $itemcount ++;
                   16949:                 }
1.919     raeburn  16950:                 if ($itemcount) {
                   16951:                     $output = &Apache::loncommon::start_data_table().
                   16952:                               $table.
                   16953:                               &Apache::loncommon::end_data_table();
                   16954:                 }
1.663     raeburn  16955:             }
                   16956:         }
                   16957:     }
                   16958:     return $output;
                   16959: }
                   16960: 
                   16961: =pod
                   16962: 
1.1162    raeburn  16963: =item * &assign_category_rows()
1.663     raeburn  16964: 
                   16965: Create a datatable row for display of nested categories in a domain,
                   16966: with checkboxes to allow a course to be categorized,called recursively.
                   16967: 
                   16968: Inputs:
                   16969: 
                   16970: itemcount - track row number for alternating colors
                   16971: 
                   16972: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16973:       categories and subcategories.
                   16974: 
                   16975: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16976: 
                   16977: parent - parent of current category item
                   16978: 
                   16979: path - Array containing all categories back up through the hierarchy from the
                   16980:        current category to the top level.
                   16981: 
                   16982: currcategories - reference to array of current categories assigned to the course
                   16983: 
1.1260    raeburn  16984: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16985:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16986: 
1.663     raeburn  16987: Returns: $output (markup to be displayed).
                   16988: 
                   16989: =cut
                   16990: 
                   16991: sub assign_category_rows {
1.1259    raeburn  16992:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16993:     my ($text,$name,$item,$chgstr);
                   16994:     if (ref($cats) eq 'ARRAY') {
                   16995:         my $maxdepth = scalar(@{$cats});
                   16996:         if (ref($cats->[$depth]) eq 'HASH') {
                   16997:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16998:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16999:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  17000:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  17001:                 for (my $j=0; $j<$numchildren; $j++) {
                   17002:                     $name = $cats->[$depth]{$parent}[$j];
                   17003:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   17004:                     my $deeper = $depth+1;
                   17005:                     my $checked = '';
                   17006:                     if (ref($currcategories) eq 'ARRAY') {
                   17007:                         if (@{$currcategories} > 0) {
                   17008:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   17009:                                 $checked = ' checked="checked"';
1.663     raeburn  17010:                             }
                   17011:                         }
                   17012:                     }
1.664     raeburn  17013:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   17014:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  17015:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  17016:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   17017:                              '</td><td>';
1.663     raeburn  17018:                     if (ref($path) eq 'ARRAY') {
                   17019:                         push(@{$path},$name);
1.1259    raeburn  17020:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  17021:                         pop(@{$path});
                   17022:                     }
                   17023:                     $text .= '</td></tr>';
                   17024:                 }
                   17025:                 $text .= '</table></td>';
                   17026:             }
                   17027:         }
                   17028:     }
                   17029:     return $text;
                   17030: }
                   17031: 
1.1181    raeburn  17032: =pod
                   17033: 
                   17034: =back
                   17035: 
                   17036: =cut
                   17037: 
1.655     raeburn  17038: ############################################################
                   17039: ############################################################
                   17040: 
                   17041: 
1.443     albertel 17042: sub commit_customrole {
1.1408    raeburn  17043:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
1.1399    raeburn  17044:     my $result = &Apache::lonnet::assigncustomrole(
1.1408    raeburn  17045:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
                   17046:                      $context,$othdomby,$requester);
1.630     raeburn  17047:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 17048:                          ($start?', '.&mt('starting').' '.localtime($start):'').
1.1399    raeburn  17049:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
                   17050:     if (wantarray) {
                   17051:         return ($output,$result);
                   17052:     } else {
                   17053:         return $output;
                   17054:     }
1.443     albertel 17055: }
                   17056: 
                   17057: sub commit_standardrole {
1.1408    raeburn  17058:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
                   17059:         $othdomby,$requester) = @_;
1.1399    raeburn  17060:     my ($output,$logmsg,$linefeed,$result);
1.541     raeburn  17061:     if ($context eq 'auto') {
                   17062:         $linefeed = "\n";
                   17063:     } else {
                   17064:         $linefeed = "<br />\n";
                   17065:     }  
1.443     albertel 17066:     if ($three eq 'st') {
1.1399    raeburn  17067:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1408    raeburn  17068:                                       $one,$two,$sec,$context,$credits,$othdomby,
                   17069:                                       $requester);
1.541     raeburn  17070:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  17071:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   17072:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 17073:         } else {
1.541     raeburn  17074:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 17075:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17076:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   17077:             if ($context eq 'auto') {
                   17078:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   17079:             } else {
                   17080:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   17081:                &mt('Add to classlist').': <b>ok</b>';
                   17082:             }
                   17083:             $output .= $linefeed;
1.443     albertel 17084:         }
                   17085:     } else {
                   17086:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   17087:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17088:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.1408    raeburn  17089:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
                   17090:                                               '','',$context,$othdomby,$requester);
1.541     raeburn  17091:         if ($context eq 'auto') {
                   17092:             $output .= $result.$linefeed;
                   17093:         } else {
                   17094:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   17095:         }
1.443     albertel 17096:     }
1.1399    raeburn  17097:     if (wantarray) {
                   17098:         return ($output,$result);
                   17099:     } else {
                   17100:         return $output;
                   17101:     }
1.443     albertel 17102: }
                   17103: 
                   17104: sub commit_studentrole {
1.1116    raeburn  17105:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
1.1408    raeburn  17106:         $credits,$othdomby,$requester) = @_;
1.626     raeburn  17107:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  17108:     if ($context eq 'auto') {
                   17109:         $linefeed = "\n";
                   17110:     } else {
                   17111:         $linefeed = '<br />'."\n";
                   17112:     }
1.443     albertel 17113:     if (defined($one) && defined($two)) {
                   17114:         my $cid=$one.'_'.$two;
                   17115:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   17116:         my $secchange = 0;
                   17117:         my $expire_role_result;
                   17118:         my $modify_section_result;
1.628     raeburn  17119:         if ($oldsec ne '-1') { 
                   17120:             if ($oldsec ne $sec) {
1.443     albertel 17121:                 $secchange = 1;
1.628     raeburn  17122:                 my $now = time;
1.443     albertel 17123:                 my $uurl='/'.$cid;
                   17124:                 $uurl=~s/\_/\//g;
                   17125:                 if ($oldsec) {
                   17126:                     $uurl.='/'.$oldsec;
                   17127:                 }
1.626     raeburn  17128:                 $oldsecurl = $uurl;
1.628     raeburn  17129:                 $expire_role_result = 
1.1408    raeburn  17130:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
                   17131:                                                 '','','',$context,$othdomby,$requester);
                   17132:                 if ($env{'request.course.sec'} ne '') {
1.628     raeburn  17133:                     if ($expire_role_result eq 'refused') {
                   17134:                         my @roles = ('st');
                   17135:                         my @statuses = ('previous');
                   17136:                         my @roledoms = ($one);
                   17137:                         my $withsec = 1;
                   17138:                         my %roleshash = 
                   17139:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   17140:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   17141:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   17142:                             my ($oldstart,$oldend) = 
                   17143:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   17144:                             if ($oldend > 0 && $oldend <= $now) {
                   17145:                                 $expire_role_result = 'ok';
                   17146:                             }
                   17147:                         }
                   17148:                     }
                   17149:                 }
1.443     albertel 17150:                 $result = $expire_role_result;
                   17151:             }
                   17152:         }
                   17153:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  17154:             $modify_section_result = 
                   17155:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   17156:                                                            undef,undef,undef,$sec,
                   17157:                                                            $end,$start,'','',$cid,
1.1408    raeburn  17158:                                                            '',$context,$credits,'',
                   17159:                                                            $othdomby,$requester);
1.443     albertel 17160:             if ($modify_section_result =~ /^ok/) {
                   17161:                 if ($secchange == 1) {
1.628     raeburn  17162:                     if ($sec eq '') {
                   17163:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   17164:                     } else {
                   17165:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   17166:                     }
1.443     albertel 17167:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  17168:                     if ($sec eq '') {
                   17169:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   17170:                     } else {
                   17171:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17172:                     }
1.443     albertel 17173:                 } else {
1.628     raeburn  17174:                     if ($sec eq '') {
                   17175:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   17176:                     } else {
                   17177:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17178:                     }
1.443     albertel 17179:                 }
                   17180:             } else {
1.1115    raeburn  17181:                 if ($secchange) { 
1.628     raeburn  17182:                     $$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;
                   17183:                 } else {
                   17184:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   17185:                 }
1.443     albertel 17186:             }
                   17187:             $result = $modify_section_result;
                   17188:         } elsif ($secchange == 1) {
1.628     raeburn  17189:             if ($oldsec eq '') {
1.1103    raeburn  17190:                 $$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  17191:             } else {
                   17192:                 $$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;
                   17193:             }
1.626     raeburn  17194:             if ($expire_role_result eq 'refused') {
                   17195:                 my $newsecurl = '/'.$cid;
                   17196:                 $newsecurl =~ s/\_/\//g;
                   17197:                 if ($sec ne '') {
                   17198:                     $newsecurl.='/'.$sec;
                   17199:                 }
                   17200:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   17201:                     if ($sec eq '') {
                   17202:                         $$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;
                   17203:                     } else {
                   17204:                         $$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;
                   17205:                     }
                   17206:                 }
                   17207:             }
1.443     albertel 17208:         }
                   17209:     } else {
1.626     raeburn  17210:         $$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 17211:         $result = "error: incomplete course id\n";
                   17212:     }
                   17213:     return $result;
                   17214: }
                   17215: 
1.1108    raeburn  17216: sub show_role_extent {
                   17217:     my ($scope,$context,$role) = @_;
                   17218:     $scope =~ s{^/}{};
                   17219:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   17220:     push(@courseroles,'co');
                   17221:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   17222:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   17223:         $scope =~ s{/}{_};
                   17224:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   17225:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   17226:         my ($audom,$auname) = split(/\//,$scope);
                   17227:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   17228:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   17229:     } else {
                   17230:         $scope =~ s{/$}{};
                   17231:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   17232:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   17233:     }
                   17234: }
                   17235: 
1.443     albertel 17236: ############################################################
                   17237: ############################################################
                   17238: 
1.566     albertel 17239: sub check_clone {
1.578     raeburn  17240:     my ($args,$linefeed) = @_;
1.566     albertel 17241:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   17242:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   17243:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  17244:     my $clonetitle;
                   17245:     my @clonemsg;
1.566     albertel 17246:     my $can_clone = 0;
1.944     raeburn  17247:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  17248:     if ($lctype ne 'community') {
                   17249:         $lctype = 'course';
                   17250:     }
1.566     albertel 17251:     if ($clonehome eq 'no_host') {
1.944     raeburn  17252:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17253:             push(@clonemsg,({
                   17254:                               mt => 'No new community created.',
                   17255:                               args => [],
                   17256:                             },
                   17257:                             {
                   17258:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   17259:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   17260:                             }));
1.908     raeburn  17261:         } else {
1.1344    raeburn  17262:             push(@clonemsg,({
                   17263:                               mt => 'No new course created.',
                   17264:                               args => [],
                   17265:                             },
                   17266:                             {
                   17267:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   17268:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17269:                             }));
                   17270:         }
1.566     albertel 17271:     } else {
                   17272: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  17273:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  17274:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  17275:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  17276:                 push(@clonemsg,({
                   17277:                                   mt => 'No new community created.',
                   17278:                                   args => [],
                   17279:                                 },
                   17280:                                 {
                   17281:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   17282:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17283:                                 }));
                   17284:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  17285:             }
                   17286:         }
1.1262    raeburn  17287: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  17288:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 17289: 	    $can_clone = 1;
                   17290: 	} else {
1.1221    raeburn  17291: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 17292: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  17293:             if ($clonehash{'cloners'} eq '') {
                   17294:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   17295:                 if ($domdefs{'canclone'}) {
                   17296:                     unless ($domdefs{'canclone'} eq 'none') {
                   17297:                         if ($domdefs{'canclone'} eq 'domain') {
                   17298:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   17299:                                 $can_clone = 1;
                   17300:                             }
                   17301:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17302:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   17303:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   17304:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   17305:                                 $can_clone = 1;
                   17306:                             }
                   17307:                         }
                   17308:                     }
                   17309:                 }
1.578     raeburn  17310:             } else {
1.1221    raeburn  17311: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   17312:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  17313:                     $can_clone = 1;
1.1221    raeburn  17314:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  17315:                     $can_clone = 1;
1.1225    raeburn  17316:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   17317:                     $can_clone = 1;
1.1221    raeburn  17318:                 }
                   17319:                 unless ($can_clone) {
1.1225    raeburn  17320:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17321:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  17322:                         my (%gotdomdefaults,%gotcodedefaults);
                   17323:                         foreach my $cloner (@cloners) {
                   17324:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   17325:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   17326:                                 my (%codedefaults,@code_order);
                   17327:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   17328:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   17329:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   17330:                                     }
                   17331:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   17332:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   17333:                                     }
                   17334:                                 } else {
                   17335:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   17336:                                                                             \%codedefaults,
                   17337:                                                                             \@code_order);
                   17338:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   17339:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   17340:                                 }
                   17341:                                 if (@code_order > 0) {
                   17342:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   17343:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   17344:                                                                                 $args->{'crscode'})) {
                   17345:                                         $can_clone = 1;
                   17346:                                         last;
                   17347:                                     }
                   17348:                                 }
                   17349:                             }
                   17350:                         }
                   17351:                     }
1.1225    raeburn  17352:                 }
                   17353:             }
                   17354:             unless ($can_clone) {
                   17355:                 my $ccrole = 'cc';
                   17356:                 if ($args->{'crstype'} eq 'Community') {
                   17357:                     $ccrole = 'co';
                   17358:                 }
                   17359: 	        my %roleshash =
                   17360: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   17361: 					          $args->{'ccdomain'},
                   17362:                                                   'userroles',['active'],[$ccrole],
                   17363: 					          [$args->{'clonedomain'}]);
                   17364: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   17365:                     $can_clone = 1;
                   17366:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   17367:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   17368:                     $can_clone = 1;
1.1221    raeburn  17369:                 }
                   17370:             }
                   17371:             unless ($can_clone) {
                   17372:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17373:                     push(@clonemsg,({
                   17374:                                       mt => 'No new community created.',
                   17375:                                       args => [],
                   17376:                                     },
                   17377:                                     {
                   17378:                                       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]).',
                   17379:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17380:                                     }));
1.942     raeburn  17381:                 } else {
1.1344    raeburn  17382:                     push(@clonemsg,({
                   17383:                                       mt => 'No new course created.',
                   17384:                                       args => [],
                   17385:                                     },
                   17386:                                     {
                   17387:                                       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]).',
                   17388:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17389:                                     }));
1.1221    raeburn  17390:                 }
1.566     albertel 17391: 	    }
1.578     raeburn  17392:         }
1.566     albertel 17393:     }
1.1344    raeburn  17394:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17395: }
                   17396: 
1.444     albertel 17397: sub construct_course {
1.1262    raeburn  17398:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  17399:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   17400:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  17401:     my $linefeed =  '<br />'."\n";
                   17402:     if ($context eq 'auto') {
                   17403:         $linefeed = "\n";
                   17404:     }
1.566     albertel 17405: 
                   17406: #
                   17407: # Are we cloning?
                   17408: #
1.1344    raeburn  17409:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17410:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  17411: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 17412:         if (!$can_clone) {
1.1344    raeburn  17413: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 17414: 	}
                   17415:     }
                   17416: 
1.444     albertel 17417: #
                   17418: # Open course
                   17419: #
1.1239    raeburn  17420:     my $showncrstype;
                   17421:     if ($args->{'crstype'} eq 'Placement') {
                   17422:         $showncrstype = 'placement test'; 
                   17423:     } else {  
                   17424:         $showncrstype = lc($args->{'crstype'});
                   17425:     }
1.444     albertel 17426:     my %cenv=();
                   17427:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   17428:                                              $args->{'cdescr'},
                   17429:                                              $args->{'curl'},
                   17430:                                              $args->{'course_home'},
                   17431:                                              $args->{'nonstandard'},
                   17432:                                              $args->{'crscode'},
                   17433:                                              $args->{'ccuname'}.':'.
                   17434:                                              $args->{'ccdomain'},
1.882     raeburn  17435:                                              $args->{'crstype'},
1.1344    raeburn  17436:                                              $cnum,$context,$category,
                   17437:                                              $callercontext);
1.444     albertel 17438: 
                   17439:     # Note: The testing routines depend on this being output; see 
                   17440:     # Utils::Course. This needs to at least be output as a comment
                   17441:     # if anyone ever decides to not show this, and Utils::Course::new
                   17442:     # will need to be suitably modified.
1.1344    raeburn  17443:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17444:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17445:     } else {
                   17446:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17447:     }
1.943     raeburn  17448:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  17449:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17450:     }
                   17451: 
1.444     albertel 17452: #
                   17453: # Check if created correctly
                   17454: #
1.479     albertel 17455:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 17456:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  17457:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  17458:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17459:             $outcome .= &mt_user($user_lh,
                   17460:                             'Course creation failed, unrecognized course home server.');
                   17461:         } else {
                   17462:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   17463:         }
                   17464:         $outcome .= $linefeed;
                   17465:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17466:     }
1.541     raeburn  17467:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 17468: 
1.444     albertel 17469: #
1.566     albertel 17470: # Do the cloning
                   17471: #   
1.1344    raeburn  17472:     my @clonemsg;
1.566     albertel 17473:     if ($can_clone && $cloneid) {
1.1344    raeburn  17474:         push(@clonemsg,
                   17475:                       {
                   17476:                           mt => 'Created [_1] by cloning from [_2]',
                   17477:                           args => [$showncrstype,$clonetitle],
                   17478:                       });
1.566     albertel 17479: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 17480: # Copy all files
1.1344    raeburn  17481:         my @info =
                   17482: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   17483: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   17484:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   17485:                                                      $args->{'tinyurls'});
                   17486:         if (@info) {
                   17487:             push(@clonemsg,@info);
                   17488:         }
1.444     albertel 17489: # Restore URL
1.566     albertel 17490: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 17491: # Restore title
1.566     albertel 17492: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  17493: # Restore creation date, creator and creation context.
                   17494:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   17495:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   17496:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 17497: # Mark as cloned
1.566     albertel 17498: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      17499: # Need to clone grading mode
                   17500:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   17501:         $cenv{'grading'}=$newenv{'grading'};
                   17502: # Do not clone these environment entries
                   17503:         &Apache::lonnet::del('environment',
                   17504:                   ['default_enrollment_start_date',
                   17505:                    'default_enrollment_end_date',
                   17506:                    'question.email',
                   17507:                    'policy.email',
                   17508:                    'comment.email',
                   17509:                    'pch.users.denied',
1.725     raeburn  17510:                    'plc.users.denied',
                   17511:                    'hidefromcat',
1.1121    raeburn  17512:                    'checkforpriv',
1.1355    raeburn  17513:                    'categories'],
1.638     www      17514:                    $$crsudom,$$crsunum);
1.1170    raeburn  17515:         if ($args->{'textbook'}) {
                   17516:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   17517:         }
1.444     albertel 17518:     }
1.566     albertel 17519: 
1.444     albertel 17520: #
                   17521: # Set environment (will override cloned, if existing)
                   17522: #
                   17523:     my @sections = ();
                   17524:     my @xlists = ();
                   17525:     if ($args->{'crstype'}) {
                   17526:         $cenv{'type'}=$args->{'crstype'};
                   17527:     }
1.1371    raeburn  17528:     if ($args->{'lti'}) {
                   17529:         $cenv{'internal.lti'}=$args->{'lti'};
                   17530:     }
1.444     albertel 17531:     if ($args->{'crsid'}) {
                   17532:         $cenv{'courseid'}=$args->{'crsid'};
                   17533:     }
                   17534:     if ($args->{'crscode'}) {
                   17535:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   17536:     }
                   17537:     if ($args->{'crsquota'} ne '') {
                   17538:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   17539:     } else {
                   17540:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   17541:     }
                   17542:     if ($args->{'ccuname'}) {
                   17543:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   17544:                                         ':'.$args->{'ccdomain'};
                   17545:     } else {
                   17546:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   17547:     }
1.1116    raeburn  17548:     if ($args->{'defaultcredits'}) {
                   17549:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   17550:     }
1.444     albertel 17551:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1412    raeburn  17552:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 17553:     if ($args->{'crssections'}) {
                   17554:         $cenv{'internal.sectionnums'} = '';
                   17555:         if ($args->{'crssections'} =~ m/,/) {
                   17556:             @sections = split/,/,$args->{'crssections'};
                   17557:         } else {
                   17558:             $sections[0] = $args->{'crssections'};
                   17559:         }
                   17560:         if (@sections > 0) {
                   17561:             foreach my $item (@sections) {
                   17562:                 my ($sec,$gp) = split/:/,$item;
                   17563:                 my $class = $args->{'crscode'}.$sec;
                   17564:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   17565:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1412    raeburn  17566:                 if ($addcheck eq 'ok') {
                   17567:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17568:                         push(@oklcsecs,$gp);
                   17569:                     }
                   17570:                 } else {
1.1263    raeburn  17571:                     push(@badclasses,$class);
1.444     albertel 17572:                 }
                   17573:             }
                   17574:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   17575:         }
                   17576:     }
                   17577: # do not hide course coordinator from staff listing, 
                   17578: # even if privileged
                   17579:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  17580: # add course coordinator's domain to domains to check for privileged users
                   17581: # if different to course domain
                   17582:     if ($$crsudom ne $args->{'ccdomain'}) {
                   17583:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   17584:     }
1.444     albertel 17585: # add crosslistings
                   17586:     if ($args->{'crsxlist'}) {
                   17587:         $cenv{'internal.crosslistings'}='';
                   17588:         if ($args->{'crsxlist'} =~ m/,/) {
                   17589:             @xlists = split/,/,$args->{'crsxlist'};
                   17590:         } else {
                   17591:             $xlists[0] = $args->{'crsxlist'};
                   17592:         }
                   17593:         if (@xlists > 0) {
                   17594:             foreach my $item (@xlists) {
                   17595:                 my ($xl,$gp) = split/:/,$item;
                   17596:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   17597:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1412    raeburn  17598:                 if ($addcheck eq 'ok') {
                   17599:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17600:                         push(@oklcsecs,$gp);
                   17601:                     }
                   17602:                 } else {
1.1263    raeburn  17603:                     push(@badclasses,$xl);
1.444     albertel 17604:                 }
                   17605:             }
                   17606:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   17607:         }
                   17608:     }
                   17609:     if ($args->{'autoadds'}) {
                   17610:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   17611:     }
                   17612:     if ($args->{'autodrops'}) {
                   17613:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   17614:     }
                   17615: # check for notification of enrollment changes
                   17616:     my @notified = ();
                   17617:     if ($args->{'notify_owner'}) {
                   17618:         if ($args->{'ccuname'} ne '') {
                   17619:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   17620:         }
                   17621:     }
                   17622:     if ($args->{'notify_dc'}) {
                   17623:         if ($uname ne '') { 
1.630     raeburn  17624:             push(@notified,$uname.':'.$udom);
1.444     albertel 17625:         }
                   17626:     }
                   17627:     if (@notified > 0) {
                   17628:         my $notifylist;
                   17629:         if (@notified > 1) {
                   17630:             $notifylist = join(',',@notified);
                   17631:         } else {
                   17632:             $notifylist = $notified[0];
                   17633:         }
                   17634:         $cenv{'internal.notifylist'} = $notifylist;
                   17635:     }
                   17636:     if (@badclasses > 0) {
                   17637:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  17638:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   17639:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   17640:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 17641:         );
1.1264    raeburn  17642:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   17643:                            &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  17644:         if ($context eq 'auto') {
                   17645:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  17646:         } else {
1.566     albertel 17647:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  17648:         }
                   17649:         foreach my $item (@badclasses) {
1.541     raeburn  17650:             if ($context eq 'auto') {
1.1261    raeburn  17651:                 $outcome .= " - $item\n";
1.541     raeburn  17652:             } else {
1.1261    raeburn  17653:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  17654:             }
1.1261    raeburn  17655:         }
                   17656:         if ($context eq 'auto') {
                   17657:             $outcome .= $linefeed;
                   17658:         } else {
                   17659:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  17660:         } 
1.444     albertel 17661:     }
                   17662:     if ($args->{'no_end_date'}) {
                   17663:         $args->{'endaccess'} = 0;
                   17664:     }
1.1412    raeburn  17665: #  If an official course with institutional sections is created by cloning 
                   17666: #  an existing course, section-specific hiding of course totals in student's
                   17667: #  view of grades as copied from cloned course, will be checked for valid 
                   17668: #  sections.
                   17669:     if (($can_clone && $cloneid) &&
                   17670:         ($cenv{'internal.coursecode'} ne '') &&
                   17671:         ($cenv{'grading'} eq 'standard') &&
                   17672:         ($cenv{'hidetotals'} ne '') &&
                   17673:         ($cenv{'hidetotals'} ne 'all')) {
                   17674:         my @hidesecs;
                   17675:         my $deletehidetotals;
                   17676:         if (@oklcsecs) {
                   17677:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   17678:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   17679:                     push(@hidesecs,$sec);
                   17680:                 }
                   17681:             }
                   17682:             if (@hidesecs) {
                   17683:                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   17684:             } else {
                   17685:                 $deletehidetotals = 1;
                   17686:             }
                   17687:         } else {
                   17688:             $deletehidetotals = 1;
                   17689:         }
                   17690:         if ($deletehidetotals) {
                   17691:             delete($cenv{'hidetotals'});
                   17692:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   17693:         }
                   17694:     }
1.444     albertel 17695:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   17696:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   17697:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   17698:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   17699:     if ($args->{'showphotos'}) {
                   17700:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   17701:     }
                   17702:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   17703:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   17704:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   17705:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  17706:             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'); 
                   17707:             if ($context eq 'auto') {
                   17708:                 $outcome .= $krb_msg;
                   17709:             } else {
1.566     albertel 17710:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  17711:             }
                   17712:             $outcome .= $linefeed;
1.444     albertel 17713:         }
                   17714:     }
                   17715:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   17716:        if ($args->{'setpolicy'}) {
                   17717:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17718:        }
                   17719:        if ($args->{'setcontent'}) {
                   17720:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17721:        }
1.1251    raeburn  17722:        if ($args->{'setcomment'}) {
                   17723:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17724:        }
1.444     albertel 17725:     }
                   17726:     if ($args->{'reshome'}) {
                   17727: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   17728: 	$cenv{'reshome'}=~s/\/+$/\//;
                   17729:     }
                   17730: #
                   17731: # course has keyed access
                   17732: #
                   17733:     if ($args->{'setkeys'}) {
                   17734:        $cenv{'keyaccess'}='yes';
                   17735:     }
                   17736: # if specified, key authority is not course, but user
                   17737: # only active if keyaccess is yes
                   17738:     if ($args->{'keyauth'}) {
1.487     albertel 17739: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   17740: 	$user = &LONCAPA::clean_username($user);
                   17741: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     17742: 	if ($user ne '' && $domain ne '') {
1.487     albertel 17743: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 17744: 	}
                   17745:     }
                   17746: 
1.1166    raeburn  17747: #
1.1167    raeburn  17748: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17749: #
                   17750:     if ($args->{'uniquecode'}) {
                   17751:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17752:         if ($code) {
                   17753:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17754:             my %crsinfo =
                   17755:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17756:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17757:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17758:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17759:             } 
1.1166    raeburn  17760:             if (ref($coderef)) {
                   17761:                 $$coderef = $code;
                   17762:             }
                   17763:         }
                   17764:     }
                   17765: 
1.444     albertel 17766:     if ($args->{'disresdis'}) {
                   17767:         $cenv{'pch.roles.denied'}='st';
                   17768:     }
                   17769:     if ($args->{'disablechat'}) {
                   17770:         $cenv{'plc.roles.denied'}='st';
                   17771:     }
                   17772: 
                   17773:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17774:     # course
                   17775:     $cenv{'course.helper.not.run'} = 1;
                   17776:     #
                   17777:     # Use new Randomseed
                   17778:     #
                   17779:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17780:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17781:     #
                   17782:     # The encryption code and receipt prefix for this course
                   17783:     #
                   17784:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17785:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17786:     #
                   17787:     # By default, use standard grading
                   17788:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17789: 
1.541     raeburn  17790:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17791:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17792: #
                   17793: # Open all assignments
                   17794: #
                   17795:     if ($args->{'openall'}) {
1.1341    raeburn  17796:        my $opendate = time;
                   17797:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17798:            $opendate = $args->{'openallfrom'};
                   17799:        }
1.444     albertel 17800:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17801:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17802:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17803:        $outcome .= &mt('All assignments open starting [_1]',
                   17804:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17805:                    &Apache::lonnet::cput
                   17806:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17807:    }
                   17808: #
                   17809: # Set first page
                   17810: #
                   17811:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17812: 	    || ($cloneid)) {
                   17813: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17814: 
                   17815: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17816:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17817: 
1.444     albertel 17818:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17819:         my $title; my $url;
                   17820:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17821: 	    $title=&mt('Syllabus');
1.444     albertel 17822:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17823:         } else {
1.963     raeburn  17824:             $title=&mt('Table of Contents');
1.444     albertel 17825:             $url='/adm/navmaps';
                   17826:         }
1.445     albertel 17827: 
                   17828:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17829: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17830: 
                   17831: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17832:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17833:     }
1.566     albertel 17834: 
1.1237    raeburn  17835: # 
                   17836: # Set params for Placement Tests
                   17837: #
1.1239    raeburn  17838:     if ($args->{'crstype'} eq 'Placement') {
                   17839:        my %storecontent; 
                   17840:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17841:        my %defaults = (
                   17842:                         buttonshide   => { value => 'yes',
                   17843:                                            type => 'string_yesno',},
                   17844:                         type          => { value => 'randomizetry',
                   17845:                                            type  => 'string_questiontype',},
                   17846:                         maxtries      => { value => 1,
                   17847:                                            type => 'int_pos',},
                   17848:                         problemstatus => { value => 'no',
                   17849:                                            type  => 'string_problemstatus',},
                   17850:                       );
                   17851:        foreach my $key (keys(%defaults)) {
                   17852:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17853:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17854:        }
1.1237    raeburn  17855:        &Apache::lonnet::cput
                   17856:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17857:     }
                   17858: 
1.1344    raeburn  17859:     return (1,$outcome,\@clonemsg);
1.444     albertel 17860: }
                   17861: 
1.1166    raeburn  17862: sub make_unique_code {
                   17863:     my ($cdom,$cnum) = @_;
                   17864:     # get lock on uniquecodes db
                   17865:     my $lockhash = {
                   17866:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17867:                                                   ':'.$env{'user.domain'},
                   17868:                    };
                   17869:     my $tries = 0;
                   17870:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17871:     my ($code,$error);
                   17872:   
                   17873:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17874:         $tries ++;
                   17875:         sleep 1;
                   17876:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17877:     }
                   17878:     if ($gotlock eq 'ok') {
                   17879:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17880:         my $gotcode;
                   17881:         my $attempts = 0;
                   17882:         while ((!$gotcode) && ($attempts < 100)) {
                   17883:             $code = &generate_code();
                   17884:             if (!exists($currcodes{$code})) {
                   17885:                 $gotcode = 1;
                   17886:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17887:                     $error = 'nostore';
                   17888:                 }
                   17889:             }
                   17890:             $attempts ++;
                   17891:         }
                   17892:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17893:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17894:     } else {
                   17895:         $error = 'nolock';
                   17896:     }
                   17897:     return ($code,$error);
                   17898: }
                   17899: 
                   17900: sub generate_code {
                   17901:     my $code;
                   17902:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17903:     for (my $i=0; $i<6; $i++) {
                   17904:         my $lettnum = int (rand 2);
                   17905:         my $item = '';
                   17906:         if ($lettnum) {
                   17907:             $item = $letts[int( rand(18) )];
                   17908:         } else {
                   17909:             $item = 1+int( rand(8) );
                   17910:         }
                   17911:         $code .= $item;
                   17912:     }
                   17913:     return $code;
                   17914: }
                   17915: 
1.444     albertel 17916: ############################################################
                   17917: ############################################################
                   17918: 
1.1237    raeburn  17919: # Community, Course and Placement Test
1.378     raeburn  17920: sub course_type {
                   17921:     my ($cid) = @_;
                   17922:     if (!defined($cid)) {
                   17923:         $cid = $env{'request.course.id'};
                   17924:     }
1.404     albertel 17925:     if (defined($env{'course.'.$cid.'.type'})) {
                   17926:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17927:     } else {
                   17928:         return 'Course';
1.377     raeburn  17929:     }
                   17930: }
1.156     albertel 17931: 
1.406     raeburn  17932: sub group_term {
                   17933:     my $crstype = &course_type();
                   17934:     my %names = (
                   17935:                   'Course' => 'group',
1.865     raeburn  17936:                   'Community' => 'group',
1.1237    raeburn  17937:                   'Placement' => 'group',
1.406     raeburn  17938:                 );
                   17939:     return $names{$crstype};
                   17940: }
                   17941: 
1.902     raeburn  17942: sub course_types {
1.1310    raeburn  17943:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17944:     my %typename = (
                   17945:                          official   => 'Official course',
                   17946:                          unofficial => 'Unofficial course',
                   17947:                          community  => 'Community',
1.1165    raeburn  17948:                          textbook   => 'Textbook course',
1.1237    raeburn  17949:                          placement  => 'Placement test',
1.1310    raeburn  17950:                          lti        => 'LTI provider',
1.902     raeburn  17951:                    );
                   17952:     return (\@types,\%typename);
                   17953: }
                   17954: 
1.156     albertel 17955: sub icon {
                   17956:     my ($file)=@_;
1.505     albertel 17957:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17958:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17959:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17960:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17961: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17962: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17963: 	            $curfext.".gif") {
                   17964: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17965: 		$curfext.".gif";
                   17966: 	}
                   17967:     }
1.249     albertel 17968:     return &lonhttpdurl($iconname);
1.154     albertel 17969: } 
1.84      albertel 17970: 
1.575     albertel 17971: sub lonhttpdurl {
1.692     www      17972: #
                   17973: # Had been used for "small fry" static images on separate port 8080.
                   17974: # Modify here if lightweight http functionality desired again.
                   17975: # Currently eliminated due to increasing firewall issues.
                   17976: #
1.575     albertel 17977:     my ($url)=@_;
1.692     www      17978:     return $url;
1.215     albertel 17979: }
                   17980: 
1.213     albertel 17981: sub connection_aborted {
                   17982:     my ($r)=@_;
                   17983:     $r->print(" ");$r->rflush();
                   17984:     my $c = $r->connection;
                   17985:     return $c->aborted();
                   17986: }
                   17987: 
1.221     foxr     17988: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17989: #    strings as 'strings'.
                   17990: sub escape_single {
1.221     foxr     17991:     my ($input) = @_;
1.223     albertel 17992:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17993:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17994:     return $input;
                   17995: }
1.223     albertel 17996: 
1.222     foxr     17997: #  Same as escape_single, but escape's "'s  This 
                   17998: #  can be used for  "strings"
                   17999: sub escape_double {
                   18000:     my ($input) = @_;
                   18001:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   18002:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   18003:     return $input;
                   18004: }
1.223     albertel 18005:  
1.222     foxr     18006: #   Escapes the last element of a full URL.
                   18007: sub escape_url {
                   18008:     my ($url)   = @_;
1.238     raeburn  18009:     my @urlslices = split(/\//, $url,-1);
1.369     www      18010:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  18011:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     18012: }
1.462     albertel 18013: 
1.820     raeburn  18014: sub compare_arrays {
                   18015:     my ($arrayref1,$arrayref2) = @_;
                   18016:     my (@difference,%count);
                   18017:     @difference = ();
                   18018:     %count = ();
                   18019:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   18020:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   18021:         foreach my $element (keys(%count)) {
                   18022:             if ($count{$element} == 1) {
                   18023:                 push(@difference,$element);
                   18024:             }
                   18025:         }
                   18026:     }
                   18027:     return @difference;
                   18028: }
                   18029: 
1.1322    raeburn  18030: sub lon_status_items {
                   18031:     my %defaults = (
                   18032:                      E         => 100,
                   18033:                      W         => 4,
                   18034:                      N         => 1,
1.1324    raeburn  18035:                      U         => 5,
1.1322    raeburn  18036:                      threshold => 200,
                   18037:                      sysmail   => 2500,
                   18038:                    );
                   18039:     my %names = (
                   18040:                    E => 'Errors',
                   18041:                    W => 'Warnings',
                   18042:                    N => 'Notices',
1.1324    raeburn  18043:                    U => 'Unsent',
1.1322    raeburn  18044:                 );
                   18045:     return (\%defaults,\%names);
                   18046: }
                   18047: 
1.817     bisitz   18048: # -------------------------------------------------------- Initialize user login
1.462     albertel 18049: sub init_user_environment {
1.463     albertel 18050:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 18051:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   18052: 
                   18053:     my $public=($username eq 'public' && $domain eq 'public');
                   18054: 
1.1415    raeburn  18055:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   18056:         $coauthorenv);
1.462     albertel 18057:     my $now=time;
                   18058: 
                   18059:     if ($public) {
                   18060: 	my $max_public=100;
                   18061: 	my $oldest;
                   18062: 	my $oldest_time=0;
                   18063: 	for(my $next=1;$next<=$max_public;$next++) {
                   18064: 	    if (-e $lonids."/publicuser_$next.id") {
                   18065: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   18066: 		if ($mtime<$oldest_time || !$oldest_time) {
                   18067: 		    $oldest_time=$mtime;
                   18068: 		    $oldest=$next;
                   18069: 		}
                   18070: 	    } else {
                   18071: 		$cookie="publicuser_$next";
                   18072: 		last;
                   18073: 	    }
                   18074: 	}
                   18075: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   18076:     } else {
1.1275    raeburn  18077: 	# See if old ID present, if so, remove if this isn't a robot,
                   18078: 	# killing any existing non-robot sessions
1.463     albertel 18079: 	if (!$args->{'robot'}) {
                   18080: 	    opendir(DIR,$lonids);
                   18081: 	    while ($filename=readdir(DIR)) {
                   18082: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  18083:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   18084:                             &GDBM_READER(),0640)) {
1.1295    raeburn  18085:                         my $linkedfile;
1.1320    raeburn  18086:                         if (exists($oldenv{'user.linkedenv'})) {
                   18087:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  18088:                         }
1.1320    raeburn  18089:                         untie(%oldenv);
                   18090:                         if (unlink("$lonids/$filename")) {
                   18091:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   18092:                                 if (-l "$lonids/$linkedfile.id") {
                   18093:                                     unlink("$lonids/$linkedfile.id");
                   18094:                                 }
1.1295    raeburn  18095:                             }
                   18096:                         }
                   18097:                     } else {
                   18098:                         unlink($lonids.'/'.$filename);
                   18099:                     }
1.463     albertel 18100: 		}
1.462     albertel 18101: 	    }
1.463     albertel 18102: 	    closedir(DIR);
1.1204    raeburn  18103: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   18104:             my $namespace = 'nohist_courseeditor';
                   18105:             my $lockingkey = 'paste'."\0".'locked_num';
                   18106:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   18107:                                                 $domain,$username);
                   18108:             if (exists($lockhash{$lockingkey})) {
                   18109:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   18110:                 unless ($delresult eq 'ok') {
                   18111:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   18112:                 }
                   18113:             }
1.462     albertel 18114: 	}
                   18115: # Give them a new cookie
1.463     albertel 18116: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      18117: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 18118: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 18119:     
                   18120: # Initialize roles
                   18121: 
1.1414    raeburn  18122: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  18123:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 18124:     }
                   18125: # ------------------------------------ Check browser type and MathML capability
                   18126: 
1.1194    raeburn  18127:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   18128:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 18129: 
                   18130: # ------------------------------------------------------------- Get environment
                   18131: 
                   18132:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   18133:     my ($tmp) = keys(%userenv);
1.1275    raeburn  18134:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 18135: 	undef(%userenv);
                   18136:     }
                   18137:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   18138: 	$form->{'interface'}=$userenv{'interface'};
                   18139:     }
                   18140:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   18141: 
                   18142: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   18143:     foreach my $option ('interface','localpath','localres') {
                   18144:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 18145:     }
                   18146: # --------------------------------------------------------- Write first profile
                   18147: 
                   18148:     {
1.1350    raeburn  18149:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 18150: 	my %initial_env = 
                   18151: 	    ("user.name"          => $username,
                   18152: 	     "user.domain"        => $domain,
                   18153: 	     "user.home"          => $authhost,
                   18154: 	     "browser.type"       => $clientbrowser,
                   18155: 	     "browser.version"    => $clientversion,
                   18156: 	     "browser.mathml"     => $clientmathml,
                   18157: 	     "browser.unicode"    => $clientunicode,
                   18158: 	     "browser.os"         => $clientos,
1.1137    raeburn  18159:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  18160:              "browser.info"       => $clientinfo,
1.1194    raeburn  18161:              "browser.osversion"  => $clientosversion,
1.462     albertel 18162: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   18163: 	     "request.course.fn"  => '',
                   18164: 	     "request.course.uri" => '',
                   18165: 	     "request.course.sec" => '',
                   18166: 	     "request.role"       => 'cm',
                   18167: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  18168: 	     "request.host"       => $ip,);
1.462     albertel 18169: 
                   18170:         if ($form->{'localpath'}) {
                   18171: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   18172: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   18173:         }
                   18174: 	
                   18175: 	if ($form->{'interface'}) {
                   18176: 	    $form->{'interface'}=~s/\W//gs;
                   18177: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   18178: 	    $env{'browser.interface'}=$form->{'interface'};
                   18179: 	}
                   18180: 
1.1157    raeburn  18181:         if ($form->{'iptoken'}) {
                   18182:             my $lonhost = $r->dir_config('lonHostID');
                   18183:             $initial_env{"user.noloadbalance"} = $lonhost;
                   18184:             $env{'user.noloadbalance'} = $lonhost;
                   18185:         }
                   18186: 
1.1268    raeburn  18187:         if ($form->{'noloadbalance'}) {
                   18188:             my @hosts = &Apache::lonnet::current_machine_ids();
                   18189:             my $hosthere = $form->{'noloadbalance'};
                   18190:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   18191:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   18192:                 $env{'user.noloadbalance'} = $hosthere;
                   18193:             }
                   18194:         }
                   18195: 
1.1016    raeburn  18196:         unless ($domain eq 'public') {
1.1273    raeburn  18197:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   18198:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   18199: 
1.1414    raeburn  18200:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
                   18201:                 $userenv{'availabletools.'.$tool} =
1.1273    raeburn  18202:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   18203:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   18204:             }
1.980     raeburn  18205: 
1.1311    raeburn  18206:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  18207:                 $userenv{'canrequest.'.$crstype} =
                   18208:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   18209:                                                       'reload','requestcourses',
                   18210:                                                       \%userenv,\%domdef,\%is_adv);
                   18211:             }
1.724     raeburn  18212: 
1.1418    raeburn  18213:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   18214:                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   18215:                 if ($userenv{'authoreditors'}) {
                   18216:                     $userenv{'editors'} = $userenv{'authoreditors'};
                   18217:                 } elsif ($domdef{'editors'} ne '') {
                   18218:                     $userenv{'editors'} = $domdef{'editors'};
                   18219:                 } else {
                   18220:                     $userenv{'editors'} = 'edit,xml';
                   18221:                 }
1.1431    raeburn  18222:                 if ($userenv{'authorarchive'}) {
                   18223:                     $userenv{'canarchive'} = 1;
                   18224:                 } elsif (($userenv{'authorarchive'} eq '') &&
                   18225:                          ($domdef{'archive'})) {
                   18226:                     $userenv{'canarchive'} = 1;
                   18227:                 }
1.1418    raeburn  18228:             }
                   18229: 
1.1273    raeburn  18230:             $userenv{'canrequest.author'} =
                   18231:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   18232:                                                   'reload','requestauthor',
1.980     raeburn  18233:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  18234:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   18235:                                                  $domain,$username);
                   18236:             my $reqstatus = $reqauthor{'author_status'};
                   18237:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   18238:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   18239:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   18240:                                                       $reqauthor{'author'}{'timestamp'};
                   18241:                 }
1.1092    raeburn  18242:             }
1.1287    raeburn  18243:             my ($types,$typename) = &course_types();
                   18244:             if (ref($types) eq 'ARRAY') {
                   18245:                 my @options = ('approval','validate','autolimit');
                   18246:                 my $optregex = join('|',@options);
                   18247:                 my (%willtrust,%trustchecked);
                   18248:                 foreach my $type (@{$types}) {
                   18249:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   18250:                     if ($dom_str ne '') {
                   18251:                         my $updatedstr = '';
                   18252:                         my @possdomains = split(',',$dom_str);
                   18253:                         foreach my $entry (@possdomains) {
                   18254:                             my ($extdom,$extopt) = split(':',$entry);
                   18255:                             unless ($trustchecked{$extdom}) {
                   18256:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   18257:                                 $trustchecked{$extdom} = 1;
                   18258:                             }
                   18259:                             if ($willtrust{$extdom}) {
                   18260:                                 $updatedstr .= $entry.',';
                   18261:                             }
                   18262:                         }
                   18263:                         $updatedstr =~ s/,$//;
                   18264:                         if ($updatedstr) {
                   18265:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   18266:                         } else {
                   18267:                             delete($userenv{'reqcrsotherdom.'.$type});
                   18268:                         }
                   18269:                     }
                   18270:                 }
                   18271:             }
1.1092    raeburn  18272:         }
1.462     albertel 18273: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  18274: 
1.462     albertel 18275: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   18276: 		 &GDBM_WRCREAT(),0640)) {
                   18277: 	    &_add_to_env(\%disk_env,\%initial_env);
                   18278: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   18279: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  18280:             if (ref($firstaccenv) eq 'HASH') {
                   18281:                 &_add_to_env(\%disk_env,$firstaccenv);
                   18282:             }
                   18283:             if (ref($timerintenv) eq 'HASH') {
                   18284:                 &_add_to_env(\%disk_env,$timerintenv);
                   18285:             }
1.1414    raeburn  18286:             if (ref($coauthorenv) eq 'HASH') {
                   18287:                 if (keys(%{$coauthorenv})) {
                   18288:                     &_add_to_env(\%disk_env,$coauthorenv);
                   18289:                 }
                   18290:             }
1.463     albertel 18291: 	    if (ref($args->{'extra_env'})) {
                   18292: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   18293: 	    }
1.462     albertel 18294: 	    untie(%disk_env);
                   18295: 	} else {
1.705     tempelho 18296: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   18297: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 18298: 	    return 'error: '.$!;
                   18299: 	}
                   18300:     }
                   18301:     $env{'request.role'}='cm';
                   18302:     $env{'request.role.adv'}=$env{'user.adv'};
                   18303:     $env{'browser.type'}=$clientbrowser;
                   18304: 
                   18305:     return $cookie;
                   18306: 
                   18307: }
                   18308: 
                   18309: sub _add_to_env {
                   18310:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  18311:     if (ref($env_data) eq 'HASH') {
                   18312:         while (my ($key,$value) = each(%$env_data)) {
                   18313: 	    $idf->{$prefix.$key} = $value;
                   18314: 	    $env{$prefix.$key}   = $value;
                   18315:         }
1.462     albertel 18316:     }
                   18317: }
                   18318: 
1.685     tempelho 18319: # --- Get the symbolic name of a problem and the url
                   18320: sub get_symb {
                   18321:     my ($request,$silent) = @_;
1.726     raeburn  18322:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 18323:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   18324:     if ($symb eq '') {
                   18325:         if (!$silent) {
1.1071    raeburn  18326:             if (ref($request)) { 
                   18327:                 $request->print("Unable to handle ambiguous references:$url:.");
                   18328:             }
1.685     tempelho 18329:             return ();
                   18330:         }
                   18331:     }
                   18332:     &Apache::lonenc::check_decrypt(\$symb);
                   18333:     return ($symb);
                   18334: }
                   18335: 
                   18336: # --------------------------------------------------------------Get annotation
                   18337: 
                   18338: sub get_annotation {
                   18339:     my ($symb,$enc) = @_;
                   18340: 
                   18341:     my $key = $symb;
                   18342:     if (!$enc) {
                   18343:         $key =
                   18344:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   18345:     }
                   18346:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   18347:     return $annotation{$key};
                   18348: }
                   18349: 
                   18350: sub clean_symb {
1.731     raeburn  18351:     my ($symb,$delete_enc) = @_;
1.685     tempelho 18352: 
                   18353:     &Apache::lonenc::check_decrypt(\$symb);
                   18354:     my $enc = $env{'request.enc'};
1.731     raeburn  18355:     if ($delete_enc) {
1.730     raeburn  18356:         delete($env{'request.enc'});
                   18357:     }
1.685     tempelho 18358: 
                   18359:     return ($symb,$enc);
                   18360: }
1.462     albertel 18361: 
1.1181    raeburn  18362: ############################################################
                   18363: ############################################################
                   18364: 
                   18365: =pod
                   18366: 
                   18367: =head1 Routines for building display used to search for courses
                   18368: 
                   18369: 
                   18370: =over 4
                   18371: 
                   18372: =item * &build_filters()
                   18373: 
                   18374: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  18375: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   18376: and quotacheck.pl
                   18377: 
1.1181    raeburn  18378: 
                   18379: Inputs:
                   18380: 
                   18381: filterlist - anonymous array of fields to include as potential filters 
                   18382: 
                   18383: crstype - course type
                   18384: 
                   18385: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   18386:               to pop-open a course selector (will contain "extra element"). 
                   18387: 
                   18388: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   18389: 
                   18390: filter - anonymous hash of criteria and their values
                   18391: 
                   18392: action - form action
                   18393: 
                   18394: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   18395: 
1.1182    raeburn  18396: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  18397: 
                   18398: cloneruname - username of owner of new course who wants to clone
                   18399: 
                   18400: clonerudom - domain of owner of new course who wants to clone
                   18401: 
                   18402: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   18403: 
                   18404: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   18405: 
                   18406: codedom - domain
                   18407: 
                   18408: formname - value of form element named "form". 
                   18409: 
                   18410: fixeddom - domain, if fixed.
                   18411: 
                   18412: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   18413: 
                   18414: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   18415: 
                   18416: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   18417: 
                   18418: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   18419: 
                   18420: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   18421: 
                   18422: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   18423: 
                   18424: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   18425: 
1.1182    raeburn  18426: 
1.1181    raeburn  18427: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   18428: 
1.1182    raeburn  18429: 
1.1181    raeburn  18430: Side Effects: None
                   18431: 
                   18432: =cut
                   18433: 
                   18434: # ---------------------------------------------- search for courses based on last activity etc.
                   18435: 
                   18436: sub build_filters {
                   18437:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   18438:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   18439:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   18440:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   18441:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  18442:     my ($list,$jscript);
1.1181    raeburn  18443:     my $onchange = 'javascript:updateFilters(this)';
                   18444:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   18445:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   18446:         $typeselectform,$instcodetitle);
                   18447:     if ($formname eq '') {
                   18448:         $formname = $caller;
                   18449:     }
                   18450:     foreach my $item (@{$filterlist}) {
                   18451:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   18452:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   18453:             if ($item eq 'domainfilter') {
                   18454:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   18455:             } elsif ($item eq 'coursefilter') {
                   18456:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   18457:             } elsif ($item eq 'ownerfilter') {
                   18458:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18459:             } elsif ($item eq 'ownerdomfilter') {
                   18460:                 $filter->{'ownerdomfilter'} =
                   18461:                     &LONCAPA::clean_domain($filter->{$item});
                   18462:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   18463:                                                        'ownerdomfilter',1);
                   18464:             } elsif ($item eq 'personfilter') {
                   18465:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18466:             } elsif ($item eq 'persondomfilter') {
                   18467:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   18468:                                                         'persondomfilter',1);
                   18469:             } else {
                   18470:                 $filter->{$item} =~ s/\W//g;
                   18471:             }
                   18472:             if (!$filter->{$item}) {
                   18473:                 $filter->{$item} = '';
                   18474:             }
                   18475:         }
                   18476:         if ($item eq 'domainfilter') {
                   18477:             my $allow_blank = 1;
                   18478:             if ($formname eq 'portform') {
                   18479:                 $allow_blank=0;
                   18480:             } elsif ($formname eq 'studentform') {
                   18481:                 $allow_blank=0;
                   18482:             }
                   18483:             if ($fixeddom) {
                   18484:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   18485:                                     ' value="'.$codedom.'" />'.
                   18486:                                     &Apache::lonnet::domain($codedom,'description');
                   18487:             } else {
                   18488:                 $domainselectform = &select_dom_form($filter->{$item},
                   18489:                                                      'domainfilter',
                   18490:                                                       $allow_blank,'',$onchange);
                   18491:             }
                   18492:         } else {
                   18493:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   18494:         }
                   18495:     }
                   18496: 
                   18497:     # last course activity filter and selection
                   18498:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   18499: 
                   18500:     # course created filter and selection
                   18501:     if (exists($filter->{'createdfilter'})) {
                   18502:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   18503:     }
                   18504: 
1.1239    raeburn  18505:     my $prefix = $crstype;
                   18506:     if ($crstype eq 'Placement') {
                   18507:         $prefix = 'Placement Test'
                   18508:     }
1.1181    raeburn  18509:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  18510:                 'cac' => "$prefix Activity",
                   18511:                 'ccr' => "$prefix Created",
                   18512:                 'cde' => "$prefix Title",
                   18513:                 'cdo' => "$prefix Domain",
1.1181    raeburn  18514:                 'ins' => 'Institutional Code',
                   18515:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  18516:                 'cow' => "$prefix Owner/Co-owner",
                   18517:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  18518:                 'cog' => 'Type',
                   18519:              );
                   18520: 
                   18521:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18522:         my $typeval = 'Course';
                   18523:         if ($crstype eq 'Community') {
                   18524:             $typeval = 'Community';
1.1239    raeburn  18525:         } elsif ($crstype eq 'Placement') {
                   18526:             $typeval = 'Placement';
1.1181    raeburn  18527:         }
                   18528:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   18529:     } else {
                   18530:         $typeselectform =  '<select name="type" size="1"';
                   18531:         if ($onchange) {
                   18532:             $typeselectform .= ' onchange="'.$onchange.'"';
                   18533:         }
                   18534:         $typeselectform .= '>'."\n";
1.1237    raeburn  18535:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  18536:             my $shown;
                   18537:             if ($posstype eq 'Placement') {
                   18538:                 $shown = &mt('Placement Test');
                   18539:             } else {
                   18540:                 $shown = &mt($posstype);
                   18541:             }
1.1181    raeburn  18542:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  18543:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  18544:         }
                   18545:         $typeselectform.="</select>";
                   18546:     }
                   18547: 
                   18548:     my ($cloneableonlyform,$cloneabletitle);
                   18549:     if (exists($filter->{'cloneableonly'})) {
                   18550:         my $cloneableon = '';
                   18551:         my $cloneableoff = ' checked="checked"';
                   18552:         if ($filter->{'cloneableonly'}) {
                   18553:             $cloneableon = $cloneableoff;
                   18554:             $cloneableoff = '';
                   18555:         }
                   18556:         $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>';
                   18557:         if ($formname eq 'ccrs') {
1.1187    bisitz   18558:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  18559:         } else {
                   18560:             $cloneabletitle = &mt('Cloneable by you');
                   18561:         }
                   18562:     }
                   18563:     my $officialjs;
                   18564:     if ($crstype eq 'Course') {
                   18565:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  18566: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   18567: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   18568:             if ($codedom) { 
1.1181    raeburn  18569:                 $officialjs = 1;
                   18570:                 ($instcodeform,$jscript,$$numtitlesref) =
                   18571:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   18572:                                                                   $officialjs,$codetitlesref);
                   18573:                 if ($jscript) {
1.1182    raeburn  18574:                     $jscript = '<script type="text/javascript">'."\n".
                   18575:                                '// <![CDATA['."\n".
                   18576:                                $jscript."\n".
                   18577:                                '// ]]>'."\n".
                   18578:                                '</script>'."\n";
1.1181    raeburn  18579:                 }
                   18580:             }
                   18581:             if ($instcodeform eq '') {
                   18582:                 $instcodeform =
                   18583:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   18584:                     $list->{'instcodefilter'}.'" />';
                   18585:                 $instcodetitle = $lt{'ins'};
                   18586:             } else {
                   18587:                 $instcodetitle = $lt{'inc'};
                   18588:             }
                   18589:             if ($fixeddom) {
                   18590:                 $instcodetitle .= '<br />('.$codedom.')';
                   18591:             }
                   18592:         }
                   18593:     }
                   18594:     my $output = qq|
                   18595: <form method="post" name="filterpicker" action="$action">
                   18596: <input type="hidden" name="form" value="$formname" />
                   18597: |;
                   18598:     if ($formname eq 'modifycourse') {
                   18599:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   18600:                    '<input type="hidden" name="prevphase" value="'.
                   18601:                    $prevphase.'" />'."\n";
1.1198    musolffc 18602:     } elsif ($formname eq 'quotacheck') {
                   18603:         $output .= qq|
                   18604: <input type="hidden" name="sortby" value="" />
                   18605: <input type="hidden" name="sortorder" value="" />
                   18606: |;
                   18607:     } else {
1.1181    raeburn  18608:         my $name_input;
                   18609:         if ($cnameelement ne '') {
                   18610:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   18611:                           $cnameelement.'" />';
                   18612:         }
                   18613:         $output .= qq|
1.1182    raeburn  18614: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   18615: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  18616: $name_input
                   18617: $roleelement
                   18618: $multelement
                   18619: $typeelement
                   18620: |;
                   18621:         if ($formname eq 'portform') {
                   18622:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   18623:         }
                   18624:     }
                   18625:     if ($fixeddom) {
                   18626:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   18627:     }
                   18628:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   18629:     if ($sincefilterform) {
                   18630:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   18631:                   .$sincefilterform
                   18632:                   .&Apache::lonhtmlcommon::row_closure();
                   18633:     }
                   18634:     if ($createdfilterform) {
                   18635:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   18636:                   .$createdfilterform
                   18637:                   .&Apache::lonhtmlcommon::row_closure();
                   18638:     }
                   18639:     if ($domainselectform) {
                   18640:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   18641:                   .$domainselectform
                   18642:                   .&Apache::lonhtmlcommon::row_closure();
                   18643:     }
                   18644:     if ($typeselectform) {
                   18645:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18646:             $output .= $typeselectform;
                   18647:         } else {
                   18648:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   18649:                       .$typeselectform
                   18650:                       .&Apache::lonhtmlcommon::row_closure();
                   18651:         }
                   18652:     }
                   18653:     if ($instcodeform) {
                   18654:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   18655:                   .$instcodeform
                   18656:                   .&Apache::lonhtmlcommon::row_closure();
                   18657:     }
                   18658:     if (exists($filter->{'ownerfilter'})) {
                   18659:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   18660:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18661:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   18662:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18663:                    $ownerdomselectform.'</td></tr></table>'.
                   18664:                    &Apache::lonhtmlcommon::row_closure();
                   18665:     }
                   18666:     if (exists($filter->{'personfilter'})) {
                   18667:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   18668:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18669:                    '<input type="text" name="personfilter" size="20" value="'.
                   18670:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18671:                    $persondomselectform.'</td></tr></table>'.
                   18672:                    &Apache::lonhtmlcommon::row_closure();
                   18673:     }
                   18674:     if (exists($filter->{'coursefilter'})) {
                   18675:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   18676:                   .'<input type="text" name="coursefilter" size="25" value="'
                   18677:                   .$list->{'coursefilter'}.'" />'
                   18678:                   .&Apache::lonhtmlcommon::row_closure();
                   18679:     }
                   18680:     if ($cloneableonlyform) {
                   18681:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   18682:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   18683:     }
                   18684:     if (exists($filter->{'descriptfilter'})) {
                   18685:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   18686:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   18687:                   .$list->{'descriptfilter'}.'" />'
                   18688:                   .&Apache::lonhtmlcommon::row_closure(1);
                   18689:     }
                   18690:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   18691:                '<input type="hidden" name="updater" value="" />'."\n".
                   18692:                '<input type="submit" name="gosearch" value="'.
                   18693:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   18694:     return $jscript.$clonewarning.$output;
                   18695: }
                   18696: 
                   18697: =pod 
                   18698: 
                   18699: =item * &timebased_select_form()
                   18700: 
1.1182    raeburn  18701: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  18702: filter e.g., Course Activity, Course Created, when searching for courses
                   18703: or communities
                   18704: 
                   18705: Inputs:
                   18706: 
                   18707: item - name of form element (sincefilter or createdfilter)
                   18708: 
                   18709: filter - anonymous hash of criteria and their values
                   18710: 
                   18711: Returns: HTML for a select box contained a blank, then six time selections,
                   18712:          with value set in incoming form variables currently selected. 
                   18713: 
                   18714: Side Effects: None
                   18715: 
                   18716: =cut
                   18717: 
                   18718: sub timebased_select_form {
                   18719:     my ($item,$filter) = @_;
                   18720:     if (ref($filter) eq 'HASH') {
                   18721:         $filter->{$item} =~ s/[^\d-]//g;
                   18722:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   18723:         return &select_form(
                   18724:                             $filter->{$item},
                   18725:                             $item,
                   18726:                             {      '-1' => '',
                   18727:                                 '86400' => &mt('today'),
                   18728:                                '604800' => &mt('last week'),
                   18729:                               '2592000' => &mt('last month'),
                   18730:                               '7776000' => &mt('last three months'),
                   18731:                              '15552000' => &mt('last six months'),
                   18732:                              '31104000' => &mt('last year'),
                   18733:                     'select_form_order' =>
                   18734:                            ['-1','86400','604800','2592000','7776000',
                   18735:                             '15552000','31104000']});
                   18736:     }
                   18737: }
                   18738: 
                   18739: =pod
                   18740: 
                   18741: =item * &js_changer()
                   18742: 
                   18743: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  18744: when course type or domain is changed, and also to hide 'Searching ...' on
                   18745: page load completion for page showing search result.
1.1181    raeburn  18746: 
                   18747: Inputs: None
                   18748: 
1.1183    raeburn  18749: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  18750: 
                   18751: Side Effects: None
                   18752: 
                   18753: =cut
                   18754: 
                   18755: sub js_changer {
                   18756:     return <<ENDJS;
                   18757: <script type="text/javascript">
                   18758: // <![CDATA[
                   18759: function updateFilters(caller) {
                   18760:     if (typeof(caller) != "undefined") {
                   18761:         document.filterpicker.updater.value = caller.name;
                   18762:     }
                   18763:     document.filterpicker.submit();
                   18764: }
1.1183    raeburn  18765: 
                   18766: function hideSearching() {
                   18767:     if (document.getElementById('searching')) {
                   18768:         document.getElementById('searching').style.display = 'none';
                   18769:     }
                   18770:     return;
                   18771: }
                   18772: 
1.1181    raeburn  18773: // ]]>
                   18774: </script>
                   18775: 
                   18776: ENDJS
                   18777: }
                   18778: 
                   18779: =pod
                   18780: 
1.1182    raeburn  18781: =item * &search_courses()
                   18782: 
                   18783: Process selected filters form course search form and pass to lonnet::courseiddump
                   18784: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18785: 
                   18786: Inputs:
                   18787: 
                   18788: dom - domain being searched 
                   18789: 
                   18790: type - course type ('Course' or 'Community' or '.' if any).
                   18791: 
                   18792: filter - anonymous hash of criteria and their values
                   18793: 
                   18794: numtitles - for institutional codes - number of categories
                   18795: 
                   18796: cloneruname - optional username of new course owner
                   18797: 
                   18798: clonerudom - optional domain of new course owner
                   18799: 
1.1221    raeburn  18800: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18801:             (used when DC is using course creation form)
                   18802: 
                   18803: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18804: 
1.1221    raeburn  18805: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18806:            (and so can clone automatically)
                   18807: 
                   18808: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18809: 
                   18810: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18811:               courses to clone 
1.1182    raeburn  18812: 
                   18813: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18814: 
                   18815: 
                   18816: Side Effects: None
                   18817: 
                   18818: =cut
                   18819: 
                   18820: 
                   18821: sub search_courses {
1.1221    raeburn  18822:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18823:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18824:     my (%courses,%showcourses,$cloner);
                   18825:     if (($filter->{'ownerfilter'} ne '') ||
                   18826:         ($filter->{'ownerdomfilter'} ne '')) {
                   18827:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18828:                                        $filter->{'ownerdomfilter'};
                   18829:     }
                   18830:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18831:         if (!$filter->{$item}) {
                   18832:             $filter->{$item}='.';
                   18833:         }
                   18834:     }
                   18835:     my $now = time;
                   18836:     my $timefilter =
                   18837:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18838:     my ($createdbefore,$createdafter);
                   18839:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18840:         $createdbefore = $now;
                   18841:         $createdafter = $now-$filter->{'createdfilter'};
                   18842:     }
                   18843:     my ($instcodefilter,$regexpok);
                   18844:     if ($numtitles) {
                   18845:         if ($env{'form.official'} eq 'on') {
                   18846:             $instcodefilter =
                   18847:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18848:             $regexpok = 1;
                   18849:         } elsif ($env{'form.official'} eq 'off') {
                   18850:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18851:             unless ($instcodefilter eq '') {
                   18852:                 $regexpok = -1;
                   18853:             }
                   18854:         }
                   18855:     } else {
                   18856:         $instcodefilter = $filter->{'instcodefilter'};
                   18857:     }
                   18858:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18859:     if ($type eq '') { $type = '.'; }
                   18860: 
                   18861:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18862:         $cloner = $cloneruname.':'.$clonerudom;
                   18863:     }
                   18864:     %courses = &Apache::lonnet::courseiddump($dom,
                   18865:                                              $filter->{'descriptfilter'},
                   18866:                                              $timefilter,
                   18867:                                              $instcodefilter,
                   18868:                                              $filter->{'combownerfilter'},
                   18869:                                              $filter->{'coursefilter'},
                   18870:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18871:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18872:                                              $filter->{'cloneableonly'},
                   18873:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18874:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18875:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18876:         my $ccrole;
                   18877:         if ($type eq 'Community') {
                   18878:             $ccrole = 'co';
                   18879:         } else {
                   18880:             $ccrole = 'cc';
                   18881:         }
                   18882:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18883:                                                      $filter->{'persondomfilter'},
                   18884:                                                      'userroles',undef,
                   18885:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18886:                                                      $dom);
                   18887:         foreach my $role (keys(%rolehash)) {
                   18888:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18889:             my $cid = $cdom.'_'.$cnum;
                   18890:             if (exists($courses{$cid})) {
                   18891:                 if (ref($courses{$cid}) eq 'HASH') {
                   18892:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18893:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18894:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18895:                         }
                   18896:                     } else {
                   18897:                         $courses{$cid}{roles} = [$courserole];
                   18898:                     }
                   18899:                     $showcourses{$cid} = $courses{$cid};
                   18900:                 }
                   18901:             }
                   18902:         }
                   18903:         %courses = %showcourses;
                   18904:     }
                   18905:     return %courses;
                   18906: }
                   18907: 
                   18908: =pod
                   18909: 
1.1181    raeburn  18910: =back
                   18911: 
1.1207    raeburn  18912: =head1 Routines for version requirements for current course.
                   18913: 
                   18914: =over 4
                   18915: 
                   18916: =item * &check_release_required()
                   18917: 
                   18918: Compares required LON-CAPA version with version on server, and
                   18919: if required version is newer looks for a server with the required version.
                   18920: 
                   18921: Looks first at servers in user's owen domain; if none suitable, looks at
                   18922: servers in course's domain are permitted to host sessions for user's domain.
                   18923: 
                   18924: Inputs:
                   18925: 
                   18926: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18927: 
                   18928: $courseid - Course ID of current course
                   18929: 
                   18930: $rolecode - User's current role in course (for switchserver query string).
                   18931: 
                   18932: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18933: 
                   18934: 
                   18935: Returns:
                   18936: 
                   18937: $switchserver - query string tp append to /adm/switchserver call (if 
                   18938:                 current server's LON-CAPA version is too old. 
                   18939: 
                   18940: $warning - Message is displayed if no suitable server could be found.
                   18941: 
                   18942: =cut
                   18943: 
                   18944: sub check_release_required {
                   18945:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18946:     my ($switchserver,$warning);
                   18947:     if ($required ne '') {
                   18948:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18949:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18950:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18951:             my $otherserver;
                   18952:             if (($major eq '' && $minor eq '') ||
                   18953:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18954:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18955:                 my $switchlcrev =
                   18956:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18957:                                                            $userdomserver);
                   18958:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18959:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18960:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18961:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18962:                     if ($cdom ne $env{'user.domain'}) {
                   18963:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18964:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18965:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18966:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18967:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18968:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18969:                         my $canhost =
                   18970:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18971:                                                               $coursedomserver,
                   18972:                                                               $remoterev,
                   18973:                                                               $udomdefaults{'remotesessions'},
                   18974:                                                               $defdomdefaults{'hostedsessions'});
                   18975: 
                   18976:                         if ($canhost) {
                   18977:                             $otherserver = $coursedomserver;
                   18978:                         } else {
                   18979:                             $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.");
                   18980:                         }
                   18981:                     } else {
                   18982:                         $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).");
                   18983:                     }
                   18984:                 } else {
                   18985:                     $otherserver = $userdomserver;
                   18986:                 }
                   18987:             }
                   18988:             if ($otherserver ne '') {
                   18989:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18990:             }
                   18991:         }
                   18992:     }
                   18993:     return ($switchserver,$warning);
                   18994: }
                   18995: 
                   18996: =pod
                   18997: 
                   18998: =item * &check_release_result()
                   18999: 
                   19000: Inputs:
                   19001: 
                   19002: $switchwarning - Warning message if no suitable server found to host session.
                   19003: 
                   19004: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   19005:                 and current role.
                   19006: 
                   19007: Returns: HTML to display with information about requirement to switch server.
                   19008:          Either displaying warning with link to Roles/Courses screen or
                   19009:          display link to switchserver.
                   19010: 
1.1181    raeburn  19011: =cut
                   19012: 
1.1207    raeburn  19013: sub check_release_result {
                   19014:     my ($switchwarning,$switchserver) = @_;
                   19015:     my $output = &start_page('Selected course unavailable on this server').
                   19016:                  '<p class="LC_warning">';
                   19017:     if ($switchwarning) {
                   19018:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   19019:         if (&show_course()) {
                   19020:             $output .= &mt('Display courses');
                   19021:         } else {
                   19022:             $output .= &mt('Display roles');
                   19023:         }
                   19024:         $output .= '</a>';
                   19025:     } elsif ($switchserver) {
                   19026:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   19027:                    '<br />'.
                   19028:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   19029:                    &mt('Switch Server').
                   19030:                    '</a>';
                   19031:     }
                   19032:     $output .= '</p>'.&end_page();
                   19033:     return $output;
                   19034: }
                   19035: 
                   19036: =pod
                   19037: 
                   19038: =item * &needs_coursereinit()
                   19039: 
                   19040: Determine if course contents stored for user's session needs to be
                   19041: refreshed, because content has changed since "Big Hash" last tied.
                   19042: 
                   19043: Check for change is made if time last checked is more than 10 minutes ago
                   19044: (by default).
                   19045: 
                   19046: Inputs:
                   19047: 
                   19048: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   19049: 
                   19050: $interval (optional) - Time which may elapse (in s) between last check for content
                   19051:                        change in current course. (default: 600 s).  
                   19052: 
                   19053: Returns: an array; first element is:
                   19054: 
                   19055: =over 4
                   19056: 
                   19057: 'switch' - if content updates mean user's session
                   19058:            needs to be switched to a server running a newer LON-CAPA version
                   19059:  
                   19060: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   19061:            on current server hosting user's session                
                   19062: 
                   19063: ''       - if no action required.
                   19064: 
                   19065: =back
                   19066: 
                   19067: If first item element is 'switch':
                   19068: 
                   19069: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   19070: 
                   19071: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   19072:                               and current role. 
                   19073: 
                   19074: otherwise: no other elements returned.
                   19075: 
                   19076: =back
                   19077: 
                   19078: =cut
                   19079: 
                   19080: sub needs_coursereinit {
                   19081:     my ($loncaparev,$interval) = @_;
                   19082:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   19083:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19084:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   19085:     my $now = time;
                   19086:     if ($interval eq '') {
                   19087:         $interval = 600;
                   19088:     }
                   19089:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  19090:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  19091:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19092:         if ($blocked) {
                   19093:             return ();
                   19094:         }
1.1391    raeburn  19095:         my $update;
                   19096:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19097:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   19098:         if ($lastmainchange > $env{'request.course.tied'}) {
                   19099:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19100:             if ($needswitch) {
                   19101:                 return ('switch',$switchwarning,$switchserver);
                   19102:             }
                   19103:             $update = 'main';
                   19104:         }
                   19105:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   19106:             if ($update) {
                   19107:                 $update = 'both';
                   19108:             } else {
                   19109:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19110:                 if ($needswitch) {
                   19111:                     return ('switch',$switchwarning,$switchserver);
                   19112:                 } else {
                   19113:                     $update = 'supp';
1.1207    raeburn  19114:                 }
                   19115:             }
1.1391    raeburn  19116:         }
1.1453    raeburn  19117:         return ($update);
1.1391    raeburn  19118:     }
                   19119:     return ();
                   19120: }
                   19121: 
                   19122: sub switch_for_update {
                   19123:     my ($loncaparev,$cdom,$cnum) = @_;
                   19124:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19125:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   19126:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   19127:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   19128:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   19129:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   19130:             my ($switchserver,$switchwarning) =
                   19131:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   19132:                                         $curr_reqd_hash{'internal.releaserequired'});
                   19133:             if ($switchwarning ne '' || $switchserver ne '') {
                   19134:                 return ('switch',$switchwarning,$switchserver);
                   19135:             }
1.1207    raeburn  19136:         }
                   19137:     }
                   19138:     return ();
                   19139: }
1.1181    raeburn  19140: 
1.1083    raeburn  19141: sub update_content_constraints {
1.1395    raeburn  19142:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  19143:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19144:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  19145:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  19146:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  19147:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  19148:         if ($item eq 'resourcetag') {
                   19149:             if ($name eq 'responsetype') {
                   19150:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   19151:             }
1.1307    raeburn  19152:         } elsif ($item eq 'course') {
                   19153:             if ($name eq 'courserestype') {
                   19154:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   19155:             }
1.1083    raeburn  19156:         }
                   19157:     }
                   19158:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19159:     if (defined($navmap)) {
1.1307    raeburn  19160:         my (%allresponses,%allcrsrestypes);
                   19161:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   19162:             if ($res->is_tool()) {
                   19163:                 if ($allcrsrestypes{'exttool'}) {
                   19164:                     $allcrsrestypes{'exttool'} ++;
                   19165:                 } else {
                   19166:                     $allcrsrestypes{'exttool'} = 1;
                   19167:                 }
                   19168:                 next;
                   19169:             }
1.1083    raeburn  19170:             my %responses = $res->responseTypes();
                   19171:             foreach my $key (keys(%responses)) {
                   19172:                 next unless(exists($checkresponsetypes{$key}));
                   19173:                 $allresponses{$key} += $responses{$key};
                   19174:             }
                   19175:         }
                   19176:         foreach my $key (keys(%allresponses)) {
                   19177:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   19178:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19179:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19180:             }
                   19181:         }
1.1307    raeburn  19182:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  19183:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  19184:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19185:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19186:             }
                   19187:         }
1.1083    raeburn  19188:         undef($navmap);
                   19189:     }
1.1391    raeburn  19190:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  19191:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   19192:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19193:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   19194:         }
                   19195:     }
1.1083    raeburn  19196:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   19197:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   19198:     }
                   19199:     return;
                   19200: }
                   19201: 
1.1110    raeburn  19202: sub allmaps_incourse {
                   19203:     my ($cdom,$cnum,$chome,$cid) = @_;
                   19204:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   19205:         $cid = $env{'request.course.id'};
                   19206:         $cdom = $env{'course.'.$cid.'.domain'};
                   19207:         $cnum = $env{'course.'.$cid.'.num'};
                   19208:         $chome = $env{'course.'.$cid.'.home'};
                   19209:     }
                   19210:     my %allmaps = ();
                   19211:     my $lastchange =
                   19212:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19213:     if ($lastchange > $env{'request.course.tied'}) {
                   19214:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   19215:         unless ($ferr) {
1.1395    raeburn  19216:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  19217:         }
                   19218:     }
                   19219:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19220:     if (defined($navmap)) {
                   19221:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   19222:             $allmaps{$res->src()} = 1;
                   19223:         }
                   19224:     }
                   19225:     return \%allmaps;
                   19226: }
                   19227: 
1.1083    raeburn  19228: sub parse_supplemental_title {
                   19229:     my ($title) = @_;
                   19230: 
                   19231:     my ($foldertitle,$renametitle);
                   19232:     if ($title =~ /&amp;&amp;&amp;/) {
                   19233:         $title = &HTML::Entites::decode($title);
                   19234:     }
                   19235:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   19236:         $renametitle=$4;
                   19237:         my ($time,$uname,$udom) = ($1,$2,$3);
                   19238:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   19239:         my $name =  &plainname($uname,$udom);
                   19240:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   19241:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1401    raeburn  19242:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
1.1402    raeburn  19243:         if ($foldertitle ne '') {
1.1401    raeburn  19244:             $title .= ': <br />'.$foldertitle;
                   19245:         }
1.1083    raeburn  19246:     }
                   19247:     if (wantarray) {
                   19248:         return ($title,$foldertitle,$renametitle);
                   19249:     }
                   19250:     return $title;
                   19251: }
                   19252: 
1.1395    raeburn  19253: sub get_supplemental {
                   19254:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   19255:     my $hashid=$cnum.':'.$cdom;
                   19256:     my ($supplemental,$cached,$set_httprefs);
                   19257:     unless ($ignorecache) {
                   19258:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   19259:     }
                   19260:     unless (defined($cached)) {
                   19261:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   19262:         unless ($chome eq 'no_host') {
                   19263:             my @order = @LONCAPA::map::order;
                   19264:             my @resources = @LONCAPA::map::resources;
                   19265:             my @resparms = @LONCAPA::map::resparms;
                   19266:             my @zombies = @LONCAPA::map::zombies;
                   19267:             my ($errors,%ids,%hidden);
                   19268:             $errors =
                   19269:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   19270:                                       $errors,$possdel,\%ids,\%hidden);
                   19271:             @LONCAPA::map::order = @order;
                   19272:             @LONCAPA::map::resources = @resources;
                   19273:             @LONCAPA::map::resparms = @resparms;
                   19274:             @LONCAPA::map::zombies = @zombies;
                   19275:             $set_httprefs = 1;
                   19276:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19277:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19278:             }
                   19279:             $supplemental = {
                   19280:                                ids => \%ids,
                   19281:                                hidden => \%hidden,
                   19282:                             };
                   19283:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   19284:         }
                   19285:     }
                   19286:     return ($supplemental,$set_httprefs);
                   19287: }
                   19288: 
1.1143    raeburn  19289: sub recurse_supplemental {
1.1391    raeburn  19290:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   19291:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   19292:         my $mapnum;
                   19293:         if ($suppmap eq 'supplemental.sequence') {
                   19294:             $mapnum = 0;
                   19295:         } else {
                   19296:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   19297:         }
1.1143    raeburn  19298:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   19299:         if ($fatal) {
                   19300:             $errors ++;
                   19301:         } else {
1.1389    raeburn  19302:             my @order = @LONCAPA::map::order;
                   19303:             if (@order > 0) {
                   19304:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  19305:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  19306:                 foreach my $idx (@order) {
                   19307:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  19308:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  19309:                         my $id = $mapnum.':'.$idx;
                   19310:                         push(@{$suppids->{$src}},$id);
                   19311:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   19312:                             $hiddensupp->{$id} = 1;
                   19313:                         }
1.1146    raeburn  19314:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  19315:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   19316:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  19317:                         } else {
1.1391    raeburn  19318:                             my $allowed;
                   19319:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   19320:                                 $allowed = 1;
                   19321:                             } elsif ($possdel) {
                   19322:                                 foreach my $item (@{$suppids->{$src}}) {
                   19323:                                     next if ($item eq $id);
                   19324:                                     unless ($hiddensupp->{$item}) {
                   19325:                                        $allowed = 1;
                   19326:                                        last;
                   19327:                                     }
                   19328:                                 }
                   19329:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   19330:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   19331:                                 }
                   19332:                             }
                   19333:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   19334:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  19335:                             }
1.1143    raeburn  19336:                         }
                   19337:                     }
                   19338:                 }
                   19339:             }
                   19340:         }
                   19341:     }
1.1391    raeburn  19342:     return $errors;
                   19343: }
                   19344: 
                   19345: sub set_supp_httprefs {
                   19346:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   19347:     if (ref($supplemental) eq 'HASH') {
                   19348:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   19349:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   19350:                 next if ($src =~ /\.sequence$/);
                   19351:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   19352:                     my $allowed;
                   19353:                     if ($env{'request.role.adv'}) {
                   19354:                         $allowed = 1;
                   19355:                     } else {
                   19356:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   19357:                             unless ($supplemental->{'hidden'}->{$id}) {
                   19358:                                 $allowed = 1;
                   19359:                                 last;
                   19360:                             }
                   19361:                         }
                   19362:                     }
                   19363:                     if (exists($env{'httpref.'.$src})) {
                   19364:                         if ($possdel) {
                   19365:                             unless ($allowed) {
                   19366:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   19367:                             }
                   19368:                         }
                   19369:                     } elsif ($allowed) {
                   19370:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   19371:                     }
                   19372:                 }
                   19373:             }
                   19374:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19375:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19376:             }
                   19377:         }
                   19378:     }
                   19379: }
                   19380: 
                   19381: sub get_supp_parameter {
                   19382:     my ($resparm,$name)=@_;
                   19383:     return if ($resparm eq '');
                   19384:     my $value=undef;
                   19385:     my $ptype=undef;
                   19386:     foreach (split('&&&',$resparm)) {
                   19387:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   19388:         if ($thisname eq $name) {
                   19389:             $value=$thisvalue;
                   19390:             $ptype=$thistype;
                   19391:         }
                   19392:     }
                   19393:     return $value;
1.1143    raeburn  19394: }
                   19395: 
1.1101    raeburn  19396: sub symb_to_docspath {
1.1267    raeburn  19397:     my ($symb,$navmapref) = @_;
                   19398:     return unless ($symb && ref($navmapref));
1.1101    raeburn  19399:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   19400:     if ($resurl=~/\.(sequence|page)$/) {
                   19401:         $mapurl=$resurl;
                   19402:     } elsif ($resurl eq 'adm/navmaps') {
                   19403:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   19404:     }
                   19405:     my $mapresobj;
1.1267    raeburn  19406:     unless (ref($$navmapref)) {
                   19407:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   19408:     }
                   19409:     if (ref($$navmapref)) {
                   19410:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  19411:     }
                   19412:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   19413:     my $type=$2;
                   19414:     my $path;
                   19415:     if (ref($mapresobj)) {
                   19416:         my $pcslist = $mapresobj->map_hierarchy();
                   19417:         if ($pcslist ne '') {
                   19418:             foreach my $pc (split(/,/,$pcslist)) {
                   19419:                 next if ($pc <= 1);
1.1267    raeburn  19420:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  19421:                 if (ref($res)) {
                   19422:                     my $thisurl = $res->src();
                   19423:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   19424:                     my $thistitle = $res->title();
                   19425:                     $path .= '&'.
                   19426:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  19427:                              &escape($thistitle).
1.1101    raeburn  19428:                              ':'.$res->randompick().
                   19429:                              ':'.$res->randomout().
                   19430:                              ':'.$res->encrypted().
                   19431:                              ':'.$res->randomorder().
                   19432:                              ':'.$res->is_page();
                   19433:                 }
                   19434:             }
                   19435:         }
                   19436:         $path =~ s/^\&//;
                   19437:         my $maptitle = $mapresobj->title();
                   19438:         if ($mapurl eq 'default') {
1.1129    raeburn  19439:             $maptitle = 'Main Content';
1.1101    raeburn  19440:         }
                   19441:         $path .= (($path ne '')? '&' : '').
                   19442:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19443:                  &escape($maptitle).
1.1101    raeburn  19444:                  ':'.$mapresobj->randompick().
                   19445:                  ':'.$mapresobj->randomout().
                   19446:                  ':'.$mapresobj->encrypted().
                   19447:                  ':'.$mapresobj->randomorder().
                   19448:                  ':'.$mapresobj->is_page();
                   19449:     } else {
                   19450:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   19451:         my $ispage = (($type eq 'page')? 1 : '');
                   19452:         if ($mapurl eq 'default') {
1.1129    raeburn  19453:             $maptitle = 'Main Content';
1.1101    raeburn  19454:         }
                   19455:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19456:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  19457:     }
                   19458:     unless ($mapurl eq 'default') {
                   19459:         $path = 'default&'.
1.1146    raeburn  19460:                 &escape('Main Content').
1.1101    raeburn  19461:                 ':::::&'.$path;
                   19462:     }
                   19463:     return $path;
                   19464: }
                   19465: 
1.1393    raeburn  19466: sub validate_folderpath {
                   19467:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   19468:     if ($env{'form.folderpath'} ne '') {
                   19469:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  19470:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  19471:         for (my $i=0; $i<@items; $i++) {
                   19472:             my $odd = $i%2;
                   19473:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   19474:                 $badpath = 1;
1.1394    raeburn  19475:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  19476:                 my $idx = $i-1;
1.1394    raeburn  19477:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   19478:                     my $esc_name = $1;
                   19479:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   19480:                         $supppath .= '&'.$esc_name;
                   19481:                         $changed = 1;
                   19482:                     } else {
                   19483:                         $supppath .= '&'.$items[$i];
                   19484:                     }
                   19485:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   19486:                     $changed = 1;
1.1393    raeburn  19487:                     my $is_hidden;
                   19488:                     unless ($got_supp) {
1.1395    raeburn  19489:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  19490:                         if (ref($supplemental) eq 'HASH') {
                   19491:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   19492:                                 %supphidden = %{$supplemental->{'hidden'}};
                   19493:                             }
                   19494:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   19495:                                 %suppids = %{$supplemental->{'ids'}};
                   19496:                             }
                   19497:                         }
                   19498:                         $got_supp = 1;
                   19499:                     }
                   19500:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   19501:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   19502:                         if ($supphidden{$mapid}) {
                   19503:                             $is_hidden = 1;
                   19504:                         }
                   19505:                     }
1.1394    raeburn  19506:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   19507:                 } else {
                   19508:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  19509:                 }
                   19510:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   19511:                 $badpath = 1;
1.1394    raeburn  19512:             } elsif ($supplementalflag) {
1.1393    raeburn  19513:                 $supppath .= '&'.$items[$i];
                   19514:             }
                   19515:             last if ($badpath);
                   19516:         }
                   19517:         if ($badpath) {
                   19518:             delete($env{'form.folderpath'});
1.1394    raeburn  19519:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  19520:             $supppath =~ s/^\&//;
                   19521:             $env{'form.folderpath'} = $supppath;
                   19522:         }
                   19523:     }
                   19524:     return;
                   19525: }
                   19526: 
1.1094    raeburn  19527: sub captcha_display {
1.1327    raeburn  19528:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19529:     my ($output,$error);
1.1234    raeburn  19530:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  19531:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19532:     if ($captcha eq 'original') {
1.1094    raeburn  19533:         $output = &create_captcha();
                   19534:         unless ($output) {
1.1172    raeburn  19535:             $error = 'captcha';
1.1094    raeburn  19536:         }
                   19537:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19538:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  19539:         unless ($output) {
1.1172    raeburn  19540:             $error = 'recaptcha';
1.1094    raeburn  19541:         }
                   19542:     }
1.1234    raeburn  19543:     return ($output,$error,$captcha,$version);
1.1094    raeburn  19544: }
                   19545: 
                   19546: sub captcha_response {
1.1327    raeburn  19547:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19548:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  19549:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19550:     if ($captcha eq 'original') {
1.1094    raeburn  19551:         ($captcha_chk,$captcha_error) = &check_captcha();
                   19552:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19553:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  19554:     } else {
                   19555:         $captcha_chk = 1;
                   19556:     }
                   19557:     return ($captcha_chk,$captcha_error);
                   19558: }
                   19559: 
                   19560: sub get_captcha_config {
1.1327    raeburn  19561:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  19562:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  19563:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   19564:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   19565:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  19566:     if ($context eq 'usercreation') {
                   19567:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   19568:         if (ref($domconfig{$context}) eq 'HASH') {
                   19569:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   19570:             if (ref($hashtocheck) eq 'HASH') {
                   19571:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   19572:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   19573:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   19574:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   19575:                     }
                   19576:                     if ($privkey && $pubkey) {
                   19577:                         $captcha = 'recaptcha';
1.1234    raeburn  19578:                         $version = $hashtocheck->{'recaptchaversion'};
                   19579:                         if ($version ne '2') {
                   19580:                             $version = 1;
                   19581:                         }
1.1095    raeburn  19582:                     } else {
                   19583:                         $captcha = 'original';
                   19584:                     }
                   19585:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   19586:                     $captcha = 'original';
                   19587:                 }
1.1094    raeburn  19588:             }
1.1095    raeburn  19589:         } else {
                   19590:             $captcha = 'captcha';
                   19591:         }
                   19592:     } elsif ($context eq 'login') {
                   19593:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   19594:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   19595:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   19596:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  19597:             if ($privkey && $pubkey) {
                   19598:                 $captcha = 'recaptcha';
1.1234    raeburn  19599:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   19600:                 if ($version ne '2') {
                   19601:                     $version = 1; 
                   19602:                 }
1.1095    raeburn  19603:             } else {
                   19604:                 $captcha = 'original';
1.1094    raeburn  19605:             }
1.1095    raeburn  19606:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   19607:             $captcha = 'original';
1.1094    raeburn  19608:         }
1.1327    raeburn  19609:     } elsif ($context eq 'passwords') {
                   19610:         if ($dom_in_effect) {
                   19611:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   19612:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   19613:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   19614:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   19615:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   19616:                 }
                   19617:                 if ($privkey && $pubkey) {
                   19618:                     $captcha = 'recaptcha';
                   19619:                     $version = $passwdconf{'recaptchaversion'};
                   19620:                     if ($version ne '2') {
                   19621:                         $version = 1;
                   19622:                     }
                   19623:                 } else {
                   19624:                     $captcha = 'original';
                   19625:                 }
                   19626:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   19627:                 $captcha = 'original';
                   19628:             }
                   19629:         }
                   19630:     } 
1.1234    raeburn  19631:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  19632: }
                   19633: 
                   19634: sub create_captcha {
                   19635:     my %captcha_params = &captcha_settings();
                   19636:     my ($output,$maxtries,$tries) = ('',10,0);
                   19637:     while ($tries < $maxtries) {
                   19638:         $tries ++;
                   19639:         my $captcha = Authen::Captcha->new (
                   19640:                                            output_folder => $captcha_params{'output_dir'},
                   19641:                                            data_folder   => $captcha_params{'db_dir'},
                   19642:                                           );
                   19643:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   19644: 
                   19645:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   19646:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  19647:                       '<span class="LC_nobreak">'.
1.1453    raeburn  19648:                       '<label>'.&mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1390    raeburn  19649:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1453    raeburn  19650:                       '</label></span><br />'.
1.1176    raeburn  19651:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  19652:             last;
                   19653:         }
                   19654:     }
1.1323    raeburn  19655:     if ($output eq '') {
                   19656:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   19657:     }
1.1094    raeburn  19658:     return $output;
                   19659: }
                   19660: 
                   19661: sub captcha_settings {
                   19662:     my %captcha_params = (
                   19663:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   19664:                            www_output_dir => "/captchaspool",
                   19665:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   19666:                            numchars       => '5',
                   19667:                          );
                   19668:     return %captcha_params;
                   19669: }
                   19670: 
                   19671: sub check_captcha {
                   19672:     my ($captcha_chk,$captcha_error);
                   19673:     my $code = $env{'form.code'};
                   19674:     my $md5sum = $env{'form.crypt'};
                   19675:     my %captcha_params = &captcha_settings();
                   19676:     my $captcha = Authen::Captcha->new(
                   19677:                       output_folder => $captcha_params{'output_dir'},
                   19678:                       data_folder   => $captcha_params{'db_dir'},
                   19679:                   );
1.1109    raeburn  19680:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  19681:     my %captcha_hash = (
                   19682:                         0       => 'Code not checked (file error)',
                   19683:                        -1      => 'Failed: code expired',
                   19684:                        -2      => 'Failed: invalid code (not in database)',
                   19685:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   19686:     );
                   19687:     if ($captcha_chk != 1) {
                   19688:         $captcha_error = $captcha_hash{$captcha_chk}
                   19689:     }
                   19690:     return ($captcha_chk,$captcha_error);
                   19691: }
                   19692: 
                   19693: sub create_recaptcha {
1.1234    raeburn  19694:     my ($pubkey,$version) = @_;
                   19695:     if ($version >= 2) {
1.1367    raeburn  19696:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   19697:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  19698:     } else {
                   19699:         my $use_ssl;
                   19700:         if ($ENV{'SERVER_PORT'} == 443) {
                   19701:             $use_ssl = 1;
                   19702:         }
                   19703:         my $captcha = Captcha::reCAPTCHA->new;
                   19704:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   19705:                $captcha->get_html($pubkey,undef,$use_ssl).
                   19706:                &mt('If the text is hard to read, [_1] will replace them.',
                   19707:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   19708:                '<br /><br />';
                   19709:     }
1.1094    raeburn  19710: }
                   19711: 
                   19712: sub check_recaptcha {
1.1234    raeburn  19713:     my ($privkey,$version) = @_;
1.1094    raeburn  19714:     my $captcha_chk;
1.1350    raeburn  19715:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  19716:     if ($version >= 2) {
                   19717:         my %info = (
                   19718:                      secret   => $privkey, 
                   19719:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  19720:                      remoteip => $ip,
1.1234    raeburn  19721:                    );
1.1280    raeburn  19722:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   19723:         $request->content(join('&',map {
                   19724:                          my $name = escape($_);
                   19725:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   19726:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   19727:                          : &escape($info{$_}) );
                   19728:         } keys(%info)));
                   19729:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  19730:         if ($response->is_success)  {
                   19731:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   19732:             if (ref($data) eq 'HASH') {
                   19733:                 if ($data->{'success'}) {
                   19734:                     $captcha_chk = 1;
                   19735:                 }
                   19736:             }
                   19737:         }
                   19738:     } else {
                   19739:         my $captcha = Captcha::reCAPTCHA->new;
                   19740:         my $captcha_result =
                   19741:             $captcha->check_answer(
                   19742:                                     $privkey,
1.1350    raeburn  19743:                                     $ip,
1.1234    raeburn  19744:                                     $env{'form.recaptcha_challenge_field'},
                   19745:                                     $env{'form.recaptcha_response_field'},
                   19746:                                   );
                   19747:         if ($captcha_result->{is_valid}) {
                   19748:             $captcha_chk = 1;
                   19749:         }
1.1094    raeburn  19750:     }
                   19751:     return $captcha_chk;
                   19752: }
                   19753: 
1.1174    raeburn  19754: sub emailusername_info {
1.1244    raeburn  19755:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  19756:     my %titles = &Apache::lonlocal::texthash (
                   19757:                      lastname      => 'Last Name',
                   19758:                      firstname     => 'First Name',
                   19759:                      institution   => 'School/college/university',
                   19760:                      location      => "School's city, state/province, country",
                   19761:                      web           => "School's web address",
                   19762:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  19763:                      id            => 'Student/Employee ID',
1.1174    raeburn  19764:                  );
                   19765:     return (\@fields,\%titles);
                   19766: }
                   19767: 
1.1161    raeburn  19768: sub cleanup_html {
                   19769:     my ($incoming) = @_;
                   19770:     my $outgoing;
                   19771:     if ($incoming ne '') {
                   19772:         $outgoing = $incoming;
                   19773:         $outgoing =~ s/;/&#059;/g;
                   19774:         $outgoing =~ s/\#/&#035;/g;
                   19775:         $outgoing =~ s/\&/&#038;/g;
                   19776:         $outgoing =~ s/</&#060;/g;
                   19777:         $outgoing =~ s/>/&#062;/g;
                   19778:         $outgoing =~ s/\(/&#040/g;
                   19779:         $outgoing =~ s/\)/&#041;/g;
                   19780:         $outgoing =~ s/"/&#034;/g;
                   19781:         $outgoing =~ s/'/&#039;/g;
                   19782:         $outgoing =~ s/\$/&#036;/g;
                   19783:         $outgoing =~ s{/}{&#047;}g;
                   19784:         $outgoing =~ s/=/&#061;/g;
                   19785:         $outgoing =~ s/\\/&#092;/g
                   19786:     }
                   19787:     return $outgoing;
                   19788: }
                   19789: 
1.1190    musolffc 19790: # Checks for critical messages and returns a redirect url if one exists.
                   19791: # $interval indicates how often to check for messages.
1.1282    raeburn  19792: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19793: sub critical_redirect {
1.1282    raeburn  19794:     my ($interval,$context) = @_;
1.1356    raeburn  19795:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19796:         return ();
                   19797:     }
1.1190    musolffc 19798:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19799:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19800:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19801:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19802:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19803:             if ($blocked) {
                   19804:                 my $checkrole = "cm./$cdom/$cnum";
                   19805:                 if ($env{'request.course.sec'} ne '') {
                   19806:                     $checkrole .= "/$env{'request.course.sec'}";
                   19807:                 }
                   19808:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19809:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19810:                     return;
                   19811:                 }
                   19812:             }
                   19813:         }
1.1190    musolffc 19814:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19815:                                         $env{'user.name'});
                   19816:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19817:         my $redirecturl;
1.1190    musolffc 19818:         if ($what[0]) {
1.1356    raeburn  19819: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19820: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19821: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19822:                 return (1, $url);
1.1190    musolffc 19823:             }
1.1191    raeburn  19824:         }
                   19825:     } 
                   19826:     return ();
1.1190    musolffc 19827: }
                   19828: 
1.1174    raeburn  19829: # Use:
                   19830: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19831: #
                   19832: ##################################################
                   19833: #          password associated functions         #
                   19834: ##################################################
                   19835: sub des_keys {
                   19836:     # Make a new key for DES encryption.
                   19837:     # Each key has two parts which are returned separately.
                   19838:     # Please note:  Each key must be passed through the &hex function
                   19839:     # before it is output to the web browser.  The hex versions cannot
                   19840:     # be used to decrypt.
                   19841:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19842:                 '8','9','a','b','c','d','e','f');
                   19843:     my $lkey='';
                   19844:     for (0..7) {
                   19845:         $lkey.=$hexstr[rand(15)];
                   19846:     }
                   19847:     my $ukey='';
                   19848:     for (0..7) {
                   19849:         $ukey.=$hexstr[rand(15)];
                   19850:     }
                   19851:     return ($lkey,$ukey);
                   19852: }
                   19853: 
                   19854: sub des_decrypt {
                   19855:     my ($key,$cyphertext) = @_;
                   19856:     my $keybin=pack("H16",$key);
                   19857:     my $cypher;
                   19858:     if ($Crypt::DES::VERSION>=2.03) {
                   19859:         $cypher=new Crypt::DES $keybin;
                   19860:     } else {
                   19861:         $cypher=new DES $keybin;
                   19862:     }
1.1233    raeburn  19863:     my $plaintext='';
                   19864:     my $cypherlength = length($cyphertext);
                   19865:     my $numchunks = int($cypherlength/32);
                   19866:     for (my $j=0; $j<$numchunks; $j++) {
                   19867:         my $start = $j*32;
                   19868:         my $cypherblock = substr($cyphertext,$start,32);
                   19869:         my $chunk =
                   19870:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   19871:         $chunk .=
                   19872:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   19873:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   19874:         $plaintext .= $chunk;
                   19875:     }
1.1174    raeburn  19876:     return $plaintext;
                   19877: }
                   19878: 
1.1344    raeburn  19879: sub get_requested_shorturls {
1.1309    raeburn  19880:     my ($cdom,$cnum,$navmap) = @_;
                   19881:     return unless (ref($navmap));
1.1344    raeburn  19882:     my ($numnew,$errors);
1.1309    raeburn  19883:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   19884:     if (@toshorten) {
                   19885:         my (%maps,%resources,%titles);
                   19886:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   19887:                                                                'shorturls',$cdom,$cnum);
                   19888:         if (keys(%resources)) {
1.1344    raeburn  19889:             my %tocreate;
1.1309    raeburn  19890:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   19891:                 my $symb = $resources{$item};
                   19892:                 if ($symb) {
                   19893:                     $tocreate{$cnum.'&'.$symb} = 1;
                   19894:                 }
                   19895:             }
1.1344    raeburn  19896:             if (keys(%tocreate)) {
                   19897:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   19898:                                                       \%tocreate);
                   19899:             }
1.1309    raeburn  19900:         }
1.1344    raeburn  19901:     }
                   19902:     return ($numnew,$errors);
                   19903: }
                   19904: 
                   19905: sub make_short_symbs {
                   19906:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   19907:     my ($numnew,@errors);
                   19908:     if (ref($tocreateref) eq 'HASH') {
                   19909:         my %tocreate = %{$tocreateref};
1.1309    raeburn  19910:         if (keys(%tocreate)) {
                   19911:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   19912:             my $su = Short::URL->new(no_vowels => 1);
                   19913:             my $init = '';
                   19914:             my (%newunique,%addcourse,%courseonly,%failed);
                   19915:             # get lock on tiny db
                   19916:             my $now = time;
1.1344    raeburn  19917:             if ($lockuser eq '') {
                   19918:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   19919:             }
1.1309    raeburn  19920:             my $lockhash = {
1.1344    raeburn  19921:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  19922:                             };
                   19923:             my $tries = 0;
                   19924:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19925:             my ($code,$error);
                   19926:             while (($gotlock ne 'ok') && ($tries<3)) {
                   19927:                 $tries ++;
                   19928:                 sleep 1;
1.1319    raeburn  19929:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  19930:             }
                   19931:             if ($gotlock eq 'ok') {
                   19932:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   19933:                                        \%addcourse,\%courseonly,\%failed);
                   19934:                 if (keys(%failed)) {
                   19935:                     my $numfailed = scalar(keys(%failed));
                   19936:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   19937:                 }
                   19938:                 if (keys(%newunique)) {
                   19939:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   19940:                     if ($putres eq 'ok') {
                   19941:                         $numnew = scalar(keys(%newunique));
                   19942:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   19943:                         unless ($newputres eq 'ok') {
                   19944:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   19945:                         }
                   19946:                     } else {
                   19947:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   19948:                     }
                   19949:                 }
                   19950:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   19951:                 unless ($dellockres eq 'ok') {
                   19952:                     push(@errors,&mt('error: could not release lockfile'));
                   19953:                 }
                   19954:             } else {
                   19955:                 push(@errors,&mt('error: could not obtain lockfile'));
                   19956:             }
                   19957:             if (keys(%courseonly)) {
                   19958:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19959:                 if ($result ne 'ok') {
                   19960:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19961:                 }
                   19962:             }
                   19963:         }
                   19964:     }
                   19965:     return ($numnew,\@errors);
                   19966: }
                   19967: 
                   19968: sub shorten_symbs {
                   19969:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19970:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19971:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19972:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19973:     my (%possibles,%collisions);
                   19974:     foreach my $key (keys(%{$tocreate})) {
                   19975:         my $num = String::CRC32::crc32($key);
                   19976:         my $tiny = $su->encode($num,$init);
                   19977:         if ($tiny) {
                   19978:             $possibles{$tiny} = $key;
                   19979:         }
                   19980:     }
                   19981:     if (!$init) {
                   19982:         $init = 1;
                   19983:     } else {
                   19984:         $init ++;
                   19985:     }
                   19986:     if (keys(%possibles)) {
                   19987:         my @posstiny = keys(%possibles);
                   19988:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19989:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19990:         if (keys(%currtiny)) {
                   19991:             foreach my $key (keys(%currtiny)) {
                   19992:                 next if ($currtiny{$key} eq '');
                   19993:                 if ($currtiny{$key} eq $possibles{$key}) {
                   19994:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19995:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19996:                         $courseonly->{$tsymb} = $key;
                   19997:                     }
                   19998:                 } else {
                   19999:                     $collisions{$possibles{$key}} = 1;
                   20000:                 }
                   20001:                 delete($possibles{$key});
                   20002:             }
                   20003:         }
                   20004:         foreach my $key (keys(%possibles)) {
                   20005:             $newunique->{$key} = $possibles{$key};
                   20006:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   20007:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   20008:                 $addcourse->{$tsymb} = $key;
                   20009:             }
                   20010:         }
                   20011:     }
                   20012:     if (keys(%collisions)) {
                   20013:         if ($init <5) {
                   20014:             if (!$init) {
                   20015:                 $init = 1;
                   20016:             } else {
                   20017:                 $init ++;
                   20018:             }
                   20019:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   20020:                                    $newunique,$addcourse,$courseonly,$failed);
                   20021:         } else {
                   20022:             foreach my $key (keys(%collisions)) {
                   20023:                 $failed->{$key} = 1;
                   20024:             }
                   20025:         }
                   20026:     }
                   20027:     return $init;
                   20028: }
                   20029: 
1.1328    raeburn  20030: sub is_nonframeable {
1.1329    raeburn  20031:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   20032:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  20033:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  20034: 
                   20035:     $remprotocol = lc($remprotocol);
                   20036:     $remhost = lc($remhost);
                   20037:     my $remport = 80;
                   20038:     if ($remprotocol eq 'https') {
                   20039:         $remport = 443;
                   20040:     }
1.1330    raeburn  20041:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  20042:     if ($cached) {
                   20043:         unless ($nocache) {
                   20044:             if ($result) {
                   20045:                 return 1;
                   20046:             } else {
                   20047:                 return 0;
                   20048:             }
                   20049:         }
                   20050:     }
1.1328    raeburn  20051:     my $uselink;
                   20052:     my $request = new HTTP::Request('HEAD',$url);
                   20053:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   20054:     if ($response->is_success()) {
                   20055:         my $secpolicy = lc($response->header('content-security-policy'));
                   20056:         my $xframeop = lc($response->header('x-frame-options'));
                   20057:         $secpolicy =~ s/^\s+|\s+$//g;
                   20058:         $xframeop =~ s/^\s+|\s+$//g;
                   20059:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  20060:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  20061:             my ($origin,$protocol,$port);
                   20062:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   20063:                 $port = $ENV{'SERVER_PORT'};
                   20064:             } else {
                   20065:                 $port = 80;
                   20066:             }
                   20067:             if ($absolute eq '') {
                   20068:                 $protocol = 'http:';
                   20069:                 if ($port == 443) {
                   20070:                     $protocol = 'https:';
                   20071:                 }
                   20072:                 $origin = $protocol.'//'.lc($hostname);
                   20073:             } else {
                   20074:                 $origin = lc($absolute);
                   20075:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   20076:             }
                   20077:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   20078:                 my $framepolicy = $1;
                   20079:                 $framepolicy =~ s/^\s+|\s+$//g;
                   20080:                 my @policies = split(/\s+/,$framepolicy);
                   20081:                 if (@policies) {
                   20082:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   20083:                         $uselink = 1;
                   20084:                     } else {
                   20085:                         $uselink = 1;
                   20086:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   20087:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   20088:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   20089:                             undef($uselink);
                   20090:                         }
                   20091:                         if ($uselink) {
                   20092:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   20093:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   20094:                                     undef($uselink);
                   20095:                                 }
                   20096:                             }
                   20097:                         }
                   20098:                         if ($uselink) {
                   20099:                             my @possok;
                   20100:                             if ($ip ne '') {
                   20101:                                 push(@possok,$ip);
                   20102:                             }
                   20103:                             my $hoststr = '';
                   20104:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   20105:                                 if ($hoststr eq '') {
                   20106:                                     $hoststr = $part;
                   20107:                                 } else {
                   20108:                                     $hoststr = "$part.$hoststr";
                   20109:                                 }
                   20110:                                 if ($hoststr eq $hostname) {
                   20111:                                     push(@possok,$hostname);
                   20112:                                 } else {
                   20113:                                     push(@possok,"*.$hoststr");
                   20114:                                 }
                   20115:                             }
                   20116:                             if (@possok) {
                   20117:                                 foreach my $poss (@possok) {
                   20118:                                     last if (!$uselink);
                   20119:                                     foreach my $policy (@policies) {
                   20120:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   20121:                                             undef($uselink);
                   20122:                                             last;
                   20123:                                         }
                   20124:                                     }
                   20125:                                 }
                   20126:                             }
                   20127:                         }
                   20128:                     }
                   20129:                 }
                   20130:             } elsif ($xframeop ne '') {
                   20131:                 $uselink = 1;
                   20132:                 my @policies = split(/\s*,\s*/,$xframeop);
                   20133:                 if (@policies) {
                   20134:                     unless (grep(/^deny$/,@policies)) {
                   20135:                         if ($origin ne '') {
                   20136:                             if (grep(/^sameorigin$/,@policies)) {
                   20137:                                 if ($remotehost eq $origin) {
                   20138:                                     undef($uselink);
                   20139:                                 }
                   20140:                             }
                   20141:                             if ($uselink) {
                   20142:                                 foreach my $policy (@policies) {
                   20143:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   20144:                                         my $allowfrom = $1;
                   20145:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   20146:                                             undef($uselink);
                   20147:                                             last;
                   20148:                                         }
                   20149:                                     }
                   20150:                                 }
                   20151:                             }
                   20152:                         }
                   20153:                     }
                   20154:                 }
                   20155:             }
                   20156:         }
                   20157:     }
1.1329    raeburn  20158:     if ($nocache) {
                   20159:         if ($cached) {
                   20160:             my $devalidate;
                   20161:             if ($uselink && !$result) {
                   20162:                 $devalidate = 1;
                   20163:             } elsif (!$uselink && $result) {
                   20164:                 $devalidate = 1;
                   20165:             }
                   20166:             if ($devalidate) {
                   20167:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   20168:             }
                   20169:         }
                   20170:     } else {
                   20171:         if ($uselink) {
                   20172:             $result = 1;
                   20173:         } else {
                   20174:             $result = 0;
                   20175:         }
                   20176:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   20177:     }
1.1328    raeburn  20178:     return $uselink;
                   20179: }
                   20180: 
1.1359    raeburn  20181: sub page_menu {
                   20182:     my ($menucolls,$menunum) = @_;
                   20183:     my %menu;
                   20184:     foreach my $item (split(/;/,$menucolls)) {
                   20185:         my ($num,$value) = split(/\%/,$item);
                   20186:         if ($num eq $menunum) {
                   20187:             my @entries = split(/\&/,$value);
                   20188:             foreach my $entry (@entries) {
                   20189:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  20190:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  20191:                     $menu{$name} = $fields;
                   20192:                 } else {
                   20193:                     my @shown;
                   20194:                     if ($fields =~ /,/) {
                   20195:                         @shown = split(/,/,$fields);
                   20196:                     } else {
                   20197:                         @shown = ($fields);
                   20198:                     }
                   20199:                     if (@shown) {
                   20200:                         foreach my $field (@shown) {
                   20201:                             next if ($field eq '');
                   20202:                             $menu{$field} = 1;
                   20203:                         }
                   20204:                     }
                   20205:                 }
                   20206:             }
                   20207:         }
                   20208:     }
                   20209:     return %menu;
                   20210: }
                   20211: 
1.112     bowersj2 20212: 1;
                   20213: __END__;
1.41      ng       20214: 

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