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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1459  ! raeburn     4: # $Id: loncommon.pm,v 1.1458 2025/02/20 01:09:33 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 {
1.1459  ! raeburn  1463:         return '&nbsp;<h1 class="LC_helpmenu">'.$text.'</h1>&nbsp;';
1.1168    raeburn  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.1459  ! raeburn  1475:     my $bannertitle = &mt('Help Menu');
        !          1476:     &js_escape(\$bannertitle);
        !          1477:     my $bodytitle = &mt('Documentation');
        !          1478:     &js_escape(\$bodytitle);
1.331     albertel 1479:     my $start_page =
                   1480:         &Apache::loncommon::start_page('Help Menu', undef,
                   1481: 				       {'frameset'    => 1,
                   1482: 					'js_ready'    => 1,
1.1154    raeburn  1483:                                         'use_absolute' => $httphost,
1.331     albertel 1484: 					'add_entries' => {
1.1168    raeburn  1485: 					    'border' => '0', 
1.579     raeburn  1486: 					    'rows'   => "110,*",},});
1.331     albertel 1487:     my $end_page =
                   1488:         &Apache::loncommon::end_page({'frameset' => 1,
                   1489: 				      'js_ready' => 1,});
1.436     albertel 1490:     my $template .= <<"ENDTEMPLATE";
                   1491: <script type="text/javascript">
1.877     bisitz   1492: // <![CDATA[
1.253     albertel 1493: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1494: var banner_link = '';
1.243     raeburn  1495: function helpMenu(target) {
                   1496:     var caller = this;
                   1497:     if (target == 'open') {
                   1498:         var newWindow = null;
                   1499:         try {
1.262     albertel 1500:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1501:         }
                   1502:         catch(error) {
                   1503:             writeHelp(caller);
                   1504:             return;
                   1505:         }
                   1506:         if (newWindow) {
                   1507:             caller = newWindow;
                   1508:         }
1.193     raeburn  1509:     }
1.243     raeburn  1510:     writeHelp(caller);
                   1511:     return;
                   1512: }
                   1513: function writeHelp(caller) {
1.1459  ! raeburn  1514:     caller.document.writeln('$start_page\\n<frame name="bannerframe" title="$bannertitle" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
        !          1515:     caller.document.writeln('<frame name="bodyframe" title="$bodytitle" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1.1168    raeburn  1516:     caller.document.close();
                   1517:     caller.focus();
1.193     raeburn  1518: }
1.877     bisitz   1519: // END LON-CAPA Internal -->
1.253     albertel 1520: // ]]>
1.436     albertel 1521: </script>
1.193     raeburn  1522: ENDTEMPLATE
                   1523:     return $template;
                   1524: }
                   1525: 
1.172     www      1526: sub help_open_bug {
                   1527:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1528:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1529:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1530:     $text = "" if (not defined $text);
                   1531: 	$stayOnPage=1;
1.184     albertel 1532:     $width = 600 if (not defined $width);
                   1533:     $height = 600 if (not defined $height);
1.172     www      1534: 
                   1535:     $topic=~s/\W+/\+/g;
                   1536:     my $link='';
                   1537:     my $template='';
1.379     albertel 1538:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1539: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1540:     if (!$stayOnPage)
                   1541:     {
                   1542: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1543:     }
                   1544:     else
                   1545:     {
                   1546: 	$link = $url;
                   1547:     }
1.1314    raeburn  1548: 
1.1382    raeburn  1549:     my $target = '_top';
                   1550:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1551:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1552:         $target = '_blank';
1.1378    raeburn  1553:     }
1.1382    raeburn  1554: 
1.172     www      1555:     # Add the text
                   1556:     if ($text ne "")
                   1557:     {
                   1558: 	$template .= 
                   1559:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1382    raeburn  1560:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1561:     }
                   1562: 
                   1563:     # Add the graphic
1.179     matthew  1564:     my $title = &mt('Report a Bug');
1.215     albertel 1565:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1566:     $template .= <<"ENDTEMPLATE";
1.1382    raeburn  1567:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1568: ENDTEMPLATE
                   1569:     if ($text ne '') { $template.='</td></tr></table>' };
                   1570:     return $template;
                   1571: 
                   1572: }
                   1573: 
                   1574: sub help_open_faq {
                   1575:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1576:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1577:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1578:     $text = "" if (not defined $text);
                   1579: 	$stayOnPage=1;
                   1580:     $width = 350 if (not defined $width);
                   1581:     $height = 400 if (not defined $height);
                   1582: 
                   1583:     $topic=~s/\W+/\+/g;
                   1584:     my $link='';
                   1585:     my $template='';
                   1586:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1587:     if (!$stayOnPage)
                   1588:     {
                   1589: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1590:     }
                   1591:     else
                   1592:     {
                   1593: 	$link = $url;
                   1594:     }
                   1595: 
                   1596:     # Add the text
                   1597:     if ($text ne "")
                   1598:     {
                   1599: 	$template .= 
1.173     www      1600:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1601:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1602:     }
                   1603: 
                   1604:     # Add the graphic
1.179     matthew  1605:     my $title = &mt('View the FAQ');
1.215     albertel 1606:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1607:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1608:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1609: ENDTEMPLATE
                   1610:     if ($text ne '') { $template.='</td></tr></table>' };
                   1611:     return $template;
                   1612: 
1.44      bowersj2 1613: }
1.37      matthew  1614: 
1.180     matthew  1615: ###############################################################
                   1616: ###############################################################
                   1617: 
1.45      matthew  1618: =pod
                   1619: 
1.648     raeburn  1620: =item * &change_content_javascript():
1.256     matthew  1621: 
                   1622: This and the next function allow you to create small sections of an
                   1623: otherwise static HTML page that you can update on the fly with
                   1624: Javascript, even in Netscape 4.
                   1625: 
                   1626: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1627: must be written to the HTML page once. It will prove the Javascript
                   1628: function "change(name, content)". Calling the change function with the
                   1629: name of the section 
                   1630: you want to update, matching the name passed to C<changable_area>, and
                   1631: the new content you want to put in there, will put the content into
                   1632: that area.
                   1633: 
                   1634: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1635: to contain room for the original contents. You need to "make space"
                   1636: for whatever changes you wish to make, and be B<sure> to check your
                   1637: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1638: it's adequate for updating a one-line status display, but little more.
                   1639: This script will set the space to 100% width, so you only need to
                   1640: worry about height in Netscape 4.
                   1641: 
                   1642: Modern browsers are much less limiting, and if you can commit to the
                   1643: user not using Netscape 4, this feature may be used freely with
                   1644: pretty much any HTML.
                   1645: 
                   1646: =cut
                   1647: 
                   1648: sub change_content_javascript {
                   1649:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1650:     if ($env{'browser.type'} eq 'netscape' &&
                   1651: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1652: 	return (<<NETSCAPE4);
                   1653: 	function change(name, content) {
                   1654: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1655: 	    doc.open();
                   1656: 	    doc.write(content);
                   1657: 	    doc.close();
                   1658: 	}
                   1659: NETSCAPE4
                   1660:     } else {
                   1661: 	# Otherwise, we need to use semi-standards-compliant code
                   1662: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1663: 	# is really scary, and every useful browser supports it
                   1664: 	return (<<DOMBASED);
                   1665: 	function change(name, content) {
                   1666: 	    element = document.getElementById(name);
                   1667: 	    element.innerHTML = content;
                   1668: 	}
                   1669: DOMBASED
                   1670:     }
                   1671: }
                   1672: 
                   1673: =pod
                   1674: 
1.648     raeburn  1675: =item * &changable_area($name,$origContent):
1.256     matthew  1676: 
                   1677: This provides a "changable area" that can be modified on the fly via
                   1678: the Javascript code provided in C<change_content_javascript>. $name is
                   1679: the name you will use to reference the area later; do not repeat the
                   1680: same name on a given HTML page more then once. $origContent is what
                   1681: the area will originally contain, which can be left blank.
                   1682: 
                   1683: =cut
                   1684: 
                   1685: sub changable_area {
                   1686:     my ($name, $origContent) = @_;
                   1687: 
1.258     albertel 1688:     if ($env{'browser.type'} eq 'netscape' &&
                   1689: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1690: 	# If this is netscape 4, we need to use the Layer tag
                   1691: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1692:     } else {
                   1693: 	return "<span id='$name'>$origContent</span>";
                   1694:     }
                   1695: }
                   1696: 
                   1697: =pod
                   1698: 
1.648     raeburn  1699: =item * &viewport_geometry_js 
1.590     raeburn  1700: 
                   1701: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1702: 
                   1703: =cut
                   1704: 
                   1705: 
                   1706: sub viewport_geometry_js { 
                   1707:     return <<"GEOMETRY";
                   1708: var Geometry = {};
                   1709: function init_geometry() {
                   1710:     if (Geometry.init) { return };
                   1711:     Geometry.init=1;
                   1712:     if (window.innerHeight) {
                   1713:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1714:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1715:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1716:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1717:     }
                   1718:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1719:         Geometry.getViewportHeight =
                   1720:             function() { return document.documentElement.clientHeight; };
                   1721:         Geometry.getViewportWidth =
                   1722:             function() { return document.documentElement.clientWidth; };
                   1723: 
                   1724:         Geometry.getHorizontalScroll =
                   1725:             function() { return document.documentElement.scrollLeft; };
                   1726:         Geometry.getVerticalScroll =
                   1727:             function() { return document.documentElement.scrollTop; };
                   1728:     }
                   1729:     else if (document.body.clientHeight) {
                   1730:         Geometry.getViewportHeight =
                   1731:             function() { return document.body.clientHeight; };
                   1732:         Geometry.getViewportWidth =
                   1733:             function() { return document.body.clientWidth; };
                   1734:         Geometry.getHorizontalScroll =
                   1735:             function() { return document.body.scrollLeft; };
                   1736:         Geometry.getVerticalScroll =
                   1737:             function() { return document.body.scrollTop; };
                   1738:     }
                   1739: }
                   1740: 
                   1741: GEOMETRY
                   1742: }
                   1743: 
                   1744: =pod
                   1745: 
1.648     raeburn  1746: =item * &viewport_size_js()
1.590     raeburn  1747: 
                   1748: 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. 
                   1749: 
                   1750: =cut
                   1751: 
                   1752: sub viewport_size_js {
                   1753:     my $geometry = &viewport_geometry_js();
                   1754:     return <<"DIMS";
                   1755: 
                   1756: $geometry
                   1757: 
                   1758: function getViewportDims(width,height) {
                   1759:     init_geometry();
                   1760:     width.value = Geometry.getViewportWidth();
                   1761:     height.value = Geometry.getViewportHeight();
                   1762:     return;
                   1763: }
                   1764: 
                   1765: DIMS
                   1766: }
                   1767: 
                   1768: =pod
                   1769: 
1.648     raeburn  1770: =item * &resize_textarea_js()
1.565     albertel 1771: 
                   1772: emits the needed javascript to resize a textarea to be as big as possible
                   1773: 
                   1774: creates a function resize_textrea that takes two IDs first should be
                   1775: the id of the element to resize, second should be the id of a div that
                   1776: surrounds everything that comes after the textarea, this routine needs
                   1777: to be attached to the <body> for the onload and onresize events.
                   1778: 
                   1779: =cut
                   1780: 
                   1781: sub resize_textarea_js {
1.590     raeburn  1782:     my $geometry = &viewport_geometry_js();
1.565     albertel 1783:     return <<"RESIZE";
                   1784:     <script type="text/javascript">
1.824     bisitz   1785: // <![CDATA[
1.590     raeburn  1786: $geometry
1.565     albertel 1787: 
1.588     albertel 1788: function getX(element) {
                   1789:     var x = 0;
                   1790:     while (element) {
                   1791: 	x += element.offsetLeft;
                   1792: 	element = element.offsetParent;
                   1793:     }
                   1794:     return x;
                   1795: }
                   1796: function getY(element) {
                   1797:     var y = 0;
                   1798:     while (element) {
                   1799: 	y += element.offsetTop;
                   1800: 	element = element.offsetParent;
                   1801:     }
                   1802:     return y;
                   1803: }
                   1804: 
                   1805: 
1.565     albertel 1806: function resize_textarea(textarea_id,bottom_id) {
                   1807:     init_geometry();
                   1808:     var textarea        = document.getElementById(textarea_id);
                   1809:     //alert(textarea);
                   1810: 
1.588     albertel 1811:     var textarea_top    = getY(textarea);
1.565     albertel 1812:     var textarea_height = textarea.offsetHeight;
                   1813:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1814:     var bottom_top      = getY(bottom);
1.565     albertel 1815:     var bottom_height   = bottom.offsetHeight;
                   1816:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1817:     var fudge           = 23;
1.565     albertel 1818:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1819:     if (new_height < 300) {
                   1820: 	new_height = 300;
                   1821:     }
                   1822:     textarea.style.height=new_height+'px';
                   1823: }
1.824     bisitz   1824: // ]]>
1.565     albertel 1825: </script>
                   1826: RESIZE
                   1827: 
                   1828: }
                   1829: 
1.1205    golterma 1830: sub colorfuleditor_js {
1.1248    raeburn  1831:     my $browse_or_search;
                   1832:     my $respath;
                   1833:     my ($cnum,$cdom) = &crsauthor_url();
                   1834:     if ($cnum) {
                   1835:         $respath = "/res/$cdom/$cnum/";
                   1836:         my %js_lt = &Apache::lonlocal::texthash(
                   1837:             sunm => 'Sub-directory name',
                   1838:             save => 'Save page to make this permanent',
                   1839:         );
                   1840:         &js_escape(\%js_lt);
1.1400    raeburn  1841:         my $showfile_js = &show_crsfiles_js();
1.1248    raeburn  1842:         $browse_or_search = <<"END";
                   1843: 
1.1400    raeburn  1844:     $showfile_js
                   1845: 
1.1248    raeburn  1846:     function toggleChooser(form,element,titleid,only,search) {
                   1847:         var disp = 'none';
                   1848:         if (document.getElementById('chooser_'+element)) {
                   1849:             var curr = document.getElementById('chooser_'+element).style.display;
                   1850:             if (curr == 'none') {
                   1851:                 disp='inline';
                   1852:                 if (form.elements['chooser_'+element].length) {
                   1853:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1854:                         form.elements['chooser_'+element][i].checked = false;
                   1855:                     }
                   1856:                 }
                   1857:                 toggleResImport(form,element);
                   1858:             }
                   1859:             document.getElementById('chooser_'+element).style.display = disp;
1.1400    raeburn  1860:             var dirsel = '';
                   1861:             var filesel = '';
                   1862:             if (document.getElementById('chooser_'+element+'_crsres')) {
                   1863:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1864:                 if (currcrsres == 'none') {
                   1865:                     dirsel = 'coursepath_'+element;
                   1866:                     var filesel = 'coursefile_'+element;
                   1867:                     var include;
                   1868:                     if (document.getElementById('crsres_include_'+element)) {
                   1869:                         include = document.getElementById('crsres_include_'+element).value;
                   1870:                     }
1.1402    raeburn  1871:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
1.1400    raeburn  1872:                 }
                   1873:             }
                   1874:             if (document.getElementById('chooser_'+element+'_upload')) {
                   1875:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
                   1876:                 if (currcrsupload == 'none') {
                   1877:                     dirsel = 'crsauthorpath_'+element;
                   1878:                     filesel = '';
1.1402    raeburn  1879:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
1.1400    raeburn  1880:                 }
                   1881:             }
1.1248    raeburn  1882:         }
                   1883:     }
                   1884: 
1.1400    raeburn  1885:     function toggleCrsFile(form,element) {
1.1248    raeburn  1886:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1887:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1888:             if (curr == 'none') {
1.1400    raeburn  1889:                 if (document.getElementById('coursepath_'+element)) {
                   1890:                     var numdirs;
                   1891:                     if (document.getElementById('coursepath_'+element).length) {
                   1892:                         numdirs = document.getElementById('coursepath_'+element).length;
                   1893:                     }
1.1402    raeburn  1894:                     if ((document.getElementById('hascrsres_'+element)) &&
                   1895:                         (document.getElementById('nocrsres_'+element))) {
                   1896:                         if (numdirs) {
                   1897:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
                   1898:                             document.getElementById('nocrsres_'+element).style.display='none';
                   1899:                         } else {
                   1900:                             document.getElementById('hascrsres_'+element).style.display='none';
                   1901:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
                   1902:                         }
                   1903:                     }
1.1248    raeburn  1904:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1905:                     if (numdirs > 1) {
1.1400    raeburn  1906:                         var selelem = form.elements['coursefile_'+element];
                   1907:                         var i, len = selelem.options.length -1;
                   1908:                         if (len >=0) {
                   1909:                             for (i = len; i >= 0; i--) {
                   1910:                                 selelem.remove(i);
                   1911:                             }
                   1912:                             selelem.options[0] = new Option('','');
                   1913:                         }
1.1248    raeburn  1914:                     }
                   1915:                 }
1.1400    raeburn  1916:             }
1.1248    raeburn  1917:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1918:         }
                   1919:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1920:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1921:             if (document.getElementById('uploadcrsres_'+element)) {
                   1922:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1923:             }
                   1924:         }
                   1925:         return;
                   1926:     }
                   1927: 
1.1400    raeburn  1928:     function toggleCrsUpload(form,element) {
1.1248    raeburn  1929:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1930:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1931:         }
                   1932:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1933:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1934:             if (curr == 'none') {
1.1400    raeburn  1935:                 form.elements['newsubdir_'+element][0].checked = true;
                   1936:                 toggleNewsubdir(form,element);
                   1937:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1938:                 if (document.getElementById('uploadcrsres_'+element)) {
                   1939:                     document.getElementById('uploadcrsres_'+element).value = '';
1.1248    raeburn  1940:                 }
                   1941:             }
                   1942:         }
                   1943:         return;
                   1944:     }
                   1945: 
                   1946:     function toggleResImport(form,element) {
                   1947:         var choices = new Array('crsres','upload');
                   1948:         for (var i=0; i<choices.length; i++) {
                   1949:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1950:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1951:             }
                   1952:         }
                   1953:     }
                   1954: 
                   1955:     function toggleNewsubdir(form,element) {
                   1956:         var newsub = form.elements['newsubdir_'+element];
                   1957:         if (newsub) {
                   1958:             if (newsub.length) {
                   1959:                 for (var j=0; j<newsub.length; j++) {
                   1960:                     if (newsub[j].checked) {
                   1961:                         if (document.getElementById('newsubdirname_'+element)) {
                   1962:                             if (newsub[j].value == '1') {
                   1963:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1964:                                 if (document.getElementById('newsubdir_'+element)) {
                   1965:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1966:                                 }
                   1967:                             } else {
                   1968:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1969:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1970:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1971:                             }
                   1972:                         }
                   1973:                         break; 
                   1974:                     }
                   1975:                 }
                   1976:             }
                   1977:         }
                   1978:     }
                   1979: 
                   1980:     function updateCrsFile(form,element) {
                   1981:         var directory = form.elements['coursepath_'+element];
                   1982:         var filename = form.elements['coursefile_'+element];
                   1983:         var path = directory.options[directory.selectedIndex].value;
                   1984:         var file = filename.options[filename.selectedIndex].value;
1.1400    raeburn  1985:         if (file != '') {
                   1986:             form.elements[element].value = '$respath';
                   1987:             if (path == '/') {
                   1988:                 form.elements[element].value += file;
                   1989:             } else {
                   1990:                 form.elements[element].value += path+'/'+file;
                   1991:             }
                   1992:             unClean();
                   1993:             if (document.getElementById('previewimg_'+element)) {
                   1994:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1995:                 var newsrc = document.getElementById('previewimg_'+element).src; 
                   1996:             }
                   1997:             if (document.getElementById('showimg_'+element)) {
                   1998:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1999:             }
1.1248    raeburn  2000:         }
                   2001:         toggleChooser(form,element);
                   2002:         return;
                   2003:     }
                   2004: 
                   2005:     function uploadDone(suffix,name) {
                   2006:         if (name) {
                   2007: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   2008:             unClean();
                   2009:             toggleChooser(document.forms["lonhomework"],suffix);
                   2010:         }
                   2011:     }
                   2012: 
                   2013: \$(document).ready(function(){
                   2014: 
                   2015:     \$(document).delegate('form :submit', 'click', function( event ) {
                   2016:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   2017:             var buttonId = this.id;
                   2018:             var suffix = buttonId.toString();
                   2019:             suffix = suffix.replace(/^crsupload_/,'');
                   2020:             event.preventDefault();
                   2021:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   2022:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   2023:             \$(this.form).submit();
                   2024:             document.lonhomework.target = '';
                   2025:             if (document.getElementById('crsuploadto_'+suffix)) {
                   2026:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   2027:             }
                   2028:             return false;
                   2029:         }
                   2030:     });
                   2031: });
                   2032: END
                   2033:     }
1.1205    golterma 2034:     return <<"COLORFULEDIT"
                   2035: <script type="text/javascript">
                   2036: // <![CDATA[>
                   2037:     function fold_box(curDepth, lastresource){
                   2038: 
                   2039:     // we need a list because there can be several blocks you need to fold in one tag
                   2040:         var block = document.getElementsByName('foldblock_'+curDepth);
                   2041:     // but there is only one folding button per tag
                   2042:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   2043: 
                   2044:         if(block.item(0).style.display == 'none'){
                   2045: 
                   2046:             foldbutton.value = '@{[&mt("Hide")]}';
                   2047:             for (i = 0; i < block.length; i++){
                   2048:                 block.item(i).style.display = '';
                   2049:             }
                   2050:         }else{
                   2051: 
                   2052:             foldbutton.value = '@{[&mt("Show")]}';
                   2053:             for (i = 0; i < block.length; i++){
                   2054:                 // block.item(i).style.visibility = 'collapse';
                   2055:                 block.item(i).style.display = 'none';
                   2056:             }
                   2057:         };
                   2058:         saveState(lastresource);
                   2059:     }
                   2060: 
                   2061:     function saveState (lastresource) {
                   2062: 
                   2063:         var tag_list = getTagList();
                   2064:         if(tag_list != null){
                   2065:             var timestamp = new Date().getTime();
                   2066:             var key = lastresource;
                   2067: 
                   2068:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   2069:             // starting with timestamp
                   2070:             var value = timestamp+';';
                   2071: 
                   2072:             // building the list of key-value pairs
                   2073:             for(var i = 0; i < tag_list.length; i++){
                   2074:                 value += tag_list[i]+',';
                   2075:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   2076:             }
                   2077: 
                   2078:             // only iterate whole storage if nothing to override
                   2079:             if(localStorage.getItem(key) == null){        
                   2080: 
                   2081:                 // prevent storage from growing large
                   2082:                 if(localStorage.length > 50){
                   2083:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2084:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2085:                     var oldest_key;
                   2086:                     
                   2087:                     for(var i = 1; i < localStorage.length; i++){
                   2088:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2089:                             oldest_key = localStorage.key(i);
                   2090:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2091:                         }
                   2092:                     }
                   2093:                     localStorage.removeItem(oldest_key);
                   2094:                 }
                   2095:             }
                   2096:             localStorage.setItem(key,value);
                   2097:         }
                   2098:     }
                   2099: 
                   2100:     // restore folding status of blocks (on page load)
                   2101:     function restoreState (lastresource) {
                   2102:         if(localStorage.getItem(lastresource) != null){
                   2103:             var key = lastresource;
                   2104:             var value = localStorage.getItem(key);
                   2105:             var regex_delTimestamp = /^\d+;/;
                   2106: 
                   2107:             value.replace(regex_delTimestamp, '');
                   2108: 
                   2109:             var valueArr = value.split(';');
                   2110:             var pairs;
                   2111:             var elements;
                   2112:             for (var i = 0; i < valueArr.length; i++){
                   2113:                 pairs = valueArr[i].split(',');
                   2114:                 elements = document.getElementsByName(pairs[0]);
                   2115: 
                   2116:                 for (var j = 0; j < elements.length; j++){  
                   2117:                     elements[j].style.display = pairs[1];
                   2118:                     if (pairs[1] == "none"){
                   2119:                         var regex_id = /([_\\d]+)\$/;
                   2120:                         regex_id.exec(pairs[0]);
                   2121:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2122:                     }
                   2123:                 }
                   2124:             }
                   2125:         }
                   2126:     }
                   2127: 
                   2128:     function getTagList () {
                   2129:         
                   2130:         var stringToSearch = document.lonhomework.innerHTML;
                   2131: 
                   2132:         var ret = new Array();
                   2133:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2134:         var tag_list = stringToSearch.match(regex_findBlock);
                   2135: 
                   2136:         if(tag_list != null){
                   2137:             for(var i = 0; i < tag_list.length; i++){            
                   2138:                 ret.push(tag_list[i].replace(/"/, ''));
                   2139:             }
                   2140:         }
                   2141:         return ret;
                   2142:     }
                   2143: 
                   2144:     function saveScrollPosition (resource) {
                   2145:         var tag_list = getTagList();
                   2146: 
                   2147:         // we dont always want to jump to the first block
                   2148:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2149:         if(\$(window).scrollTop() > 170){
                   2150:             if(tag_list != null){
                   2151:                 var result;
                   2152:                 for(var i = 0; i < tag_list.length; i++){
                   2153:                     if(isElementInViewport(tag_list[i])){
                   2154:                         result += tag_list[i]+';';
                   2155:                     }
                   2156:                 }
                   2157:                 sessionStorage.setItem('anchor_'+resource, result);
                   2158:             }
                   2159:         } else {
                   2160:             // we dont need to save zero, just delete the item to leave everything tidy
                   2161:             sessionStorage.removeItem('anchor_'+resource);
                   2162:         }
                   2163:     }
                   2164: 
                   2165:     function restoreScrollPosition(resource){
                   2166: 
                   2167:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2168:         if(elem != null){
                   2169:             var tag_list = elem.split(';');
                   2170:             var elem_list;
                   2171: 
                   2172:             for(var i = 0; i < tag_list.length; i++){
                   2173:                 elem_list = document.getElementsByName(tag_list[i]);
                   2174:                 
                   2175:                 if(elem_list.length > 0){
                   2176:                     elem = elem_list[0];
                   2177:                     break;
                   2178:                 }
                   2179:             }
                   2180:             elem.scrollIntoView();
                   2181:         }
                   2182:     }
                   2183: 
                   2184:     function isElementInViewport(el) {
                   2185: 
                   2186:         // change to last element instead of first
                   2187:         var elem = document.getElementsByName(el);
                   2188:         var rect = elem[0].getBoundingClientRect();
                   2189: 
                   2190:         return (
                   2191:             rect.top >= 0 &&
                   2192:             rect.left >= 0 &&
                   2193:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2194:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2195:         );
                   2196:     }
                   2197:     
                   2198:     function autosize(depth){
                   2199:         var cmInst = window['cm'+depth];
                   2200:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2201: 
                   2202:         // is fixed size, switching to dynamic
                   2203:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2204:             cmInst.setSize("","auto");
                   2205:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2206:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2207: 
                   2208:         // is dynamic size, switching to fixed
                   2209:         } else {
                   2210:             cmInst.setSize("","300px");
                   2211:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2212:             sessionStorage.removeItem("autosized_"+depth);
                   2213:         }
                   2214:     }
                   2215: 
1.1248    raeburn  2216: $browse_or_search
1.1205    golterma 2217: 
                   2218: // ]]>
                   2219: </script>
                   2220: COLORFULEDIT
                   2221: }
                   2222: 
                   2223: sub xmleditor_js {
                   2224:     return <<XMLEDIT
                   2225: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2226: <script type="text/javascript">
                   2227: // <![CDATA[>
                   2228: 
                   2229:     function saveScrollPosition (resource) {
                   2230: 
                   2231:         var scrollPos = \$(window).scrollTop();
                   2232:         sessionStorage.setItem(resource,scrollPos);
                   2233:     }
                   2234: 
                   2235:     function restoreScrollPosition(resource){
                   2236: 
                   2237:         var scrollPos = sessionStorage.getItem(resource);
                   2238:         \$(window).scrollTop(scrollPos);
                   2239:     }
                   2240: 
                   2241:     // unless internet explorer
                   2242:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2243: 
                   2244:         \$(document).ready(function() {
                   2245:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2246:         });
                   2247:     }
                   2248: 
                   2249:     // inserts text at cursor position into codemirror (xml editor only)
                   2250:     function insertText(text){
                   2251:         cm.focus();
                   2252:         var curPos = cm.getCursor();
                   2253:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2254:     }
                   2255: // ]]>
                   2256: </script>
                   2257: XMLEDIT
                   2258: }
                   2259: 
                   2260: sub insert_folding_button {
                   2261:     my $curDepth = $Apache::lonxml::curdepth;
                   2262:     my $lastresource = $env{'request.ambiguous'};
                   2263: 
                   2264:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2265:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2266: }
                   2267: 
1.1248    raeburn  2268: sub crsauthor_url {
                   2269:     my ($url) = @_;
                   2270:     if ($url eq '') {
                   2271:         $url = $ENV{'REQUEST_URI'};
                   2272:     }
                   2273:     my ($cnum,$cdom);
                   2274:     if ($env{'request.course.id'}) {
                   2275:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2276:         if ($audom ne '' && $auname ne '') {
                   2277:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2278:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2279:                 $cnum = $auname;
                   2280:                 $cdom = $audom;
                   2281:             }
                   2282:         }
                   2283:     }
                   2284:     return ($cnum,$cdom);
                   2285: }
                   2286: 
                   2287: sub import_crsauthor_form {
1.1400    raeburn  2288:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2289:     return (0) unless ($env{'request.course.id'});
                   2290:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2291:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2292:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2293:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2294:     my @ids=&Apache::lonnet::current_machine_ids();
1.1400    raeburn  2295:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
1.1402    raeburn  2296: 
1.1248    raeburn  2297:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2298:         $is_home = 1;
                   2299:     }
1.1400    raeburn  2300:     $toppath = "/priv/$cdom/$cnum";
                   2301:     my $nonemptydir = 1;
                   2302:     my $js_only;
                   2303:     if ($only) {
                   2304:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
                   2305:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
                   2306:     }
                   2307:     $exclude = &Apache::lonnet::priv_exclude();
1.1402    raeburn  2308:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
1.1400    raeburn  2309:     my $numdirs = scalar(keys(%files));
1.1248    raeburn  2310:     my %lt = &Apache::lonlocal::texthash (
                   2311:         fnam => 'Filename',
                   2312:         dire => 'Directory',
1.1400    raeburn  2313:         se   => 'Select',
1.1248    raeburn  2314:     );
1.1450    raeburn  2315:     $output = '<label>'.$lt{'dire'}.':&nbsp;'.
1.1400    raeburn  2316:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
1.1402    raeburn  2317:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
1.1400    raeburn  2318:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
1.1402    raeburn  2319:     if ($files{'/'}) {
                   2320:         $output .= '<option value="/">/</option>'."\n";
                   2321:     }
1.1400    raeburn  2322:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
1.1402    raeburn  2323:         next if ($key eq '/');
1.1400    raeburn  2324:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
                   2325:     }
1.1450    raeburn  2326:     $output .= '</select></label><br /><label>'."\n".
1.1402    raeburn  2327:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
1.1400    raeburn  2328:                '<option value="" selected="selected"></option>'."\n".
1.1450    raeburn  2329:                '</select></label>'."\n".
1.1402    raeburn  2330:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
1.1400    raeburn  2331:     return ($numdirs,$output);
                   2332: }
                   2333: 
                   2334: sub show_crsfiles_js {
                   2335:     my $excluderef = &Apache::lonnet::priv_exclude();
                   2336:     my $se = &js_escape(&mt('Select'));
                   2337:     my $exclude;
                   2338:     if (ref($excluderef) eq 'HASH') {
                   2339:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
                   2340:     }
                   2341:     my $js = <<"END";
                   2342: 
                   2343: 
1.1402    raeburn  2344:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
1.1400    raeburn  2345:         var relpath = '';
                   2346:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2347:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
                   2348:             if (currdir == '') {
                   2349:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2350:                     selelem = form.elements[filesel];
                   2351:                     var j, numfiles = selelem.options.length -1;
                   2352:                     if (numfiles >=0) {
                   2353:                         for (j = numfiles; j >= 0; j--) {
                   2354:                             selelem.remove(j);
                   2355:                         }
                   2356:                     }
                   2357:                     if (selelem.options.length == 0) {
                   2358:                         selelem.options[selelem.options.length] = new Option('','');
                   2359:                         selelem.selectedIndex = 0;
1.1248    raeburn  2360:                     }
                   2361:                 }
1.1400    raeburn  2362:                 return;
                   2363:             } else {
                   2364:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
1.1248    raeburn  2365:             }
                   2366:         }
1.1400    raeburn  2367:         var http = new XMLHttpRequest();
                   2368:         var url = "/adm/courseauthor";
                   2369:         var crsrole = "$env{'request.role'}";
                   2370:         var exclude = '';
                   2371:         if (exc) {
                   2372:             exclude = '$exclude';
                   2373:         }
1.1402    raeburn  2374:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
1.1400    raeburn  2375:         http.open("POST", url, true);
                   2376:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                   2377:         http.onreadystatechange = function() {
                   2378:             if (http.readyState == 4 && http.status == 200) {
                   2379:                 var data = JSON.parse(http.responseText);
                   2380:                 var selelem;
                   2381:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2382:                     if (Array.isArray(data.dirs)) {
                   2383:                         selelem = form.elements[dirsel];
                   2384:                         var i, numdirs = selelem.options.length -1;
                   2385:                         if (numdirs >=0) {
                   2386:                             for (i = numdirs; i >= 0; i--) {
                   2387:                                 selelem.remove(i);
                   2388:                             }
                   2389:                         }
                   2390:                         var len = data.dirs.length;
                   2391:                         if (len) {
1.1402    raeburn  2392:                             selelem.options[selelem.options.length] = new Option('$se','');
1.1400    raeburn  2393:                             var j;
                   2394:                             for (j = 0; j < len; j++) {
                   2395:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
                   2396:                             }
                   2397:                             selelem.selectedIndex = 0;
                   2398:                         }
                   2399:                         if (!setfile) {
                   2400:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2401:                                 selelem = form.elements[filesel];
                   2402:                                 var j, numfiles = selelem.options.length -1;
                   2403:                                 if (numfiles >=0) {
                   2404:                                     for (j = numfiles; j >= 0; j--) {
                   2405:                                         selelem.remove(j);
                   2406:                                     }
                   2407:                                 }
                   2408:                                 if (selelem.options.length == 0) {
                   2409:                                     selelem.options[selelem.options.length] = new Option('','');
                   2410:                                     selelem.selectedIndex = 0;
                   2411:                                 }
                   2412:                             }
                   2413:                         }
                   2414:                     }
                   2415:                 }
                   2416:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2417:                     selelem = form.elements[filesel];
                   2418:                     var i, numfiles = selelem.options.length -1;
                   2419:                     if (numfiles >=0) {
                   2420:                         for (i = numfiles; i >= 0; i--) {
                   2421:                             selelem.remove(i);
                   2422:                         }
                   2423:                     }
                   2424:                     var x;
                   2425:                     for (x in data.files) {
                   2426:                         if (Array.isArray(data.files[x])) {
                   2427:                             if (data.files[x].length > 1) {
                   2428:                                 selelem.options[selelem.options.length] = new Option('$se','');
                   2429:                             }
                   2430:                             var len = data.files[x].length;
                   2431:                             if (len) {
                   2432:                                 var k;
                   2433:                                 for (k = 0; k < len; k++) {
                   2434:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
                   2435:                                 }
                   2436:                                 selelem.selectedIndex = 0;
                   2437:                             }
                   2438:                         }
                   2439:                     }
                   2440:                     if (selelem.options.length == 0) {
                   2441:                         selelem.options[selelem.options.length] = new Option('','');
                   2442:                         selelem.selectedIndex = 0;
                   2443:                     }
1.1248    raeburn  2444:                 }
                   2445:             }
                   2446:         }
1.1400    raeburn  2447:         http.send(params);
1.1248    raeburn  2448:     }
1.1400    raeburn  2449: END
1.1248    raeburn  2450: }
                   2451: 
1.1426    raeburn  2452: sub crsauthor_rights {
                   2453:     my ($rightsfile,$path,$docroot,$cnum,$cdom) = @_;
                   2454:     my $sourcerights = "$path/$rightsfile";
                   2455:     my $now = time;
                   2456:     if (!-e $sourcerights) {
                   2457:         my $cid = $cdom.'_'.$cnum;
                   2458:         if (!-e "$docroot/priv/$cdom") {
                   2459:             mkdir("$docroot/priv/$cdom",0755);
                   2460:         }
                   2461:         if (!-e "$docroot/priv/$cdom/$cnum") {
                   2462:             mkdir("$docroot/priv/$cdom/$cnum",0755);
                   2463:         }
                   2464:         if (open(my $fh,">$sourcerights")) {
                   2465:             print $fh <<END;
                   2466: <accessrule effect="deny" realm="" type="course" role="" />
                   2467: <accessrule effect="allow" realm="$cid" type="course" role="" />
                   2468: END
                   2469:             close($fh);
                   2470:         }
                   2471:     }
                   2472:     if (!-e "$sourcerights.meta") {
                   2473:         if (open(my $fh,">$sourcerights.meta")) {
                   2474:             my $author=$env{'environment.firstname'}.' '.
                   2475:                        $env{'environment.middlename'}.' '.
                   2476:                        $env{'environment.lastname'}.' '.
                   2477:                        $env{'environment.generation'};
                   2478:             $author =~ s/\s+$//;
                   2479:             print $fh <<"END";
                   2480: 
                   2481: <abstract></abstract>
                   2482: <author>$author</author>
                   2483: <authorspace>$cnum:$cdom</authorspace>
                   2484: <copyright>private</copyright>
                   2485: <creationdate>$now</creationdate>
                   2486: <customdistributionfile></customdistributionfile>
                   2487: <dependencies></dependencies>
                   2488: <domain>$cdom</domain>
                   2489: <highestgradelevel>0</highestgradelevel>
                   2490: <keywords></keywords>
1.1445    raeburn  2491: <language>notset</language>
1.1426    raeburn  2492: <lastrevisiondate>$now</lastrevisiondate>
                   2493: <lowestgradelevel>0</lowestgradelevel>
                   2494: <mime>rights</mime>
                   2495: <modifyinguser>$env{'user.name'}:$env{'user.domain'}</modifyinguser>
                   2496: <notes></notes>
                   2497: <obsolete></obsolete>
                   2498: <obsoletereplacement></obsoletereplacement>
                   2499: <owner>$cnum:$cdom</owner>
                   2500: <rule>deny:::course,allow:$cid::course</rule>
                   2501: <sourceavail></sourceavail>
                   2502: <standards></standards>
                   2503: <subject></subject>
                   2504: <title>Course Authoring Rights</title>
                   2505: END
                   2506:             close($fh);
                   2507:         }
                   2508:     }
                   2509:     return;
                   2510: }
                   2511: 
1.565     albertel 2512: =pod
                   2513: 
1.1420    raeburn  2514: =item * &iframe_wrapper_headjs()
                   2515: 
1.1425    raeburn  2516: emits javascript containing two global vars to facilitate handling of resizing
                   2517: by code in iframe_wrapper_resizejs() used when an iframe is present in a page
                   2518: with standard LON-CAPA menus.
                   2519: 
                   2520: =cut
                   2521: 
1.1420    raeburn  2522: #
                   2523: # Where iframe is in use, if window.onload() executes before the custom resize function
                   2524: # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
                   2525: # are used to ensure document.ready() triggers a call to resize, so the iframe contents
                   2526: # do not obscure the Functions menu.
                   2527: #
                   2528: 
                   2529: sub iframe_wrapper_headjs {
                   2530:     return <<"ENDJS";
                   2531: <script type="text/javascript">
                   2532: // <![CDATA[
                   2533: var LCnotready = 0;
                   2534: var LCresizedef = 0;
                   2535: // ]]>
                   2536: </script>
                   2537: 
                   2538: ENDJS
                   2539: 
                   2540: }
                   2541: 
                   2542: =pod
                   2543: 
                   2544: =item * &iframe_wrapper_resizejs()
                   2545: 
1.1425    raeburn  2546: emits javascript used to handle resizing for a page containing
                   2547: an iframe, to ensure that the iframe does not obscure any
                   2548: standard LON-CAPA menu items.
                   2549: 
                   2550: =back
                   2551: 
                   2552: =cut
                   2553: 
1.1420    raeburn  2554: #
                   2555: # jQuery to use when iframe is in use and a page resize occurs.
                   2556: # This script will ensure that the iframe does not obscure any
                   2557: # standard LON-CAPA inline menus (primary, secondary, and/or
                   2558: # breadcrumbs and Functions menus. Expects javascript from
                   2559: # &iframe_wrapper_headjs() to be in head portion of the web page,
                   2560: # e.g., by inclusion in second arg passed to &start_page().
                   2561: #
                   2562: 
                   2563: sub iframe_wrapper_resizejs {
                   2564:     my $offset = 5;
                   2565:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
                   2566:     if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
                   2567:         $offset = 0;
                   2568:     }
                   2569:     return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
                   2570:     \$(document).ready( function() {
                   2571:         \$(window).unbind('resize').resize(function(){
                   2572:             var header = null;
                   2573:             var offset = $offset;
                   2574:             var height = 0;
                   2575:             var hdrtop = 0;
1.1421    raeburn  2576:             if (\$('div.LC_menus_content:first').length) {
                   2577:                 if (\$('div.LC_menus_content:first').hasClass ("shown")) {
                   2578:                     header = \$('div.LC_menus_content:first');
1.1423    raeburn  2579:                     offset = 12;
1.1421    raeburn  2580:                 }
                   2581:             } else if (\$('div.LC_head_subbox:first').length) {
1.1420    raeburn  2582:                 header = \$('div.LC_head_subbox:first');
                   2583:                 offset = 9;
                   2584:             } else {
                   2585:                 if (\$('#LC_breadcrumbs').length) {
                   2586:                     header = \$('#LC_breadcrumbs');
                   2587:                 }
                   2588:             }
                   2589:             if (header != null && header.length) {
                   2590:                 height = header.height();
                   2591:                 hdrtop = header.position().top;
                   2592:             }
                   2593:             var pos = height + hdrtop + offset;
                   2594:             \$('.LC_iframecontainer').css('top', pos);
                   2595:         });
                   2596:         LCresizedef = 1;
                   2597:         if (LCnotready == 1) {
                   2598:             LCnotready = 0;
                   2599:             \$(window).trigger('resize');
                   2600:         }
                   2601:     });
                   2602:     window.onload = function(){
                   2603:          if (LCresizedef) {
                   2604:              LCnotready = 0;
                   2605:              \$(window).trigger('resize');
                   2606:          } else {
                   2607:              LCnotready = 1;
                   2608:          }
                   2609:     };
                   2610: SCRIPT
                   2611: 
                   2612: }
                   2613: 
                   2614: =pod
                   2615: 
1.256     matthew  2616: =head1 Excel and CSV file utility routines
                   2617: 
                   2618: =cut
                   2619: 
                   2620: ###############################################################
                   2621: ###############################################################
                   2622: 
                   2623: =pod
                   2624: 
1.1162    raeburn  2625: =over 4
                   2626: 
1.648     raeburn  2627: =item * &csv_translate($text) 
1.37      matthew  2628: 
1.185     www      2629: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2630: format.
                   2631: 
                   2632: =cut
                   2633: 
1.180     matthew  2634: ###############################################################
                   2635: ###############################################################
1.37      matthew  2636: sub csv_translate {
                   2637:     my $text = shift;
                   2638:     $text =~ s/\"/\"\"/g;
1.209     albertel 2639:     $text =~ s/\n/ /g;
1.37      matthew  2640:     return $text;
                   2641: }
1.180     matthew  2642: 
                   2643: ###############################################################
                   2644: ###############################################################
                   2645: 
                   2646: =pod
                   2647: 
1.648     raeburn  2648: =item * &define_excel_formats()
1.180     matthew  2649: 
                   2650: Define some commonly used Excel cell formats.
                   2651: 
                   2652: Currently supported formats:
                   2653: 
                   2654: =over 4
                   2655: 
                   2656: =item header
                   2657: 
                   2658: =item bold
                   2659: 
                   2660: =item h1
                   2661: 
                   2662: =item h2
                   2663: 
                   2664: =item h3
                   2665: 
1.256     matthew  2666: =item h4
                   2667: 
                   2668: =item i
                   2669: 
1.180     matthew  2670: =item date
                   2671: 
                   2672: =back
                   2673: 
                   2674: Inputs: $workbook
                   2675: 
                   2676: Returns: $format, a hash reference.
                   2677: 
1.1057    foxr     2678: 
1.180     matthew  2679: =cut
                   2680: 
                   2681: ###############################################################
                   2682: ###############################################################
                   2683: sub define_excel_formats {
                   2684:     my ($workbook) = @_;
                   2685:     my $format;
                   2686:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2687:                                                 bottom    => 1,
                   2688:                                                 align     => 'center');
                   2689:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2690:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2691:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2692:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2693:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2694:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2695:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2696:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2697:     return $format;
                   2698: }
                   2699: 
                   2700: ###############################################################
                   2701: ###############################################################
1.113     bowersj2 2702: 
                   2703: =pod
                   2704: 
1.648     raeburn  2705: =item * &create_workbook()
1.255     matthew  2706: 
                   2707: Create an Excel worksheet.  If it fails, output message on the
                   2708: request object and return undefs.
                   2709: 
                   2710: Inputs: Apache request object
                   2711: 
                   2712: Returns (undef) on failure, 
                   2713:     Excel worksheet object, scalar with filename, and formats 
                   2714:     from &Apache::loncommon::define_excel_formats on success
                   2715: 
                   2716: =cut
                   2717: 
                   2718: ###############################################################
                   2719: ###############################################################
                   2720: sub create_workbook {
                   2721:     my ($r) = @_;
                   2722:         #
                   2723:     # Create the excel spreadsheet
                   2724:     my $filename = '/prtspool/'.
1.258     albertel 2725:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2726:         time.'_'.rand(1000000000).'.xls';
                   2727:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2728:     if (! defined($workbook)) {
                   2729:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2730:         $r->print(
                   2731:             '<p class="LC_error">'
                   2732:            .&mt('Problems occurred in creating the new Excel file.')
                   2733:            .' '.&mt('This error has been logged.')
                   2734:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2735:            .'</p>'
                   2736:         );
1.255     matthew  2737:         return (undef);
                   2738:     }
                   2739:     #
1.1014    foxr     2740:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2741:     #
                   2742:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2743:     return ($workbook,$filename,$format);
                   2744: }
                   2745: 
                   2746: ###############################################################
                   2747: ###############################################################
                   2748: 
                   2749: =pod
                   2750: 
1.648     raeburn  2751: =item * &create_text_file()
1.113     bowersj2 2752: 
1.542     raeburn  2753: Create a file to write to and eventually make available to the user.
1.256     matthew  2754: If file creation fails, outputs an error message on the request object and 
                   2755: return undefs.
1.113     bowersj2 2756: 
1.256     matthew  2757: Inputs: Apache request object, and file suffix
1.113     bowersj2 2758: 
1.256     matthew  2759: Returns (undef) on failure, 
                   2760:     Filehandle and filename on success.
1.113     bowersj2 2761: 
                   2762: =cut
                   2763: 
1.256     matthew  2764: ###############################################################
                   2765: ###############################################################
                   2766: sub create_text_file {
                   2767:     my ($r,$suffix) = @_;
                   2768:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2769:     my $fh;
                   2770:     my $filename = '/prtspool/'.
1.258     albertel 2771:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2772:         time.'_'.rand(1000000000).'.'.$suffix;
                   2773:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2774:     if (! defined($fh)) {
                   2775:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2776:         $r->print(
                   2777:             '<p class="LC_error">'
                   2778:            .&mt('Problems occurred in creating the output file.')
                   2779:            .' '.&mt('This error has been logged.')
                   2780:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2781:            .'</p>'
                   2782:         );
1.113     bowersj2 2783:     }
1.256     matthew  2784:     return ($fh,$filename)
1.113     bowersj2 2785: }
                   2786: 
                   2787: 
1.256     matthew  2788: =pod 
1.113     bowersj2 2789: 
                   2790: =back
                   2791: 
                   2792: =cut
1.37      matthew  2793: 
                   2794: ###############################################################
1.33      matthew  2795: ##        Home server <option> list generating code          ##
                   2796: ###############################################################
1.35      matthew  2797: 
1.169     www      2798: # ------------------------------------------
                   2799: 
                   2800: sub domain_select {
1.1289    raeburn  2801:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2802:     my @possdoms;
                   2803:     if (ref($incdoms) eq 'ARRAY') {
                   2804:         @possdoms = @{$incdoms};
                   2805:     } else {
                   2806:         @possdoms = &Apache::lonnet::all_domains();
                   2807:     }
                   2808: 
1.169     www      2809:     my %domains=map { 
1.514     albertel 2810: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2811:     } @possdoms;
                   2812: 
                   2813:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2814:         foreach my $dom (@{$excdoms}) {
                   2815:             delete($domains{$dom});
                   2816:         }
                   2817:     }
                   2818: 
1.169     www      2819:     if ($multiple) {
                   2820: 	$domains{''}=&mt('Any domain');
1.550     albertel 2821: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2822: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2823:     } else {
1.550     albertel 2824: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2825: 	return &select_form($name,$value,\%domains);
1.169     www      2826:     }
                   2827: }
                   2828: 
1.282     albertel 2829: #-------------------------------------------
                   2830: 
                   2831: =pod
                   2832: 
1.519     raeburn  2833: =head1 Routines for form select boxes
                   2834: 
                   2835: =over 4
                   2836: 
1.648     raeburn  2837: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2838: 
                   2839: Returns a string containing a <select> element int multiple mode
                   2840: 
                   2841: 
                   2842: Args:
                   2843:   $name - name of the <select> element
1.506     raeburn  2844:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2845:   $size - number of rows long the select element is
1.283     albertel 2846:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2847:           (shown text should already have been &mt())
1.506     raeburn  2848:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2849: 
1.282     albertel 2850: =cut
                   2851: 
                   2852: #-------------------------------------------
1.169     www      2853: sub multiple_select_form {
1.284     albertel 2854:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2855:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2856:     my $output='';
1.191     matthew  2857:     if (! defined($size)) {
                   2858:         $size = 4;
1.283     albertel 2859:         if (scalar(keys(%$hash))<4) {
                   2860:             $size = scalar(keys(%$hash));
1.191     matthew  2861:         }
                   2862:     }
1.734     bisitz   2863:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2864:     my @order;
1.506     raeburn  2865:     if (ref($order) eq 'ARRAY')  {
                   2866:         @order = @{$order};
                   2867:     } else {
                   2868:         @order = sort(keys(%$hash));
1.501     banghart 2869:     }
                   2870:     if (exists($$hash{'select_form_order'})) {
                   2871:         @order = @{$$hash{'select_form_order'}};
                   2872:     }
                   2873:         
1.284     albertel 2874:     foreach my $key (@order) {
1.356     albertel 2875:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2876:         $output.='selected="selected" ' if ($selected{$key});
                   2877:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2878:     }
                   2879:     $output.="</select>\n";
                   2880:     return $output;
                   2881: }
                   2882: 
1.88      www      2883: #-------------------------------------------
                   2884: 
                   2885: =pod
                   2886: 
1.1254    raeburn  2887: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2888: 
                   2889: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2890: allow a user to select options from a ref to a hash containing:
                   2891: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2892: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2893: An optional arg -- $readonly -- if true will cause the select form
                   2894: to be disabled, e.g., for the case where an instructor has a section-
                   2895: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2896: 
1.88      www      2897: See lonrights.pm for an example invocation and use.
                   2898: 
                   2899: =cut
                   2900: 
                   2901: #-------------------------------------------
                   2902: sub select_form {
1.1228    raeburn  2903:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2904:     return unless (ref($hashref) eq 'HASH');
                   2905:     if ($onchange) {
                   2906:         $onchange = ' onchange="'.$onchange.'"';
                   2907:     }
1.1228    raeburn  2908:     my $disabled;
                   2909:     if ($readonly) {
                   2910:         $disabled = ' disabled="disabled"';
                   2911:     }
                   2912:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2913:     my @keys;
1.970     raeburn  2914:     if (exists($hashref->{'select_form_order'})) {
                   2915: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2916:     } else {
1.970     raeburn  2917: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2918:     }
1.356     albertel 2919:     foreach my $key (@keys) {
                   2920:         $selectform.=
                   2921: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2922:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2923:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2924:     }
                   2925:     $selectform.="</select>";
                   2926:     return $selectform;
                   2927: }
                   2928: 
1.475     www      2929: # For display filters
                   2930: 
                   2931: sub display_filter {
1.1074    raeburn  2932:     my ($context) = @_;
1.475     www      2933:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2934:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2935:     my $phraseinput = 'hidden';
                   2936:     my $includeinput = 'hidden';
                   2937:     my ($checked,$includetypestext);
                   2938:     if ($env{'form.displayfilter'} eq 'containing') {
                   2939:         $phraseinput = 'text'; 
                   2940:         if ($context eq 'parmslog') {
                   2941:             $includeinput = 'checkbox';
                   2942:             if ($env{'form.includetypes'}) {
                   2943:                 $checked = ' checked="checked"';
                   2944:             }
                   2945:             $includetypestext = &mt('Include parameter types');
                   2946:         }
                   2947:     } else {
                   2948:         $includetypestext = '&nbsp;';
                   2949:     }
                   2950:     my ($additional,$secondid,$thirdid);
                   2951:     if ($context eq 'parmslog') {
                   2952:         $additional = 
                   2953:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2954:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2955:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2956:             '</label>';
                   2957:         $secondid = 'includetypes';
                   2958:         $thirdid = 'includetypestext';
                   2959:     }
                   2960:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2961:                                                     '$secondid','$thirdid')";
                   2962:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.1403    raeburn  2963: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
1.475     www      2964: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2965: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2966:            &mt('Filter: [_1]',
1.477     www      2967: 	   &select_form($env{'form.displayfilter'},
                   2968: 			'displayfilter',
1.970     raeburn  2969: 			{'currentfolder' => 'Current folder/page',
1.477     www      2970: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2971: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2972: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2973:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2974:                          '" />'.$additional;
                   2975: }
                   2976: 
                   2977: sub display_filter_js {
                   2978:     my $includetext = &mt('Include parameter types');
                   2979:     return <<"ENDJS";
                   2980:   
                   2981: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2982:     var firstType = 'hidden';
                   2983:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2984:         firstType = 'text';
                   2985:     }
                   2986:     firstObject = document.getElementById(firstid);
                   2987:     if (typeof(firstObject) == 'object') {
                   2988:         if (firstObject.type != firstType) {
                   2989:             changeInputType(firstObject,firstType);
                   2990:         }
                   2991:     }
                   2992:     if (context == 'parmslog') {
                   2993:         var secondType = 'hidden';
                   2994:         if (firstType == 'text') {
                   2995:             secondType = 'checkbox';
                   2996:         }
                   2997:         secondObject = document.getElementById(secondid);  
                   2998:         if (typeof(secondObject) == 'object') {
                   2999:             if (secondObject.type != secondType) {
                   3000:                 changeInputType(secondObject,secondType);
                   3001:             }
                   3002:         }
                   3003:         var textItem = document.getElementById(thirdid);
                   3004:         var currtext = textItem.innerHTML;
                   3005:         var newtext;
                   3006:         if (firstType == 'text') {
                   3007:             newtext = '$includetext';
                   3008:         } else {
                   3009:             newtext = '&nbsp;';
                   3010:         }
                   3011:         if (currtext != newtext) {
                   3012:             textItem.innerHTML = newtext;
                   3013:         }
                   3014:     }
                   3015:     return;
                   3016: }
                   3017: 
                   3018: function changeInputType(oldObject,newType) {
                   3019:     var newObject = document.createElement('input');
                   3020:     newObject.type = newType;
                   3021:     if (oldObject.size) {
                   3022:         newObject.size = oldObject.size;
                   3023:     }
                   3024:     if (oldObject.value) {
                   3025:         newObject.value = oldObject.value;
                   3026:     }
                   3027:     if (oldObject.name) {
                   3028:         newObject.name = oldObject.name;
                   3029:     }
                   3030:     if (oldObject.id) {
                   3031:         newObject.id = oldObject.id;
                   3032:     }
                   3033:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   3034:     return;
                   3035: }
                   3036: 
                   3037: ENDJS
1.475     www      3038: }
                   3039: 
1.167     www      3040: sub gradeleveldescription {
                   3041:     my $gradelevel=shift;
                   3042:     my %gradelevels=(0 => 'Not specified',
                   3043: 		     1 => 'Grade 1',
                   3044: 		     2 => 'Grade 2',
                   3045: 		     3 => 'Grade 3',
                   3046: 		     4 => 'Grade 4',
                   3047: 		     5 => 'Grade 5',
                   3048: 		     6 => 'Grade 6',
                   3049: 		     7 => 'Grade 7',
                   3050: 		     8 => 'Grade 8',
                   3051: 		     9 => 'Grade 9',
                   3052: 		     10 => 'Grade 10',
                   3053: 		     11 => 'Grade 11',
                   3054: 		     12 => 'Grade 12',
                   3055: 		     13 => 'Grade 13',
                   3056: 		     14 => '100 Level',
                   3057: 		     15 => '200 Level',
                   3058: 		     16 => '300 Level',
                   3059: 		     17 => '400 Level',
                   3060: 		     18 => 'Graduate Level');
                   3061:     return &mt($gradelevels{$gradelevel});
                   3062: }
                   3063: 
1.163     www      3064: sub select_level_form {
                   3065:     my ($deflevel,$name)=@_;
                   3066:     unless ($deflevel) { $deflevel=0; }
1.167     www      3067:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   3068:     for (my $i=0; $i<=18; $i++) {
                   3069:         $selectform.="<option value=\"$i\" ".
1.253     albertel 3070:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      3071:                 ">".&gradeleveldescription($i)."</option>\n";
                   3072:     }
                   3073:     $selectform.="</select>";
                   3074:     return $selectform;
1.163     www      3075: }
1.167     www      3076: 
1.35      matthew  3077: #-------------------------------------------
                   3078: 
1.45      matthew  3079: =pod
                   3080: 
1.1453    raeburn  3081: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled,$id)
1.35      matthew  3082: 
                   3083: Returns a string containing a <select name='$name' size='1'> form to 
                   3084: allow a user to select the domain to preform an operation in.  
                   3085: See loncreateuser.pm for an example invocation and use.
                   3086: 
1.90      www      3087: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   3088: selected");
                   3089: 
1.743     raeburn  3090: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   3091: 
1.910     raeburn  3092: 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.
                   3093: 
1.1121    raeburn  3094: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   3095: 
                   3096: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  3097: 
1.1256    raeburn  3098: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   3099: 
1.1453    raeburn  3100: The option $id argument is the value (if any) to set as the (unique) id attribute for the select tag.
                   3101: 
1.35      matthew  3102: =cut
                   3103: 
                   3104: #-------------------------------------------
1.34      matthew  3105: sub select_dom_form {
1.1453    raeburn  3106:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled,$id) = @_;
1.872     raeburn  3107:     if ($onchange) {
1.874     raeburn  3108:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  3109:     }
1.1256    raeburn  3110:     if ($disabled) {
                   3111:         $disabled = ' disabled="disabled"';
                   3112:     }
1.1453    raeburn  3113:     if ($id ne '') {
                   3114:         $id = ' id="'.$id.'"';
                   3115:     }
1.1121    raeburn  3116:     my (@domains,%exclude);
1.910     raeburn  3117:     if (ref($incdoms) eq 'ARRAY') {
                   3118:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   3119:     } else {
                   3120:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   3121:     }
1.90      www      3122:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  3123:     if (ref($excdoms) eq 'ARRAY') {
                   3124:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   3125:     }
1.1453    raeburn  3126:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled$id>\n";
1.356     albertel 3127:     foreach my $dom (@domains) {
1.1121    raeburn  3128:         next if ($exclude{$dom});
1.356     albertel 3129:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  3130:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   3131:         if ($showdomdesc) {
                   3132:             if ($dom ne '') {
                   3133:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   3134:                 if ($domdesc ne '') {
                   3135:                     $selectdomain .= ' ('.$domdesc.')';
                   3136:                 }
                   3137:             } 
                   3138:         }
                   3139:         $selectdomain .= "</option>\n";
1.34      matthew  3140:     }
                   3141:     $selectdomain.="</select>";
                   3142:     return $selectdomain;
                   3143: }
                   3144: 
1.35      matthew  3145: #-------------------------------------------
                   3146: 
1.45      matthew  3147: =pod
                   3148: 
1.648     raeburn  3149: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  3150: 
1.586     raeburn  3151: input: 4 arguments (two required, two optional) - 
                   3152:     $domain - domain of new user
                   3153:     $name - name of form element
                   3154:     $default - Value of 'default' causes a default item to be first 
                   3155:                             option, and selected by default. 
                   3156:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   3157:                             if 1 server found, or default, if 0 found.
1.594     raeburn  3158: output: returns 2 items: 
1.586     raeburn  3159: (a) form element which contains either:
                   3160:    (i) <select name="$name">
                   3161:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   3162:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   3163:        </select>
                   3164:        form item if there are multiple library servers in $domain, or
                   3165:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   3166:        if there is only one library server in $domain.
                   3167: 
                   3168: (b) number of library servers found.
                   3169: 
                   3170: See loncreateuser.pm for example of use.
1.35      matthew  3171: 
                   3172: =cut
                   3173: 
                   3174: #-------------------------------------------
1.586     raeburn  3175: sub home_server_form_item {
                   3176:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 3177:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  3178:     my $result;
                   3179:     my $numlib = keys(%servers);
                   3180:     if ($numlib > 1) {
                   3181:         $result .= '<select name="'.$name.'" />'."\n";
                   3182:         if ($default) {
1.804     bisitz   3183:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  3184:                        '</option>'."\n";
                   3185:         }
                   3186:         foreach my $hostid (sort(keys(%servers))) {
                   3187:             $result.= '<option value="'.$hostid.'">'.
                   3188: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   3189:         }
                   3190:         $result .= '</select>'."\n";
                   3191:     } elsif ($numlib == 1) {
                   3192:         my $hostid;
                   3193:         foreach my $item (keys(%servers)) {
                   3194:             $hostid = $item;
                   3195:         }
                   3196:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   3197:                    $hostid.'" />';
                   3198:                    if (!$hide) {
                   3199:                        $result .= $hostid.' '.$servers{$hostid};
                   3200:                    }
                   3201:                    $result .= "\n";
                   3202:     } elsif ($default) {
                   3203:         $result .= '<input type="hidden" name="'.$name.
                   3204:                    '" value="default" />';
                   3205:                    if (!$hide) {
                   3206:                        $result .= &mt('default');
                   3207:                    }
                   3208:                    $result .= "\n";
1.33      matthew  3209:     }
1.586     raeburn  3210:     return ($result,$numlib);
1.33      matthew  3211: }
1.112     bowersj2 3212: 
                   3213: =pod
                   3214: 
1.534     albertel 3215: =back 
                   3216: 
1.112     bowersj2 3217: =cut
1.87      matthew  3218: 
                   3219: ###############################################################
1.112     bowersj2 3220: ##                  Decoding User Agent                      ##
1.87      matthew  3221: ###############################################################
                   3222: 
                   3223: =pod
                   3224: 
1.112     bowersj2 3225: =head1 Decoding the User Agent
                   3226: 
                   3227: =over 4
                   3228: 
                   3229: =item * &decode_user_agent()
1.87      matthew  3230: 
                   3231: Inputs: $r
                   3232: 
                   3233: Outputs:
                   3234: 
                   3235: =over 4
                   3236: 
1.112     bowersj2 3237: =item * $httpbrowser
1.87      matthew  3238: 
1.112     bowersj2 3239: =item * $clientbrowser
1.87      matthew  3240: 
1.112     bowersj2 3241: =item * $clientversion
1.87      matthew  3242: 
1.112     bowersj2 3243: =item * $clientmathml
1.87      matthew  3244: 
1.112     bowersj2 3245: =item * $clientunicode
1.87      matthew  3246: 
1.112     bowersj2 3247: =item * $clientos
1.87      matthew  3248: 
1.1137    raeburn  3249: =item * $clientmobile
                   3250: 
1.1141    raeburn  3251: =item * $clientinfo
                   3252: 
1.1194    raeburn  3253: =item * $clientosversion
                   3254: 
1.87      matthew  3255: =back
                   3256: 
1.157     matthew  3257: =back 
                   3258: 
1.87      matthew  3259: =cut
                   3260: 
                   3261: ###############################################################
                   3262: ###############################################################
                   3263: sub decode_user_agent {
1.247     albertel 3264:     my ($r)=@_;
1.87      matthew  3265:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   3266:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   3267:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 3268:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  3269:     my $clientbrowser='unknown';
                   3270:     my $clientversion='0';
                   3271:     my $clientmathml='';
                   3272:     my $clientunicode='0';
1.1137    raeburn  3273:     my $clientmobile=0;
1.1194    raeburn  3274:     my $clientosversion='';
1.87      matthew  3275:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  3276:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  3277: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   3278: 	    $clientbrowser=$bname;
                   3279:             $httpbrowser=~/$vreg/i;
                   3280: 	    $clientversion=$1;
                   3281:             $clientmathml=($clientversion>=$minv);
                   3282:             $clientunicode=($clientversion>=$univ);
                   3283: 	}
                   3284:     }
                   3285:     my $clientos='unknown';
1.1141    raeburn  3286:     my $clientinfo;
1.87      matthew  3287:     if (($httpbrowser=~/linux/i) ||
                   3288:         ($httpbrowser=~/unix/i) ||
                   3289:         ($httpbrowser=~/ux/i) ||
                   3290:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   3291:     if (($httpbrowser=~/vax/i) ||
                   3292:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   3293:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   3294:     if (($httpbrowser=~/mac/i) ||
                   3295:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  3296:     if ($httpbrowser=~/win/i) {
                   3297:         $clientos='win';
                   3298:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   3299:             $clientosversion = $1;
                   3300:         }
                   3301:     }
1.87      matthew  3302:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3303:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3304:         $clientmobile=lc($1);
                   3305:     }
1.1141    raeburn  3306:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3307:         $clientinfo = 'firefox-'.$1;
                   3308:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3309:         $clientinfo = 'chromeframe-'.$1;
                   3310:     }
1.87      matthew  3311:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3312:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3313:             $clientosversion);
1.87      matthew  3314: }
                   3315: 
1.32      matthew  3316: ###############################################################
                   3317: ##    Authentication changing form generation subroutines    ##
                   3318: ###############################################################
                   3319: ##
                   3320: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3321: ## hash, and have reasonable default values.
                   3322: ##
                   3323: ##    formname = the name given in the <form> tag.
1.35      matthew  3324: #-------------------------------------------
                   3325: 
1.45      matthew  3326: =pod
                   3327: 
1.112     bowersj2 3328: =head1 Authentication Routines
                   3329: 
                   3330: =over 4
                   3331: 
1.648     raeburn  3332: =item * &authform_xxxxxx()
1.35      matthew  3333: 
                   3334: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3335: handle some of the conveniences required for authentication forms.  
                   3336: This is not an optimal method, but it works.  
                   3337: 
                   3338: =over 4
                   3339: 
1.112     bowersj2 3340: =item * authform_header
1.35      matthew  3341: 
1.112     bowersj2 3342: =item * authform_authorwarning
1.35      matthew  3343: 
1.112     bowersj2 3344: =item * authform_nochange
1.35      matthew  3345: 
1.112     bowersj2 3346: =item * authform_kerberos
1.35      matthew  3347: 
1.112     bowersj2 3348: =item * authform_internal
1.35      matthew  3349: 
1.112     bowersj2 3350: =item * authform_filesystem
1.35      matthew  3351: 
1.1310    raeburn  3352: =item * authform_lti
                   3353: 
1.35      matthew  3354: =back
                   3355: 
1.648     raeburn  3356: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3357: 
1.35      matthew  3358: =cut
                   3359: 
                   3360: #-------------------------------------------
1.32      matthew  3361: sub authform_header{  
                   3362:     my %in = (
                   3363:         formname => 'cu',
1.80      albertel 3364:         kerb_def_dom => '',
1.32      matthew  3365:         @_,
                   3366:     );
                   3367:     $in{'formname'} = 'document.' . $in{'formname'};
                   3368:     my $result='';
1.80      albertel 3369: 
                   3370: #---------------------------------------------- Code for upper case translation
                   3371:     my $Javascript_toUpperCase;
                   3372:     unless ($in{kerb_def_dom}) {
                   3373:         $Javascript_toUpperCase =<<"END";
                   3374:         switch (choice) {
                   3375:            case 'krb': currentform.elements[choicearg].value =
                   3376:                currentform.elements[choicearg].value.toUpperCase();
                   3377:                break;
                   3378:            default:
                   3379:         }
                   3380: END
                   3381:     } else {
                   3382:         $Javascript_toUpperCase = "";
                   3383:     }
                   3384: 
1.165     raeburn  3385:     my $radioval = "'nochange'";
1.591     raeburn  3386:     if (defined($in{'curr_authtype'})) {
                   3387:         if ($in{'curr_authtype'} ne '') {
                   3388:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3389:         }
1.174     matthew  3390:     }
1.165     raeburn  3391:     my $argfield = 'null';
1.591     raeburn  3392:     if (defined($in{'mode'})) {
1.165     raeburn  3393:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3394:             if (defined($in{'curr_autharg'})) {
                   3395:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3396:                     $argfield = "'$in{'curr_autharg'}'";
                   3397:                 }
                   3398:             }
                   3399:         }
                   3400:     }
                   3401: 
1.32      matthew  3402:     $result.=<<"END";
                   3403: var current = new Object();
1.165     raeburn  3404: current.radiovalue = $radioval;
                   3405: current.argfield = $argfield;
1.32      matthew  3406: 
                   3407: function changed_radio(choice,currentform) {
                   3408:     var choicearg = choice + 'arg';
                   3409:     // If a radio button in changed, we need to change the argfield
                   3410:     if (current.radiovalue != choice) {
                   3411:         current.radiovalue = choice;
                   3412:         if (current.argfield != null) {
                   3413:             currentform.elements[current.argfield].value = '';
                   3414:         }
                   3415:         if (choice == 'nochange') {
                   3416:             current.argfield = null;
                   3417:         } else {
                   3418:             current.argfield = choicearg;
                   3419:             switch(choice) {
                   3420:                 case 'krb': 
                   3421:                     currentform.elements[current.argfield].value = 
                   3422:                         "$in{'kerb_def_dom'}";
                   3423:                 break;
                   3424:               default:
                   3425:                 break;
                   3426:             }
                   3427:         }
                   3428:     }
                   3429:     return;
                   3430: }
1.22      www      3431: 
1.32      matthew  3432: function changed_text(choice,currentform) {
                   3433:     var choicearg = choice + 'arg';
                   3434:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3435:         $Javascript_toUpperCase
1.32      matthew  3436:         // clear old field
                   3437:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3438:             currentform.elements[current.argfield].value = '';
                   3439:         }
                   3440:         current.argfield = choicearg;
                   3441:     }
                   3442:     set_auth_radio_buttons(choice,currentform);
                   3443:     return;
1.20      www      3444: }
1.32      matthew  3445: 
                   3446: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3447:     var numauthchoices = currentform.login.length;
                   3448:     if (typeof numauthchoices  == "undefined") {
                   3449:         return;
                   3450:     } 
1.32      matthew  3451:     var i=0;
1.986     raeburn  3452:     while (i < numauthchoices) {
1.32      matthew  3453:         if (currentform.login[i].value == newvalue) { break; }
                   3454:         i++;
                   3455:     }
1.986     raeburn  3456:     if (i == numauthchoices) {
1.32      matthew  3457:         return;
                   3458:     }
                   3459:     current.radiovalue = newvalue;
                   3460:     currentform.login[i].checked = true;
                   3461:     return;
                   3462: }
                   3463: END
                   3464:     return $result;
                   3465: }
                   3466: 
1.1106    raeburn  3467: sub authform_authorwarning {
1.32      matthew  3468:     my $result='';
1.144     matthew  3469:     $result='<i>'.
                   3470:         &mt('As a general rule, only authors or co-authors should be '.
                   3471:             'filesystem authenticated '.
                   3472:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3473:     return $result;
                   3474: }
                   3475: 
1.1106    raeburn  3476: sub authform_nochange {
1.32      matthew  3477:     my %in = (
                   3478:               formname => 'document.cu',
                   3479:               kerb_def_dom => 'MSU.EDU',
                   3480:               @_,
                   3481:           );
1.1106    raeburn  3482:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3483:     my $result;
1.1104    raeburn  3484:     if (!$authnum) {
1.1105    raeburn  3485:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3486:     } else {
                   3487:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3488:                   '<input type="radio" name="login" value="nochange" '.
                   3489:                   'checked="checked" onclick="'.
1.281     albertel 3490:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3491: 	    '</label>';
1.586     raeburn  3492:     }
1.32      matthew  3493:     return $result;
                   3494: }
                   3495: 
1.591     raeburn  3496: sub authform_kerberos {
1.32      matthew  3497:     my %in = (
                   3498:               formname => 'document.cu',
                   3499:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3500:               kerb_def_auth => 'krb4',
1.32      matthew  3501:               @_,
                   3502:               );
1.586     raeburn  3503:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3504:         $autharg,$jscall,$disabled);
1.1106    raeburn  3505:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3506:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3507:        $check5 = ' checked="checked"';
1.80      albertel 3508:     } else {
1.772     bisitz   3509:        $check4 = ' checked="checked"';
1.80      albertel 3510:     }
1.1259    raeburn  3511:     if ($in{'readonly'}) {
                   3512:         $disabled = ' disabled="disabled"';
                   3513:     }
1.165     raeburn  3514:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3515:     if (defined($in{'curr_authtype'})) {
                   3516:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3517:             $krbcheck = ' checked="checked"';
1.623     raeburn  3518:             if (defined($in{'mode'})) {
                   3519:                 if ($in{'mode'} eq 'modifyuser') {
                   3520:                     $krbcheck = '';
                   3521:                 }
                   3522:             }
1.591     raeburn  3523:             if (defined($in{'curr_kerb_ver'})) {
                   3524:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3525:                     $check5 = ' checked="checked"';
1.591     raeburn  3526:                     $check4 = '';
                   3527:                 } else {
1.772     bisitz   3528:                     $check4 = ' checked="checked"';
1.591     raeburn  3529:                     $check5 = '';
                   3530:                 }
1.586     raeburn  3531:             }
1.591     raeburn  3532:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3533:                 $krbarg = $in{'curr_autharg'};
                   3534:             }
1.586     raeburn  3535:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3536:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3537:                     $result = 
                   3538:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3539:         $in{'curr_autharg'},$krbver);
                   3540:                 } else {
                   3541:                     $result =
                   3542:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3543:                 }
                   3544:                 return $result; 
                   3545:             }
                   3546:         }
                   3547:     } else {
                   3548:         if ($authnum == 1) {
1.784     bisitz   3549:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3550:         }
                   3551:     }
1.586     raeburn  3552:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3553:         return;
1.587     raeburn  3554:     } elsif ($authtype eq '') {
1.591     raeburn  3555:         if (defined($in{'mode'})) {
1.587     raeburn  3556:             if ($in{'mode'} eq 'modifycourse') {
                   3557:                 if ($authnum == 1) {
1.1259    raeburn  3558:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3559:                 }
                   3560:             }
                   3561:         }
1.586     raeburn  3562:     }
                   3563:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3564:     if ($authtype eq '') {
                   3565:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3566:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3567:                     $krbcheck.$disabled.' />';
1.586     raeburn  3568:     }
                   3569:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3570:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3571:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3572:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3573:          $in{'curr_authtype'} eq 'krb4')) {
                   3574:         $result .= &mt
1.144     matthew  3575:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3576:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3577:          '<label>'.$authtype,
1.281     albertel 3578:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3579:              'value="'.$krbarg.'" '.
1.1259    raeburn  3580:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3581:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3582:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3583: 	 '</label>');
1.586     raeburn  3584:     } elsif ($can_assign{'krb4'}) {
                   3585:         $result .= &mt
                   3586:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3587:          '[_3] Version 4 [_4]',
                   3588:          '<label>'.$authtype,
                   3589:          '</label><input type="text" size="10" name="krbarg" '.
                   3590:              'value="'.$krbarg.'" '.
1.1259    raeburn  3591:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3592:          '<label><input type="hidden" name="krbver" value="4" />',
                   3593:          '</label>');
                   3594:     } elsif ($can_assign{'krb5'}) {
                   3595:         $result .= &mt
                   3596:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3597:          '[_3] Version 5 [_4]',
                   3598:          '<label>'.$authtype,
                   3599:          '</label><input type="text" size="10" name="krbarg" '.
                   3600:              'value="'.$krbarg.'" '.
1.1259    raeburn  3601:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3602:          '<label><input type="hidden" name="krbver" value="5" />',
                   3603:          '</label>');
                   3604:     }
1.32      matthew  3605:     return $result;
                   3606: }
                   3607: 
1.1106    raeburn  3608: sub authform_internal {
1.586     raeburn  3609:     my %in = (
1.32      matthew  3610:                 formname => 'document.cu',
                   3611:                 kerb_def_dom => 'MSU.EDU',
                   3612:                 @_,
                   3613:                 );
1.1259    raeburn  3614:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3615:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3616:     if ($in{'readonly'}) {
                   3617:         $disabled = ' disabled="disabled"';
                   3618:     }
1.591     raeburn  3619:     if (defined($in{'curr_authtype'})) {
                   3620:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3621:             if ($can_assign{'int'}) {
1.772     bisitz   3622:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3623:                 if (defined($in{'mode'})) {
                   3624:                     if ($in{'mode'} eq 'modifyuser') {
                   3625:                         $intcheck = '';
                   3626:                     }
                   3627:                 }
1.591     raeburn  3628:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3629:                     $intarg = $in{'curr_autharg'};
                   3630:                 }
                   3631:             } else {
                   3632:                 $result = &mt('Currently internally authenticated.');
                   3633:                 return $result;
1.165     raeburn  3634:             }
                   3635:         }
1.586     raeburn  3636:     } else {
                   3637:         if ($authnum == 1) {
1.784     bisitz   3638:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3639:         }
                   3640:     }
                   3641:     if (!$can_assign{'int'}) {
                   3642:         return;
1.587     raeburn  3643:     } elsif ($authtype eq '') {
1.591     raeburn  3644:         if (defined($in{'mode'})) {
1.587     raeburn  3645:             if ($in{'mode'} eq 'modifycourse') {
                   3646:                 if ($authnum == 1) {
1.1259    raeburn  3647:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3648:                 }
                   3649:             }
                   3650:         }
1.165     raeburn  3651:     }
1.586     raeburn  3652:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3653:     if ($authtype eq '') {
                   3654:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3655:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3656:     }
1.605     bisitz   3657:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3658:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3659:     $result = &mt
1.144     matthew  3660:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3661:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3662:     $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  3663:     return $result;
                   3664: }
                   3665: 
1.1104    raeburn  3666: sub authform_local {
1.32      matthew  3667:     my %in = (
                   3668:               formname => 'document.cu',
                   3669:               kerb_def_dom => 'MSU.EDU',
                   3670:               @_,
                   3671:               );
1.1259    raeburn  3672:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3673:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3674:     if ($in{'readonly'}) {
                   3675:         $disabled = ' disabled="disabled"';
                   3676:     } 
1.591     raeburn  3677:     if (defined($in{'curr_authtype'})) {
                   3678:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3679:             if ($can_assign{'loc'}) {
1.772     bisitz   3680:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3681:                 if (defined($in{'mode'})) {
                   3682:                     if ($in{'mode'} eq 'modifyuser') {
                   3683:                         $loccheck = '';
                   3684:                     }
                   3685:                 }
1.591     raeburn  3686:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3687:                     $locarg = $in{'curr_autharg'};
                   3688:                 }
                   3689:             } else {
                   3690:                 $result = &mt('Currently using local (institutional) authentication.');
                   3691:                 return $result;
1.165     raeburn  3692:             }
                   3693:         }
1.586     raeburn  3694:     } else {
                   3695:         if ($authnum == 1) {
1.784     bisitz   3696:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3697:         }
                   3698:     }
                   3699:     if (!$can_assign{'loc'}) {
                   3700:         return;
1.587     raeburn  3701:     } elsif ($authtype eq '') {
1.591     raeburn  3702:         if (defined($in{'mode'})) {
1.587     raeburn  3703:             if ($in{'mode'} eq 'modifycourse') {
                   3704:                 if ($authnum == 1) {
1.1259    raeburn  3705:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3706:                 }
                   3707:             }
                   3708:         }
1.165     raeburn  3709:     }
1.586     raeburn  3710:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3711:     if ($authtype eq '') {
                   3712:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3713:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3714:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3715:     }
                   3716:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3717:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3718:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3719:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3720:     return $result;
                   3721: }
                   3722: 
1.1106    raeburn  3723: sub authform_filesystem {
1.32      matthew  3724:     my %in = (
                   3725:               formname => 'document.cu',
                   3726:               kerb_def_dom => 'MSU.EDU',
                   3727:               @_,
                   3728:               );
1.1259    raeburn  3729:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3730:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3731:     if ($in{'readonly'}) {
                   3732:         $disabled = ' disabled="disabled"';
                   3733:     }
1.591     raeburn  3734:     if (defined($in{'curr_authtype'})) {
                   3735:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3736:             if ($can_assign{'fsys'}) {
1.772     bisitz   3737:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3738:                 if (defined($in{'mode'})) {
                   3739:                     if ($in{'mode'} eq 'modifyuser') {
                   3740:                         $fsyscheck = '';
                   3741:                     }
                   3742:                 }
1.586     raeburn  3743:             } else {
                   3744:                 $result = &mt('Currently Filesystem Authenticated.');
                   3745:                 return $result;
1.1259    raeburn  3746:             }
1.586     raeburn  3747:         }
                   3748:     } else {
                   3749:         if ($authnum == 1) {
1.784     bisitz   3750:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3751:         }
                   3752:     }
                   3753:     if (!$can_assign{'fsys'}) {
                   3754:         return;
1.587     raeburn  3755:     } elsif ($authtype eq '') {
1.591     raeburn  3756:         if (defined($in{'mode'})) {
1.587     raeburn  3757:             if ($in{'mode'} eq 'modifycourse') {
                   3758:                 if ($authnum == 1) {
1.1259    raeburn  3759:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3760:                 }
                   3761:             }
                   3762:         }
1.586     raeburn  3763:     }
                   3764:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3765:     if ($authtype eq '') {
                   3766:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3767:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3768:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3769:     }
1.1310    raeburn  3770:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3771:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3772:     $result = &mt
1.144     matthew  3773:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3774:          '<label>'.$authtype,'</label>'.$autharg);
                   3775:     return $result;
                   3776: }
                   3777: 
                   3778: sub authform_lti {
                   3779:     my %in = (
                   3780:               formname => 'document.cu',
                   3781:               kerb_def_dom => 'MSU.EDU',
                   3782:               @_,
                   3783:               );
                   3784:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3785:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3786:     if ($in{'readonly'}) {
                   3787:         $disabled = ' disabled="disabled"';
                   3788:     }
                   3789:     if (defined($in{'curr_authtype'})) {
                   3790:         if ($in{'curr_authtype'} eq 'lti') {
                   3791:             if ($can_assign{'lti'}) {
                   3792:                 $lticheck = 'checked="checked" ';
                   3793:                 if (defined($in{'mode'})) {
                   3794:                     if ($in{'mode'} eq 'modifyuser') {
                   3795:                         $lticheck = '';
                   3796:                     }
                   3797:                 }
                   3798:             } else {
                   3799:                 $result = &mt('Currently LTI Authenticated.');
                   3800:                 return $result;
                   3801:             }
                   3802:         }
                   3803:     } else {
                   3804:         if ($authnum == 1) {
                   3805:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3806:         }
                   3807:     }
                   3808:     if (!$can_assign{'lti'}) {
                   3809:         return;
                   3810:     } elsif ($authtype eq '') {
                   3811:         if (defined($in{'mode'})) {
                   3812:             if ($in{'mode'} eq 'modifycourse') {
                   3813:                 if ($authnum == 1) {
                   3814:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3815:                 }
                   3816:             }
                   3817:         }
                   3818:     }
                   3819:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3820:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3821:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3822:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3823:                     $jscall.'"'.$disabled.' />';
                   3824:     }
                   3825:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3826:     if ($authtype) {
                   3827:         $result = &mt('[_1] LTI Authenticated',
                   3828:                       '<label>'.$authtype.'</label>'.$autharg);
                   3829:     } else {
                   3830:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3831:                   $autharg;
                   3832:     }
1.32      matthew  3833:     return $result;
                   3834: }
                   3835: 
1.586     raeburn  3836: sub get_assignable_auth {
                   3837:     my ($dom) = @_;
                   3838:     if ($dom eq '') {
                   3839:         $dom = $env{'request.role.domain'};
                   3840:     }
                   3841:     my %can_assign = (
                   3842:                           krb4 => 1,
                   3843:                           krb5 => 1,
                   3844:                           int  => 1,
                   3845:                           loc  => 1,
1.1310    raeburn  3846:                           lti  => 1,
1.586     raeburn  3847:                      );
                   3848:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3849:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3850:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3851:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3852:             my $context;
                   3853:             if ($env{'request.role'} =~ /^au/) {
                   3854:                 $context = 'author';
1.1259    raeburn  3855:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3856:                 $context = 'domain';
                   3857:             } elsif ($env{'request.course.id'}) {
                   3858:                 $context = 'course';
                   3859:             }
                   3860:             if ($context) {
                   3861:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3862:                    %can_assign = %{$authhash->{$context}}; 
                   3863:                 }
                   3864:             }
                   3865:         }
                   3866:     }
                   3867:     my $authnum = 0;
                   3868:     foreach my $key (keys(%can_assign)) {
                   3869:         if ($can_assign{$key}) {
                   3870:             $authnum ++;
                   3871:         }
                   3872:     }
                   3873:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3874:         $authnum --;
                   3875:     }
                   3876:     return ($authnum,%can_assign);
                   3877: }
                   3878: 
1.1331    raeburn  3879: sub check_passwd_rules {
                   3880:     my ($domain,$plainpass) = @_;
                   3881:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3882:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3883:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3884:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3885:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3886:             if ($passwdconf{'min'} > $min) {
                   3887:                 $min = $passwdconf{'min'};
                   3888:             }
1.1331    raeburn  3889:         }
                   3890:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3891:             $max = $passwdconf{'max'};
                   3892:         }
                   3893:         @chars = @{$passwdconf{'chars'}};
                   3894:     }
                   3895:     if (($min) && (length($plainpass) < $min)) {
                   3896:         push(@brokerule,'min');
                   3897:     }
                   3898:     if (($max) && (length($plainpass) > $max)) {
                   3899:         push(@brokerule,'max');
                   3900:     }
                   3901:     if (@chars) {
                   3902:         my %rules;
                   3903:         map { $rules{$_} = 1; } @chars;
                   3904:         if ($rules{'uc'}) {
                   3905:             unless ($plainpass =~ /[A-Z]/) {
                   3906:                 push(@brokerule,'uc');
                   3907:             }
                   3908:         }
                   3909:         if ($rules{'lc'}) {
1.1332    raeburn  3910:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3911:                 push(@brokerule,'lc');
                   3912:             }
                   3913:         }
                   3914:         if ($rules{'num'}) {
                   3915:             unless ($plainpass =~ /\d/) {
                   3916:                 push(@brokerule,'num');
                   3917:             }
                   3918:         }
                   3919:         if ($rules{'spec'}) {
                   3920:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3921:                 push(@brokerule,'spec');
                   3922:             }
                   3923:         }
                   3924:     }
                   3925:     if (@brokerule) {
                   3926:         my %rulenames = &Apache::lonlocal::texthash(
                   3927:             uc   => 'At least one upper case letter',
                   3928:             lc   => 'At least one lower case letter',
                   3929:             num  => 'At least one number',
                   3930:             spec => 'At least one non-alphanumeric',
                   3931:         );
                   3932:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3933:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3934:         $rulenames{'num'} .= ': 0123456789';
                   3935:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3936:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3937:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3938:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3939:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3940:             if (grep(/^$rule$/,@brokerule)) {
                   3941:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3942:             }
                   3943:         }
                   3944:         $warning .= '</ul>';
                   3945:     }
1.1332    raeburn  3946:     if (wantarray) {
                   3947:         return @brokerule;
                   3948:     }
1.1331    raeburn  3949:     return $warning;
                   3950: }
                   3951: 
1.1376    raeburn  3952: sub passwd_validation_js {
1.1377    raeburn  3953:     my ($currpasswdval,$domain,$context,$id) = @_;
                   3954:     my (%passwdconf,$alertmsg);
                   3955:     if ($context eq 'linkprot') {
                   3956:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3957:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3958:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3959:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3960:             }
                   3961:         }
                   3962:         if ($id eq 'add') {
                   3963:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3964:         } elsif ($id =~ /^\d+$/) {
                   3965:             my $pos = $id+1;
                   3966:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3967:         } else {
                   3968:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3969:         }
1.1434    raeburn  3970:     } elsif ($context eq 'ltitools') {
                   3971:         my %domconfig = &Apache::lonnet::get_dom('configuration',['toolsec'],$domain);
                   3972:         if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   3973:             if (ref($domconfig{'toolsec'}{'rules'}) eq 'HASH') {
                   3974:                 %passwdconf = %{$domconfig{'toolsec'}{'rules'}};
                   3975:             }
                   3976:         }
                   3977:         if ($id eq 'add') {
                   3978:             $alertmsg = &mt('Secret for added external tool did not satisfy requirement(s):').'\n\n';
                   3979:         } elsif ($id =~ /^\d+$/) {
                   3980:             my $pos = $id+1;
                   3981:             $alertmsg = &mt('Secret for external tool [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3982:         } else {
                   3983:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3984:         }
1.1377    raeburn  3985:     } else {
                   3986:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3987:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3988:     }
1.1376    raeburn  3989:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3990:     $numrules = 0;
                   3991:     $min = $Apache::lonnet::passwdmin;
                   3992:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3993:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3994:             if ($passwdconf{'min'} > $min) {
                   3995:                 $min = $passwdconf{'min'};
                   3996:             }
                   3997:         }
                   3998:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3999:             $max = $passwdconf{'max'};
                   4000:             $numrules ++;
                   4001:         }
                   4002:         @chars = @{$passwdconf{'chars'}};
                   4003:         if (@chars) {
                   4004:             $numrules ++;
                   4005:         }
                   4006:     }
                   4007:     if ($min > 0) {
                   4008:         $numrules ++;
                   4009:     }
                   4010:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   4011:         if ($min) {
                   4012:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   4013:         }
                   4014:         if ($max) {
                   4015:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   4016:         }
                   4017:         my (@charalerts,@charrules);
                   4018:         if (@chars) {
                   4019:             if (grep(/^uc$/,@chars)) {
                   4020:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   4021:                 push(@charrules,'uc');
                   4022:             }
                   4023:             if (grep(/^lc$/,@chars)) {
                   4024:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   4025:                 push(@charrules,'lc');
                   4026:             }
                   4027:             if (grep(/^num$/,@chars)) {
                   4028:                 push(@charalerts,&mt('contain at least one number'));
                   4029:                 push(@charrules,'num');
                   4030:             }
                   4031:             if (grep(/^spec$/,@chars)) {
                   4032:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   4033:                 push(@charrules,'spec');
                   4034:             }
                   4035:         }
                   4036:         $intargjs = qq|            var rulesmsg = '';\n|.
                   4037:                     qq|            var currpwval = $currpasswdval;\n|;
                   4038:             if ($min) {
                   4039:                 $intargjs .= qq|
                   4040:             if (currpwval.length < $min) {
                   4041:                 rulesmsg += ' - $alert{min}';
                   4042:             }
                   4043: |;
                   4044:             }
                   4045:             if ($max) {
                   4046:                 $intargjs .= qq|
                   4047:             if (currpwval.length > $max) {
                   4048:                 rulesmsg += ' - $alert{max}';
                   4049:             }
                   4050: |;
                   4051:             }
                   4052:             if (@chars > 0) {
                   4053:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   4054:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   4055:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   4056:                              qq|            var charrules = new Array($charrulestr);\n|.
                   4057:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   4058:                 my %rules;
                   4059:                 map { $rules{$_} = 1; } @chars;
                   4060:                 if ($rules{'uc'}) {
                   4061:                     $intargjs .= qq|
                   4062:             var ucRegExp = /[A-Z]/;
                   4063:             if (!ucRegExp.test(currpwval)) {
                   4064:                 brokerules.push('uc');
                   4065:             }
                   4066: |;
                   4067:                 }
                   4068:                 if ($rules{'lc'}) {
                   4069:                     $intargjs .= qq|
                   4070:             var lcRegExp = /[a-z]/;
                   4071:             if (!lcRegExp.test(currpwval)) {
                   4072:                 brokerules.push('lc');
                   4073:             }
                   4074: |;
                   4075:                 }
                   4076:                 if ($rules{'num'}) {
                   4077:                      $intargjs .= qq|
                   4078:             var numRegExp = /[0-9]/;
                   4079:             if (!numRegExp.test(currpwval)) {
                   4080:                 brokerules.push('num');
                   4081:             }
                   4082: |;
                   4083:                 }
                   4084:                 if ($rules{'spec'}) {
                   4085:                      $intargjs .= q|
                   4086:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   4087:             if (!specRegExp.test(currpwval)) {
                   4088:                 brokerules.push('spec');
                   4089:             }
                   4090: |;
                   4091:                 }
                   4092:                 $intargjs .= qq|
                   4093:             if (brokerules.length > 0) {
                   4094:                 for (var i=0; i<brokerules.length; i++) {
                   4095:                     for (var j=0; j<charrules.length; j++) {
                   4096:                         if (brokerules[i] == charrules[j]) {
                   4097:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   4098:                             break;
                   4099:                         }
                   4100:                     }
                   4101:                 }
                   4102:             }
                   4103: |;
                   4104:             }
                   4105:             $intargjs .= qq|
                   4106:             if (rulesmsg != '') {
                   4107:                 rulesmsg = '$alertmsg'+rulesmsg;
                   4108:                 alert(rulesmsg);
                   4109:                 return false;
                   4110:             }
                   4111: |;
                   4112:     }
                   4113:     return ($numrules,$intargjs);
                   4114: }
                   4115: 
1.80      albertel 4116: ###############################################################
                   4117: ##    Get Kerberos Defaults for Domain                 ##
                   4118: ###############################################################
                   4119: ##
                   4120: ## Returns default kerberos version and an associated argument
                   4121: ## as listed in file domain.tab. If not listed, provides
                   4122: ## appropriate default domain and kerberos version.
                   4123: ##
                   4124: #-------------------------------------------
                   4125: 
                   4126: =pod
                   4127: 
1.648     raeburn  4128: =item * &get_kerberos_defaults()
1.80      albertel 4129: 
                   4130: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  4131: version and domain. If not found, it defaults to version 4 and the 
                   4132: domain of the server.
1.80      albertel 4133: 
1.648     raeburn  4134: =over 4
                   4135: 
1.80      albertel 4136: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   4137: 
1.648     raeburn  4138: =back
                   4139: 
                   4140: =back
                   4141: 
1.80      albertel 4142: =cut
                   4143: 
                   4144: #-------------------------------------------
                   4145: sub get_kerberos_defaults {
                   4146:     my $domain=shift;
1.641     raeburn  4147:     my ($krbdef,$krbdefdom);
                   4148:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   4149:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   4150:         $krbdef = $domdefaults{'auth_def'};
                   4151:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   4152:     } else {
1.80      albertel 4153:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   4154:         my $krbdefdom=$1;
                   4155:         $krbdefdom=~tr/a-z/A-Z/;
                   4156:         $krbdef = "krb4";
                   4157:     }
                   4158:     return ($krbdef,$krbdefdom);
                   4159: }
1.112     bowersj2 4160: 
1.32      matthew  4161: 
1.46      matthew  4162: ###############################################################
                   4163: ##                Thesaurus Functions                        ##
                   4164: ###############################################################
1.20      www      4165: 
1.46      matthew  4166: =pod
1.20      www      4167: 
1.112     bowersj2 4168: =head1 Thesaurus Functions
                   4169: 
                   4170: =over 4
                   4171: 
1.648     raeburn  4172: =item * &initialize_keywords()
1.46      matthew  4173: 
                   4174: Initializes the package variable %Keywords if it is empty.  Uses the
                   4175: package variable $thesaurus_db_file.
                   4176: 
                   4177: =cut
                   4178: 
                   4179: ###################################################
                   4180: 
                   4181: sub initialize_keywords {
                   4182:     return 1 if (scalar keys(%Keywords));
                   4183:     # If we are here, %Keywords is empty, so fill it up
                   4184:     #   Make sure the file we need exists...
                   4185:     if (! -e $thesaurus_db_file) {
                   4186:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   4187:                                  " failed because it does not exist");
                   4188:         return 0;
                   4189:     }
                   4190:     #   Set up the hash as a database
                   4191:     my %thesaurus_db;
                   4192:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4193:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4194:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   4195:                                  $thesaurus_db_file);
                   4196:         return 0;
                   4197:     } 
                   4198:     #  Get the average number of appearances of a word.
                   4199:     my $avecount = $thesaurus_db{'average.count'};
                   4200:     #  Put keywords (those that appear > average) into %Keywords
                   4201:     while (my ($word,$data)=each (%thesaurus_db)) {
                   4202:         my ($count,undef) = split /:/,$data;
                   4203:         $Keywords{$word}++ if ($count > $avecount);
                   4204:     }
                   4205:     untie %thesaurus_db;
                   4206:     # Remove special values from %Keywords.
1.356     albertel 4207:     foreach my $value ('total.count','average.count') {
                   4208:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  4209:   }
1.46      matthew  4210:     return 1;
                   4211: }
                   4212: 
                   4213: ###################################################
                   4214: 
                   4215: =pod
                   4216: 
1.648     raeburn  4217: =item * &keyword($word)
1.46      matthew  4218: 
                   4219: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   4220: than the average number of times in the thesaurus database.  Calls 
                   4221: &initialize_keywords
                   4222: 
                   4223: =cut
                   4224: 
                   4225: ###################################################
1.20      www      4226: 
                   4227: sub keyword {
1.46      matthew  4228:     return if (!&initialize_keywords());
                   4229:     my $word=lc(shift());
                   4230:     $word=~s/\W//g;
                   4231:     return exists($Keywords{$word});
1.20      www      4232: }
1.46      matthew  4233: 
                   4234: ###############################################################
                   4235: 
                   4236: =pod 
1.20      www      4237: 
1.648     raeburn  4238: =item * &get_related_words()
1.46      matthew  4239: 
1.160     matthew  4240: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  4241: an array of words.  If the keyword is not in the thesaurus, an empty array
                   4242: will be returned.  The order of the words returned is determined by the
                   4243: database which holds them.
                   4244: 
                   4245: Uses global $thesaurus_db_file.
                   4246: 
1.1057    foxr     4247: 
1.46      matthew  4248: =cut
                   4249: 
                   4250: ###############################################################
                   4251: sub get_related_words {
                   4252:     my $keyword = shift;
                   4253:     my %thesaurus_db;
                   4254:     if (! -e $thesaurus_db_file) {
                   4255:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   4256:                                  "failed because the file does not exist");
                   4257:         return ();
                   4258:     }
                   4259:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4260:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4261:         return ();
                   4262:     } 
                   4263:     my @Words=();
1.429     www      4264:     my $count=0;
1.46      matthew  4265:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 4266: 	# The first element is the number of times
                   4267: 	# the word appears.  We do not need it now.
1.429     www      4268: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   4269: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   4270: 	my $threshold=$mostfrequentcount/10;
                   4271:         foreach my $possibleword (@RelatedWords) {
                   4272:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   4273:             if ($wordcount>$threshold) {
                   4274: 		push(@Words,$word);
                   4275:                 $count++;
                   4276:                 if ($count>10) { last; }
                   4277: 	    }
1.20      www      4278:         }
                   4279:     }
1.46      matthew  4280:     untie %thesaurus_db;
                   4281:     return @Words;
1.14      harris41 4282: }
1.1090    foxr     4283: ###############################################################
                   4284: #
                   4285: #  Spell checking
                   4286: #
                   4287: 
                   4288: =pod
                   4289: 
1.1142    raeburn  4290: =back
                   4291: 
1.1090    foxr     4292: =head1 Spell checking
                   4293: 
                   4294: =over 4
                   4295: 
                   4296: =item * &check_spelling($wordlist $language)
                   4297: 
                   4298: Takes a string containing words and feeds it to an external
                   4299: spellcheck program via a pipeline. Returns a string containing
                   4300: them mis-spelled words.
                   4301: 
                   4302: Parameters:
                   4303: 
                   4304: =over 4
                   4305: 
                   4306: =item - $wordlist
                   4307: 
                   4308: String that will be fed into the spellcheck program.
                   4309: 
                   4310: =item - $language
                   4311: 
                   4312: Language string that specifies the language for which the spell
                   4313: check will be performed.
                   4314: 
                   4315: =back
                   4316: 
                   4317: =back
                   4318: 
                   4319: Note: This sub assumes that aspell is installed.
                   4320: 
                   4321: 
                   4322: =cut
                   4323: 
1.46      matthew  4324: 
1.1090    foxr     4325: sub check_spelling {
                   4326:     my ($wordlist, $language) = @_;
1.1091    foxr     4327:     my @misspellings;
                   4328:     
                   4329:     # Generate the speller and set the langauge.
                   4330:     # if explicitly selected:
1.1090    foxr     4331: 
1.1091    foxr     4332:     my $speller = Text::Aspell->new;
1.1090    foxr     4333:     if ($language) {
1.1091    foxr     4334: 	$speller->set_option('lang', $language);
1.1090    foxr     4335:     }
                   4336: 
1.1091    foxr     4337:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4338: 
1.1091    foxr     4339:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4340: 
1.1091    foxr     4341:     foreach my $word (@words) {
                   4342: 	if(! $speller->check($word)) {
                   4343: 	    push(@misspellings, $word);
1.1090    foxr     4344: 	}
                   4345:     }
1.1091    foxr     4346:     return join(' ', @misspellings);
                   4347:     
1.1090    foxr     4348: }
                   4349: 
1.61      www      4350: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4351: =pod
                   4352: 
1.112     bowersj2 4353: =head1 User Name Functions
                   4354: 
                   4355: =over 4
                   4356: 
1.648     raeburn  4357: =item * &plainname($uname,$udom,$first)
1.81      albertel 4358: 
1.112     bowersj2 4359: Takes a users logon name and returns it as a string in
1.226     albertel 4360: "first middle last generation" form 
                   4361: if $first is set to 'lastname' then it returns it as
                   4362: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4363: 
                   4364: =cut
1.61      www      4365: 
1.295     www      4366: 
1.81      albertel 4367: ###############################################################
1.61      www      4368: sub plainname {
1.226     albertel 4369:     my ($uname,$udom,$first)=@_;
1.537     albertel 4370:     return if (!defined($uname) || !defined($udom));
1.295     www      4371:     my %names=&getnames($uname,$udom);
1.226     albertel 4372:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4373: 					  $names{'middlename'},
                   4374: 					  $names{'lastname'},
                   4375: 					  $names{'generation'},$first);
                   4376:     $name=~s/^\s+//;
1.62      www      4377:     $name=~s/\s+$//;
                   4378:     $name=~s/\s+/ /g;
1.353     albertel 4379:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4380:     return $name;
1.61      www      4381: }
1.66      www      4382: 
                   4383: # -------------------------------------------------------------------- Nickname
1.81      albertel 4384: =pod
                   4385: 
1.648     raeburn  4386: =item * &nickname($uname,$udom)
1.81      albertel 4387: 
                   4388: Gets a users name and returns it as a string as
                   4389: 
                   4390: "&quot;nickname&quot;"
1.66      www      4391: 
1.81      albertel 4392: if the user has a nickname or
                   4393: 
                   4394: "first middle last generation"
                   4395: 
                   4396: if the user does not
                   4397: 
                   4398: =cut
1.66      www      4399: 
                   4400: sub nickname {
                   4401:     my ($uname,$udom)=@_;
1.537     albertel 4402:     return if (!defined($uname) || !defined($udom));
1.295     www      4403:     my %names=&getnames($uname,$udom);
1.68      albertel 4404:     my $name=$names{'nickname'};
1.66      www      4405:     if ($name) {
                   4406:        $name='&quot;'.$name.'&quot;'; 
                   4407:     } else {
                   4408:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4409: 	     $names{'lastname'}.' '.$names{'generation'};
                   4410:        $name=~s/\s+$//;
                   4411:        $name=~s/\s+/ /g;
                   4412:     }
                   4413:     return $name;
                   4414: }
                   4415: 
1.295     www      4416: sub getnames {
                   4417:     my ($uname,$udom)=@_;
1.537     albertel 4418:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4419:     if ($udom eq 'public' && $uname eq 'public') {
                   4420: 	return ('lastname' => &mt('Public'));
                   4421:     }
1.295     www      4422:     my $id=$uname.':'.$udom;
                   4423:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4424:     if ($cached) {
                   4425: 	return %{$names};
                   4426:     } else {
                   4427: 	my %loadnames=&Apache::lonnet::get('environment',
                   4428:                     ['firstname','middlename','lastname','generation','nickname'],
                   4429: 					 $udom,$uname);
                   4430: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4431: 	return %loadnames;
                   4432:     }
                   4433: }
1.61      www      4434: 
1.542     raeburn  4435: # -------------------------------------------------------------------- getemails
1.648     raeburn  4436: 
1.542     raeburn  4437: =pod
                   4438: 
1.648     raeburn  4439: =item * &getemails($uname,$udom)
1.542     raeburn  4440: 
                   4441: Gets a user's email information and returns it as a hash with keys:
                   4442: notification, critnotification, permanentemail
                   4443: 
                   4444: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4445: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4446:  
1.648     raeburn  4447: 
1.542     raeburn  4448: =cut
                   4449: 
1.648     raeburn  4450: 
1.466     albertel 4451: sub getemails {
                   4452:     my ($uname,$udom)=@_;
                   4453:     if ($udom eq 'public' && $uname eq 'public') {
                   4454: 	return;
                   4455:     }
1.467     www      4456:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4457:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4458:     my $id=$uname.':'.$udom;
                   4459:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4460:     if ($cached) {
                   4461: 	return %{$names};
                   4462:     } else {
                   4463: 	my %loadnames=&Apache::lonnet::get('environment',
                   4464:                     			   ['notification','critnotification',
                   4465: 					    'permanentemail'],
                   4466: 					   $udom,$uname);
                   4467: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4468: 	return %loadnames;
                   4469:     }
                   4470: }
                   4471: 
1.551     albertel 4472: sub flush_email_cache {
                   4473:     my ($uname,$udom)=@_;
                   4474:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4475:     if (!$uname) { $uname=$env{'user.name'};   }
                   4476:     return if ($udom eq 'public' && $uname eq 'public');
                   4477:     my $id=$uname.':'.$udom;
                   4478:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4479: }
                   4480: 
1.728     raeburn  4481: # -------------------------------------------------------------------- getlangs
                   4482: 
                   4483: =pod
                   4484: 
                   4485: =item * &getlangs($uname,$udom)
                   4486: 
                   4487: Gets a user's language preference and returns it as a hash with key:
                   4488: language.
                   4489: 
                   4490: =cut
                   4491: 
                   4492: 
                   4493: sub getlangs {
                   4494:     my ($uname,$udom) = @_;
                   4495:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4496:     if (!$uname) { $uname=$env{'user.name'};   }
                   4497:     my $id=$uname.':'.$udom;
                   4498:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4499:     if ($cached) {
                   4500:         return %{$langs};
                   4501:     } else {
                   4502:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4503:                                            $udom,$uname);
                   4504:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4505:         return %loadlangs;
                   4506:     }
                   4507: }
                   4508: 
                   4509: sub flush_langs_cache {
                   4510:     my ($uname,$udom)=@_;
                   4511:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4512:     if (!$uname) { $uname=$env{'user.name'};   }
                   4513:     return if ($udom eq 'public' && $uname eq 'public');
                   4514:     my $id=$uname.':'.$udom;
                   4515:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4516: }
                   4517: 
1.61      www      4518: # ------------------------------------------------------------------ Screenname
1.81      albertel 4519: 
                   4520: =pod
                   4521: 
1.648     raeburn  4522: =item * &screenname($uname,$udom)
1.81      albertel 4523: 
                   4524: Gets a users screenname and returns it as a string
                   4525: 
                   4526: =cut
1.61      www      4527: 
                   4528: sub screenname {
                   4529:     my ($uname,$udom)=@_;
1.258     albertel 4530:     if ($uname eq $env{'user.name'} &&
                   4531: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4532:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4533:     return $names{'screenname'};
1.62      www      4534: }
                   4535: 
1.212     albertel 4536: 
1.802     bisitz   4537: # ------------------------------------------------------------- Confirm Wrapper
                   4538: =pod
                   4539: 
1.1142    raeburn  4540: =item * &confirmwrapper($message)
1.802     bisitz   4541: 
                   4542: Wrap messages about completion of operation in box
                   4543: 
                   4544: =cut
                   4545: 
                   4546: sub confirmwrapper {
                   4547:     my ($message)=@_;
                   4548:     if ($message) {
                   4549:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4550:                .$message."\n"
                   4551:                .'</div>'."\n";
                   4552:     } else {
                   4553:         return $message;
                   4554:     }
                   4555: }
                   4556: 
1.62      www      4557: # ------------------------------------------------------------- Message Wrapper
                   4558: 
                   4559: sub messagewrapper {
1.369     www      4560:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4561:     return 
1.441     albertel 4562:         '<a href="/adm/email?compose=individual&amp;'.
                   4563:         'recname='.$username.'&amp;recdom='.$domain.
                   4564: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4565:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4566: }
1.802     bisitz   4567: 
1.74      www      4568: # --------------------------------------------------------------- Notes Wrapper
                   4569: 
                   4570: sub noteswrapper {
                   4571:     my ($link,$un,$do)=@_;
                   4572:     return 
1.896     amueller 4573: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4574: }
1.802     bisitz   4575: 
1.62      www      4576: # ------------------------------------------------------------- Aboutme Wrapper
                   4577: 
                   4578: sub aboutmewrapper {
1.1070    raeburn  4579:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4580:     if (!defined($username)  && !defined($domain)) {
                   4581:         return;
                   4582:     }
1.1096    raeburn  4583:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4584: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4585: }
                   4586: 
                   4587: # ------------------------------------------------------------ Syllabus Wrapper
                   4588: 
                   4589: sub syllabuswrapper {
1.707     bisitz   4590:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4591:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4592: }
1.14      harris41 4593: 
1.1397    raeburn  4594: # -----------------------------------------------------------------------------
                   4595: 
1.1396    raeburn  4596: sub aboutme_on {
                   4597:     my ($uname,$udom)=@_;
                   4598:     unless ($uname) { $uname=$env{'user.name'}; }
                   4599:     unless ($udom)  { $udom=$env{'user.domain'}; }
                   4600:     return if ($udom eq 'public' && $uname eq 'public');
                   4601:     my $hashkey=$uname.':'.$udom;
                   4602:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   4603:     if ($cached) {
                   4604:         return $aboutme;
                   4605:     }
                   4606:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   4607:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   4608:     return $aboutme;
                   4609: }
                   4610: 
                   4611: sub devalidate_aboutme_cache {
                   4612:     my ($uname,$udom)=@_;
                   4613:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4614:     if (!$uname) { $uname=$env{'user.name'};   }
                   4615:     return if ($udom eq 'public' && $uname eq 'public');
                   4616:     my $id=$uname.':'.$udom;
                   4617:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   4618: }
                   4619: 
1.208     matthew  4620: sub track_student_link {
1.887     raeburn  4621:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4622:     my $link ="/adm/trackstudent?";
1.208     matthew  4623:     my $title = 'View recent activity';
                   4624:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4625:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4626:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4627:         $title .= ' of this student';
1.268     albertel 4628:     } 
1.208     matthew  4629:     if (defined($target) && $target !~ /^\s*$/) {
                   4630:         $target = qq{target="$target"};
                   4631:     } else {
                   4632:         $target = '';
                   4633:     }
1.268     albertel 4634:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4635:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4636:     $title = &mt($title);
                   4637:     $linktext = &mt($linktext);
1.448     albertel 4638:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4639: 	&help_open_topic('View_recent_activity');
1.208     matthew  4640: }
                   4641: 
1.781     raeburn  4642: sub slot_reservations_link {
                   4643:     my ($linktext,$sname,$sdom,$target) = @_;
                   4644:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4645:     my $title = 'View slot reservation history';
                   4646:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4647:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4648:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4649:         $title .= ' of this student';
                   4650:     }
                   4651:     if (defined($target) && $target !~ /^\s*$/) {
                   4652:         $target = qq{target="$target"};
                   4653:     } else {
                   4654:         $target = '';
                   4655:     }
                   4656:     $title = &mt($title);
                   4657:     $linktext = &mt($linktext);
                   4658:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4659: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4660: 
                   4661: }
                   4662: 
1.508     www      4663: # ===================================================== Display a student photo
                   4664: 
                   4665: 
1.509     albertel 4666: sub student_image_tag {
1.508     www      4667:     my ($domain,$user)=@_;
                   4668:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4669:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4670: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4671:     } else {
                   4672: 	return '';
                   4673:     }
                   4674: }
                   4675: 
1.112     bowersj2 4676: =pod
                   4677: 
                   4678: =back
                   4679: 
                   4680: =head1 Access .tab File Data
                   4681: 
                   4682: =over 4
                   4683: 
1.648     raeburn  4684: =item * &languageids() 
1.112     bowersj2 4685: 
                   4686: returns list of all language ids
                   4687: 
                   4688: =cut
                   4689: 
1.14      harris41 4690: sub languageids {
1.16      harris41 4691:     return sort(keys(%language));
1.14      harris41 4692: }
                   4693: 
1.112     bowersj2 4694: =pod
                   4695: 
1.648     raeburn  4696: =item * &languagedescription() 
1.112     bowersj2 4697: 
                   4698: returns description of a specified language id
                   4699: 
                   4700: =cut
                   4701: 
1.14      harris41 4702: sub languagedescription {
1.125     www      4703:     my $code=shift;
                   4704:     return  ($supported_language{$code}?'* ':'').
                   4705:             $language{$code}.
1.126     www      4706: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4707: }
                   4708: 
1.1048    foxr     4709: =pod
                   4710: 
                   4711: =item * &plainlanguagedescription
                   4712: 
                   4713: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4714: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4715: 
                   4716: =cut
                   4717: 
1.145     www      4718: sub plainlanguagedescription {
                   4719:     my $code=shift;
                   4720:     return $language{$code};
                   4721: }
                   4722: 
1.1048    foxr     4723: =pod
                   4724: 
                   4725: =item * &supportedlanguagecode
                   4726: 
                   4727: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4728: code.
                   4729: 
                   4730: =cut
                   4731: 
1.145     www      4732: sub supportedlanguagecode {
                   4733:     my $code=shift;
                   4734:     return $supported_language{$code};
1.97      www      4735: }
                   4736: 
1.112     bowersj2 4737: =pod
                   4738: 
1.1048    foxr     4739: =item * &latexlanguage()
                   4740: 
                   4741: Given a language key code returns the correspondnig language to use
                   4742: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4743: is no supported hyphenation for the language code.
                   4744: 
                   4745: =cut
                   4746: 
                   4747: sub latexlanguage {
                   4748:     my $code = shift;
                   4749:     return $latex_language{$code};
                   4750: }
                   4751: 
                   4752: =pod
                   4753: 
                   4754: =item * &latexhyphenation()
                   4755: 
                   4756: Same as above but what's supplied is the language as it might be stored
                   4757: in the metadata.
                   4758: 
                   4759: =cut
                   4760: 
                   4761: sub latexhyphenation {
                   4762:     my $key = shift;
                   4763:     return $latex_language_bykey{$key};
                   4764: }
                   4765: 
                   4766: =pod
                   4767: 
1.648     raeburn  4768: =item * &copyrightids() 
1.112     bowersj2 4769: 
                   4770: returns list of all copyrights
                   4771: 
                   4772: =cut
                   4773: 
                   4774: sub copyrightids {
                   4775:     return sort(keys(%cprtag));
                   4776: }
                   4777: 
                   4778: =pod
                   4779: 
1.648     raeburn  4780: =item * &copyrightdescription() 
1.112     bowersj2 4781: 
                   4782: returns description of a specified copyright id
                   4783: 
                   4784: =cut
                   4785: 
                   4786: sub copyrightdescription {
1.166     www      4787:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4788: }
1.197     matthew  4789: 
                   4790: =pod
                   4791: 
1.648     raeburn  4792: =item * &source_copyrightids() 
1.192     taceyjo1 4793: 
                   4794: returns list of all source copyrights
                   4795: 
                   4796: =cut
                   4797: 
                   4798: sub source_copyrightids {
                   4799:     return sort(keys(%scprtag));
                   4800: }
                   4801: 
                   4802: =pod
                   4803: 
1.648     raeburn  4804: =item * &source_copyrightdescription() 
1.192     taceyjo1 4805: 
                   4806: returns description of a specified source copyright id
                   4807: 
                   4808: =cut
                   4809: 
                   4810: sub source_copyrightdescription {
                   4811:     return &mt($scprtag{shift(@_)});
                   4812: }
1.112     bowersj2 4813: 
                   4814: =pod
                   4815: 
1.648     raeburn  4816: =item * &filecategories() 
1.112     bowersj2 4817: 
                   4818: returns list of all file categories
                   4819: 
                   4820: =cut
                   4821: 
                   4822: sub filecategories {
                   4823:     return sort(keys(%category_extensions));
                   4824: }
                   4825: 
                   4826: =pod
                   4827: 
1.648     raeburn  4828: =item * &filecategorytypes() 
1.112     bowersj2 4829: 
                   4830: returns list of file types belonging to a given file
                   4831: category
                   4832: 
                   4833: =cut
                   4834: 
                   4835: sub filecategorytypes {
1.356     albertel 4836:     my ($cat) = @_;
1.1248    raeburn  4837:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4838:         return @{$category_extensions{lc($cat)}};
                   4839:     } else {
                   4840:         return ();
                   4841:     }
1.112     bowersj2 4842: }
                   4843: 
                   4844: =pod
                   4845: 
1.648     raeburn  4846: =item * &fileembstyle() 
1.112     bowersj2 4847: 
                   4848: returns embedding style for a specified file type
                   4849: 
                   4850: =cut
                   4851: 
                   4852: sub fileembstyle {
                   4853:     return $fe{lc(shift(@_))};
1.169     www      4854: }
                   4855: 
1.351     www      4856: sub filemimetype {
                   4857:     return $fm{lc(shift(@_))};
                   4858: }
                   4859: 
1.169     www      4860: 
                   4861: sub filecategoryselect {
                   4862:     my ($name,$value)=@_;
1.189     matthew  4863:     return &select_form($value,$name,
1.970     raeburn  4864:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4865: }
                   4866: 
                   4867: =pod
                   4868: 
1.648     raeburn  4869: =item * &filedescription() 
1.112     bowersj2 4870: 
                   4871: returns description for a specified file type
                   4872: 
                   4873: =cut
                   4874: 
                   4875: sub filedescription {
1.188     matthew  4876:     my $file_description = $fd{lc(shift())};
                   4877:     $file_description =~ s:([\[\]]):~$1:g;
                   4878:     return &mt($file_description);
1.112     bowersj2 4879: }
                   4880: 
                   4881: =pod
                   4882: 
1.648     raeburn  4883: =item * &filedescriptionex() 
1.112     bowersj2 4884: 
                   4885: returns description for a specified file type with
                   4886: extra formatting
                   4887: 
                   4888: =cut
                   4889: 
                   4890: sub filedescriptionex {
                   4891:     my $ex=shift;
1.188     matthew  4892:     my $file_description = $fd{lc($ex)};
                   4893:     $file_description =~ s:([\[\]]):~$1:g;
                   4894:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4895: }
                   4896: 
                   4897: # End of .tab access
                   4898: =pod
                   4899: 
                   4900: =back
                   4901: 
                   4902: =cut
                   4903: 
                   4904: # ------------------------------------------------------------------ File Types
                   4905: sub fileextensions {
                   4906:     return sort(keys(%fe));
                   4907: }
                   4908: 
1.97      www      4909: # ----------------------------------------------------------- Display Languages
                   4910: # returns a hash with all desired display languages
                   4911: #
                   4912: 
                   4913: sub display_languages {
                   4914:     my %languages=();
1.695     raeburn  4915:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4916: 	$languages{$lang}=1;
1.97      www      4917:     }
                   4918:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4919:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4920: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4921: 	    $languages{$lang}=1;
1.97      www      4922:         }
                   4923:     }
                   4924:     return %languages;
1.14      harris41 4925: }
                   4926: 
1.582     albertel 4927: sub languages {
                   4928:     my ($possible_langs) = @_;
1.695     raeburn  4929:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4930:     if (!ref($possible_langs)) {
                   4931: 	if( wantarray ) {
                   4932: 	    return @preferred_langs;
                   4933: 	} else {
                   4934: 	    return $preferred_langs[0];
                   4935: 	}
                   4936:     }
                   4937:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4938:     my @preferred_possibilities;
                   4939:     foreach my $preferred_lang (@preferred_langs) {
                   4940: 	if (exists($possibilities{$preferred_lang})) {
                   4941: 	    push(@preferred_possibilities, $preferred_lang);
                   4942: 	}
                   4943:     }
                   4944:     if( wantarray ) {
                   4945: 	return @preferred_possibilities;
                   4946:     }
                   4947:     return $preferred_possibilities[0];
                   4948: }
                   4949: 
1.742     raeburn  4950: sub user_lang {
                   4951:     my ($touname,$toudom,$fromcid) = @_;
                   4952:     my @userlangs;
                   4953:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4954:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4955:                     $env{'course.'.$fromcid.'.languages'}));
                   4956:     } else {
                   4957:         my %langhash = &getlangs($touname,$toudom);
                   4958:         if ($langhash{'languages'} ne '') {
                   4959:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4960:         } else {
                   4961:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4962:             if ($domdefs{'lang_def'} ne '') {
                   4963:                 @userlangs = ($domdefs{'lang_def'});
                   4964:             }
                   4965:         }
                   4966:     }
                   4967:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4968:     my $user_lh = Apache::localize->get_handle(@languages);
                   4969:     return $user_lh;
                   4970: }
                   4971: 
                   4972: 
1.112     bowersj2 4973: ###############################################################
                   4974: ##               Student Answer Attempts                     ##
                   4975: ###############################################################
                   4976: 
                   4977: =pod
                   4978: 
                   4979: =head1 Alternate Problem Views
                   4980: 
                   4981: =over 4
                   4982: 
1.648     raeburn  4983: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4984:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4985: 
                   4986: Return string with previous attempt on problem. Arguments:
                   4987: 
                   4988: =over 4
                   4989: 
                   4990: =item * $symb: Problem, including path
                   4991: 
                   4992: =item * $username: username of the desired student
                   4993: 
                   4994: =item * $domain: domain of the desired student
1.14      harris41 4995: 
1.112     bowersj2 4996: =item * $course: Course ID
1.14      harris41 4997: 
1.112     bowersj2 4998: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4999:     something
1.14      harris41 5000: 
1.112     bowersj2 5001: =item * $regexp: if string matches this regexp, the string will be
                   5002:     sent to $gradesub
1.14      harris41 5003: 
1.112     bowersj2 5004: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 5005: 
1.1199    raeburn  5006: =item * $usec: section of the desired student
                   5007: 
                   5008: =item * $identifier: counter for student (multiple students one problem) or 
                   5009:     problem (one student; whole sequence).
                   5010: 
1.112     bowersj2 5011: =back
1.14      harris41 5012: 
1.112     bowersj2 5013: The output string is a table containing all desired attempts, if any.
1.16      harris41 5014: 
1.112     bowersj2 5015: =cut
1.1       albertel 5016: 
                   5017: sub get_previous_attempt {
1.1199    raeburn  5018:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 5019:   my $prevattempts='';
1.43      ng       5020:   no strict 'refs';
1.1       albertel 5021:   if ($symb) {
1.3       albertel 5022:     my (%returnhash)=
                   5023:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 5024:     if ($returnhash{'version'}) {
                   5025:       my %lasthash=();
                   5026:       my $version;
                   5027:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  5028:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   5029:             if ($key =~ /\.rawrndseed$/) {
                   5030:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   5031:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   5032:             } else {
                   5033:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   5034:             }
1.19      harris41 5035:         }
1.1       albertel 5036:       }
1.596     albertel 5037:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   5038:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  5039:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  5040:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 5041:       foreach my $key (sort(keys(%lasthash))) {
                   5042: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       5043: 	if ($#parts > 0) {
1.31      albertel 5044: 	  my $data=$parts[-1];
1.989     raeburn  5045:           next if ($data eq 'foilorder');
1.31      albertel 5046: 	  pop(@parts);
1.1010    www      5047:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  5048:           if ($data eq 'type') {
                   5049:               unless ($showsurv) {
                   5050:                   my $id = join(',',@parts);
                   5051:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  5052:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   5053:                       $lasthidden{$ign.'.'.$id} = 1;
                   5054:                   }
1.945     raeburn  5055:               }
1.1199    raeburn  5056:               if ($identifier ne '') {
                   5057:                   my $id = join(',',@parts);
                   5058:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   5059:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   5060:                       $hidestatus{$ign.'.'.$id} = 1;
                   5061:                   }
                   5062:               }
                   5063:           } elsif ($data eq 'regrader') {
                   5064:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  5065:                   my $id = join(',',@parts);
                   5066:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  5067:               }
1.1010    www      5068:           } 
1.31      albertel 5069: 	} else {
1.41      ng       5070: 	  if ($#parts == 0) {
                   5071: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   5072: 	  } else {
                   5073: 	    $prevattempts.='<th>'.$ign.'</th>';
                   5074: 	  }
1.31      albertel 5075: 	}
1.16      harris41 5076:       }
1.596     albertel 5077:       $prevattempts.=&end_data_table_header_row();
1.40      ng       5078:       if ($getattempt eq '') {
1.1199    raeburn  5079:         my (%solved,%resets,%probstatus);
1.1200    raeburn  5080:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   5081:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   5082:                 foreach my $id (keys(%regraded)) {
                   5083:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   5084:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   5085:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   5086:                         push(@{$resets{$id}},$version);
1.1199    raeburn  5087:                     }
                   5088:                 }
                   5089:             }
1.1200    raeburn  5090:         }
                   5091: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  5092:             my (@hidden,@unsolved);
1.945     raeburn  5093:             if (%typeparts) {
                   5094:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  5095:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   5096:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  5097:                         push(@hidden,$id);
1.1199    raeburn  5098:                     } elsif ($identifier ne '') {
                   5099:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   5100:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   5101:                                 ($hidestatus{$id})) {
1.1200    raeburn  5102:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  5103:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   5104:                                 push(@{$solved{$id}},$version);
                   5105:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   5106:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   5107:                                 my $skip;
                   5108:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   5109:                                     foreach my $reset (@{$resets{$id}}) {
                   5110:                                         if ($reset > $solved{$id}[-1]) {
                   5111:                                             $skip=1;
                   5112:                                             last;
                   5113:                                         }
                   5114:                                     }
                   5115:                                 }
                   5116:                                 unless ($skip) {
                   5117:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   5118:                                     push(@unsolved,$partslist);
                   5119:                                 }
                   5120:                             }
                   5121:                         }
1.945     raeburn  5122:                     }
                   5123:                 }
                   5124:             }
                   5125:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  5126:                            '<td>'.&mt('Transaction [_1]',$version);
                   5127:             if (@unsolved) {
                   5128:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   5129:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   5130:                                  &mt('Hide').'</label></span>';
                   5131:             }
                   5132:             $prevattempts .= '</td>';
1.945     raeburn  5133:             if (@hidden) {
                   5134:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5135:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  5136:                     my $hide;
                   5137:                     foreach my $id (@hidden) {
                   5138:                         if ($key =~ /^\Q$id\E/) {
                   5139:                             $hide = 1;
                   5140:                             last;
                   5141:                         }
                   5142:                     }
                   5143:                     if ($hide) {
                   5144:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5145:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5146:                             my $value = &format_previous_attempt_value($key,
                   5147:                                              $returnhash{$version.':'.$key});
1.1173    kruse    5148:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5149:                         } else {
                   5150:                             $prevattempts.='<td>&nbsp;</td>';
                   5151:                         }
                   5152:                     } else {
                   5153:                         if ($key =~ /\./) {
1.1212    raeburn  5154:                             my $value = $returnhash{$version.':'.$key};
                   5155:                             if ($key =~ /\.rndseed$/) {
                   5156:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5157:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5158:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5159:                                 }
                   5160:                             }
                   5161:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5162:                                            '&nbsp;</td>';
1.945     raeburn  5163:                         } else {
                   5164:                             $prevattempts.='<td>&nbsp;</td>';
                   5165:                         }
                   5166:                     }
                   5167:                 }
                   5168:             } else {
                   5169: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5170:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  5171:                     my $value = $returnhash{$version.':'.$key};
                   5172:                     if ($key =~ /\.rndseed$/) {
                   5173:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5174:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5175:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5176:                         }
                   5177:                     }
                   5178:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5179:                                    '&nbsp;</td>';
1.945     raeburn  5180: 	        }
                   5181:             }
                   5182: 	    $prevattempts.=&end_data_table_row();
1.40      ng       5183: 	 }
1.1       albertel 5184:       }
1.945     raeburn  5185:       my @currhidden = keys(%lasthidden);
1.596     albertel 5186:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 5187:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5188:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  5189:           if (%typeparts) {
                   5190:               my $hidden;
                   5191:               foreach my $id (@currhidden) {
                   5192:                   if ($key =~ /^\Q$id\E/) {
                   5193:                       $hidden = 1;
                   5194:                       last;
                   5195:                   }
                   5196:               }
                   5197:               if ($hidden) {
                   5198:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5199:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5200:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5201:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5202:                           $value = &$gradesub($value);
                   5203:                       }
1.1173    kruse    5204:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  5205:                   } else {
                   5206:                       $prevattempts.='<td>&nbsp;</td>';
                   5207:                   }
                   5208:               } else {
                   5209:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5210:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5211:                       $value = &$gradesub($value);
                   5212:                   }
1.1173    kruse    5213:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5214:               }
                   5215:           } else {
                   5216: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5217: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5218:                   $value = &$gradesub($value);
                   5219:               }
1.1173    kruse    5220: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5221:           }
1.16      harris41 5222:       }
1.596     albertel 5223:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 5224:     } else {
1.1305    raeburn  5225:       my $msg;
                   5226:       if ($symb =~ /ext\.tool$/) {
                   5227:           $msg = &mt('No grade passed back.');
                   5228:       } else {
                   5229:           $msg = &mt('Nothing submitted - no attempts.');
                   5230:       }
1.596     albertel 5231:       $prevattempts=
                   5232: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  5233: 	  '<td>'.$msg.'</td>'.
1.596     albertel 5234: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5235:     }
                   5236:   } else {
1.596     albertel 5237:     $prevattempts=
                   5238: 	  &start_data_table().&start_data_table_row().
                   5239: 	  '<td>'.&mt('No data.').'</td>'.
                   5240: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5241:   }
1.10      albertel 5242: }
                   5243: 
1.581     albertel 5244: sub format_previous_attempt_value {
                   5245:     my ($key,$value) = @_;
1.1011    www      5246:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    5247:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 5248:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    5249:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  5250:     } elsif ($key =~ /answerstring$/) {
                   5251:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    5252:         my @answer = %answers;
                   5253:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  5254:         my @anskeys = sort(keys(%answers));
                   5255:         if (@anskeys == 1) {
                   5256:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  5257:             if ($answer =~ m{\0}) {
                   5258:                 $answer =~ s{\0}{,}g;
1.988     raeburn  5259:             }
                   5260:             my $tag_internal_answer_name = 'INTERNAL';
                   5261:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   5262:                 $value = $answer; 
                   5263:             } else {
                   5264:                 $value = $anskeys[0].'='.$answer;
                   5265:             }
                   5266:         } else {
                   5267:             foreach my $ans (@anskeys) {
                   5268:                 my $answer = $answers{$ans};
1.1001    raeburn  5269:                 if ($answer =~ m{\0}) {
                   5270:                     $answer =~ s{\0}{,}g;
1.988     raeburn  5271:                 }
                   5272:                 $value .=  $ans.'='.$answer.'<br />';;
                   5273:             } 
                   5274:         }
1.581     albertel 5275:     } else {
1.1173    kruse    5276:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 5277:     }
                   5278:     return $value;
                   5279: }
                   5280: 
                   5281: 
1.107     albertel 5282: sub relative_to_absolute {
                   5283:     my ($url,$output)=@_;
                   5284:     my $parser=HTML::TokeParser->new(\$output);
                   5285:     my $token;
                   5286:     my $thisdir=$url;
                   5287:     my @rlinks=();
                   5288:     while ($token=$parser->get_token) {
                   5289: 	if ($token->[0] eq 'S') {
                   5290: 	    if ($token->[1] eq 'a') {
                   5291: 		if ($token->[2]->{'href'}) {
                   5292: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   5293: 		}
                   5294: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   5295: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   5296: 	    } elsif ($token->[1] eq 'base') {
                   5297: 		$thisdir=$token->[2]->{'href'};
                   5298: 	    }
                   5299: 	}
                   5300:     }
                   5301:     $thisdir=~s-/[^/]*$--;
1.356     albertel 5302:     foreach my $link (@rlinks) {
1.726     raeburn  5303: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 5304: 		($link=~/^\//) ||
                   5305: 		($link=~/^javascript:/i) ||
                   5306: 		($link=~/^mailto:/i) ||
                   5307: 		($link=~/^\#/)) {
                   5308: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   5309: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 5310: 	}
                   5311:     }
                   5312: # -------------------------------------------------- Deal with Applet codebases
                   5313:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   5314:     return $output;
                   5315: }
                   5316: 
1.112     bowersj2 5317: =pod
                   5318: 
1.648     raeburn  5319: =item * &get_student_view()
1.112     bowersj2 5320: 
                   5321: show a snapshot of what student was looking at
                   5322: 
                   5323: =cut
                   5324: 
1.10      albertel 5325: sub get_student_view {
1.186     albertel 5326:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      5327:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5328:   my (%form);
1.10      albertel 5329:   my @elements=('symb','courseid','domain','username');
                   5330:   foreach my $element (@elements) {
1.186     albertel 5331:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5332:   }
1.186     albertel 5333:   if (defined($moreenv)) {
                   5334:       %form=(%form,%{$moreenv});
                   5335:   }
1.236     albertel 5336:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 5337:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  5338:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   5339:       $feedurl =~ s{^/adm/wrapper}{};
                   5340:   }
1.650     www      5341:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5342:   $userview=~s/\<body[^\>]*\>//gi;
                   5343:   $userview=~s/\<\/body\>//gi;
                   5344:   $userview=~s/\<html\>//gi;
                   5345:   $userview=~s/\<\/html\>//gi;
                   5346:   $userview=~s/\<head\>//gi;
                   5347:   $userview=~s/\<\/head\>//gi;
                   5348:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5349:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5350:   if (wantarray) {
                   5351:      return ($userview,$response);
                   5352:   } else {
                   5353:      return $userview;
                   5354:   }
                   5355: }
                   5356: 
                   5357: sub get_student_view_with_retries {
                   5358:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5359: 
                   5360:     my $ok = 0;                 # True if we got a good response.
                   5361:     my $content;
                   5362:     my $response;
                   5363: 
                   5364:     # Try to get the student_view done. within the retries count:
                   5365:     
                   5366:     do {
                   5367:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5368:          $ok      = $response->is_success;
                   5369:          if (!$ok) {
                   5370:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5371:          }
                   5372:          $retries--;
                   5373:     } while (!$ok && ($retries > 0));
                   5374:     
                   5375:     if (!$ok) {
                   5376:        $content = '';          # On error return an empty content.
                   5377:     }
1.651     www      5378:     if (wantarray) {
                   5379:        return ($content, $response);
                   5380:     } else {
                   5381:        return $content;
                   5382:     }
1.11      albertel 5383: }
                   5384: 
1.1349    raeburn  5385: sub css_links {
                   5386:     my ($currsymb,$level) = @_;
                   5387:     my ($links,@symbs,%cssrefs,%httpref);
                   5388:     if ($level eq 'map') {
                   5389:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5390:         if (ref($navmap)) {
                   5391:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5392:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5393:             foreach my $res (@resources) {
                   5394:                 if (ref($res) && $res->symb()) {
                   5395:                     push(@symbs,$res->symb());
                   5396:                 }
                   5397:             }
                   5398:         }
                   5399:     } else {
                   5400:         @symbs = ($currsymb);
                   5401:     }
                   5402:     foreach my $symb (@symbs) {
                   5403:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5404:         if ($css_href =~ /\S/) {
                   5405:             unless ($css_href =~ m{https?://}) {
                   5406:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5407:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5408:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5409:                 unless ($css_href =~ m{^/}) {
                   5410:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5411:                 }
                   5412:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5413:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5414:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5415:                         my $thisurl = $proburl;
                   5416:                         if ($env{'httpref.'.$proburl}) {
                   5417:                             $thisurl = $env{'httpref.'.$proburl};
                   5418:                         }
                   5419:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5420:                     }
                   5421:                 }
                   5422:             }
                   5423:             $cssrefs{$css_href} = 1;
                   5424:         }
                   5425:     }
                   5426:     if (keys(%httpref)) {
                   5427:         &Apache::lonnet::appenv(\%httpref);
                   5428:     }
                   5429:     if (keys(%cssrefs)) {
                   5430:         foreach my $css_href (keys(%cssrefs)) {
                   5431:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5432:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5433:         }
                   5434:     }
                   5435:     return $links;
                   5436: }
                   5437: 
1.112     bowersj2 5438: =pod
                   5439: 
1.648     raeburn  5440: =item * &get_student_answers() 
1.112     bowersj2 5441: 
                   5442: show a snapshot of how student was answering problem
                   5443: 
                   5444: =cut
                   5445: 
1.11      albertel 5446: sub get_student_answers {
1.100     sakharuk 5447:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5448:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5449:   my (%moreenv);
1.11      albertel 5450:   my @elements=('symb','courseid','domain','username');
                   5451:   foreach my $element (@elements) {
1.186     albertel 5452:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5453:   }
1.186     albertel 5454:   $moreenv{'grade_target'}='answer';
                   5455:   %moreenv=(%form,%moreenv);
1.497     raeburn  5456:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5457:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5458:   return $userview;
1.1       albertel 5459: }
1.116     albertel 5460: 
                   5461: =pod
                   5462: 
                   5463: =item * &submlink()
                   5464: 
1.242     albertel 5465: Inputs: $text $uname $udom $symb $target
1.116     albertel 5466: 
                   5467: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5468: 
                   5469: =cut
                   5470: 
                   5471: ###############################################
                   5472: sub submlink {
1.242     albertel 5473:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5474:     if (!($uname && $udom)) {
                   5475: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5476: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5477: 	if (!$symb) { $symb=$cursymb; }
                   5478:     }
1.254     matthew  5479:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5480:     $symb=&escape($symb);
1.960     bisitz   5481:     if ($target) { $target=" target=\"$target\""; }
                   5482:     return
                   5483:         '<a href="/adm/grades?command=submission'.
                   5484:         '&amp;symb='.$symb.
                   5485:         '&amp;student='.$uname.
                   5486:         '&amp;userdom='.$udom.'"'.
                   5487:         $target.'>'.$text.'</a>';
1.242     albertel 5488: }
                   5489: ##############################################
                   5490: 
                   5491: =pod
                   5492: 
                   5493: =item * &pgrdlink()
                   5494: 
                   5495: Inputs: $text $uname $udom $symb $target
                   5496: 
                   5497: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5498: 
                   5499: =cut
                   5500: 
                   5501: ###############################################
                   5502: sub pgrdlink {
                   5503:     my $link=&submlink(@_);
                   5504:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5505:     return $link;
                   5506: }
                   5507: ##############################################
                   5508: 
                   5509: =pod
                   5510: 
                   5511: =item * &pprmlink()
                   5512: 
                   5513: Inputs: $text $uname $udom $symb $target
                   5514: 
                   5515: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5516: student and a specific resource
1.242     albertel 5517: 
                   5518: =cut
                   5519: 
                   5520: ###############################################
                   5521: sub pprmlink {
                   5522:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5523:     if (!($uname && $udom)) {
                   5524: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5525: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5526: 	if (!$symb) { $symb=$cursymb; }
                   5527:     }
1.254     matthew  5528:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5529:     $symb=&escape($symb);
1.242     albertel 5530:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5531:     return '<a href="/adm/parmset?command=set&amp;'.
                   5532: 	'symb='.$symb.'&amp;uname='.$uname.
                   5533: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5534: }
                   5535: ##############################################
1.37      matthew  5536: 
1.112     bowersj2 5537: =pod
                   5538: 
                   5539: =back
                   5540: 
                   5541: =cut
                   5542: 
1.37      matthew  5543: ###############################################
1.51      www      5544: 
                   5545: 
                   5546: sub timehash {
1.687     raeburn  5547:     my ($thistime) = @_;
                   5548:     my $timezone = &Apache::lonlocal::gettimezone();
                   5549:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5550:                      ->set_time_zone($timezone);
                   5551:     my $wday = $dt->day_of_week();
                   5552:     if ($wday == 7) { $wday = 0; }
                   5553:     return ( 'second' => $dt->second(),
                   5554:              'minute' => $dt->minute(),
                   5555:              'hour'   => $dt->hour(),
                   5556:              'day'     => $dt->day_of_month(),
                   5557:              'month'   => $dt->month(),
                   5558:              'year'    => $dt->year(),
                   5559:              'weekday' => $wday,
                   5560:              'dayyear' => $dt->day_of_year(),
                   5561:              'dlsav'   => $dt->is_dst() );
1.51      www      5562: }
                   5563: 
1.370     www      5564: sub utc_string {
                   5565:     my ($date)=@_;
1.371     www      5566:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5567: }
                   5568: 
1.51      www      5569: sub maketime {
                   5570:     my %th=@_;
1.687     raeburn  5571:     my ($epoch_time,$timezone,$dt);
                   5572:     $timezone = &Apache::lonlocal::gettimezone();
                   5573:     eval {
                   5574:         $dt = DateTime->new( year   => $th{'year'},
                   5575:                              month  => $th{'month'},
                   5576:                              day    => $th{'day'},
                   5577:                              hour   => $th{'hour'},
                   5578:                              minute => $th{'minute'},
                   5579:                              second => $th{'second'},
                   5580:                              time_zone => $timezone,
                   5581:                          );
                   5582:     };
                   5583:     if (!$@) {
                   5584:         $epoch_time = $dt->epoch;
                   5585:         if ($epoch_time) {
                   5586:             return $epoch_time;
                   5587:         }
                   5588:     }
1.51      www      5589:     return POSIX::mktime(
                   5590:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5591:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5592: }
                   5593: 
                   5594: #########################################
1.51      www      5595: 
                   5596: sub findallcourses {
1.482     raeburn  5597:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5598:     my %roles;
                   5599:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5600:     my %courses;
1.51      www      5601:     my $now=time;
1.482     raeburn  5602:     if (!defined($uname)) {
                   5603:         $uname = $env{'user.name'};
                   5604:     }
                   5605:     if (!defined($udom)) {
                   5606:         $udom = $env{'user.domain'};
                   5607:     }
                   5608:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5609:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5610:         if (!%roles) {
                   5611:             %roles = (
                   5612:                        cc => 1,
1.907     raeburn  5613:                        co => 1,
1.482     raeburn  5614:                        in => 1,
                   5615:                        ep => 1,
                   5616:                        ta => 1,
                   5617:                        cr => 1,
                   5618:                        st => 1,
                   5619:              );
                   5620:         }
                   5621:         foreach my $entry (keys(%roleshash)) {
                   5622:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5623:             if ($trole =~ /^cr/) { 
                   5624:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5625:             } else {
                   5626:                 next if (!exists($roles{$trole}));
                   5627:             }
                   5628:             if ($tend) {
                   5629:                 next if ($tend < $now);
                   5630:             }
                   5631:             if ($tstart) {
                   5632:                 next if ($tstart > $now);
                   5633:             }
1.1058    raeburn  5634:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5635:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5636:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5637:             if ($secpart eq '') {
                   5638:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5639:                 $sec = 'none';
1.1058    raeburn  5640:                 $value .= $cnum.'/';
1.482     raeburn  5641:             } else {
                   5642:                 $cnum = $cnumpart;
                   5643:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5644:                 $value .= $cnum.'/'.$sec;
                   5645:             }
                   5646:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5647:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5648:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5649:                 }
                   5650:             } else {
                   5651:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5652:             }
1.482     raeburn  5653:         }
                   5654:     } else {
                   5655:         foreach my $key (keys(%env)) {
1.483     albertel 5656: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5657:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5658: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5659: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5660: 	        next if (%roles && !exists($roles{$role}));
                   5661: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5662:                 my $active=1;
                   5663:                 if ($starttime) {
                   5664: 		    if ($now<$starttime) { $active=0; }
                   5665:                 }
                   5666:                 if ($endtime) {
                   5667:                     if ($now>$endtime) { $active=0; }
                   5668:                 }
                   5669:                 if ($active) {
1.1058    raeburn  5670:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5671:                     if ($sec eq '') {
                   5672:                         $sec = 'none';
1.1058    raeburn  5673:                     } else {
                   5674:                         $value .= $sec;
                   5675:                     }
                   5676:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5677:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5678:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5679:                         }
                   5680:                     } else {
                   5681:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5682:                     }
1.474     raeburn  5683:                 }
                   5684:             }
1.51      www      5685:         }
                   5686:     }
1.474     raeburn  5687:     return %courses;
1.51      www      5688: }
1.37      matthew  5689: 
1.54      www      5690: ###############################################
1.474     raeburn  5691: 
                   5692: sub blockcheck {
1.1372    raeburn  5693:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5694:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5695:         my ($has_evb,$check_ipaccess);
                   5696:         my $dom = $env{'user.domain'};
                   5697:         if ($env{'request.course.id'}) {
                   5698:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5699:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5700:             my $checkrole = "cm./$cdom/$cnum";
                   5701:             my $sec = $env{'request.course.sec'};
                   5702:             if ($sec ne '') {
                   5703:                 $checkrole .= "/$sec";
                   5704:             }
                   5705:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5706:                 ($env{'request.role'} !~ /^st/)) {
                   5707:                 $has_evb = 1;
                   5708:             }
                   5709:             unless ($has_evb) {
                   5710:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
1.1444    raeburn  5711:                     ($activity eq 'index') || ($activity eq 'boards') || ($activity eq 'groups') || 
                   5712:                     ($activity eq 'chat')) {
1.1372    raeburn  5713:                     if ($udom eq $cdom) {
                   5714:                         $check_ipaccess = 1;
                   5715:                     }
                   5716:                 }
                   5717:             }
1.1375    raeburn  5718:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5719:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5720:             my $checkrole;
                   5721:             if ($env{'request.role.domain'} eq '') {
                   5722:                 $checkrole = "cm./$env{'user.domain'}/";
                   5723:             } else {
                   5724:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5725:             }
                   5726:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5727:                 $has_evb = 1;
                   5728:             }
1.1372    raeburn  5729:         }
                   5730:         unless ($has_evb || $check_ipaccess) {
                   5731:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5732:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5733:                 $dom = $udom;
                   5734:             }
                   5735:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5736:                 $check_ipaccess = 1;
                   5737:             } else {
                   5738:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5739:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5740:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5741:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5742:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5743:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5744:                         $check_ipaccess = 1;
                   5745:                     }
                   5746:                 }
                   5747:             }
                   5748:         }
                   5749:         if ($check_ipaccess) {
                   5750:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5751:             unless (defined($cached)) {
                   5752:                 my %domconfig =
                   5753:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5754:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5755:             }
                   5756:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5757:                 foreach my $id (keys(%{$ipaccessref})) {
                   5758:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5759:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5760:                         if ($range) {
                   5761:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5762:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5763:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5764:                                         return ('','','',$id,$dom);
                   5765:                                         last;
                   5766:                                     }
                   5767:                                 }
                   5768:                             }
                   5769:                         }
                   5770:                     }
                   5771:                 }
                   5772:             }
                   5773:         }
1.1373    raeburn  5774:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5775:             return ();
                   5776:         }
1.1372    raeburn  5777:     }
1.1189    raeburn  5778:     if (defined($udom) && defined($uname)) {
                   5779:         # If uname and udom are for a course, check for blocks in the course.
                   5780:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5781:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5782:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5783:             return ($startblock,$endblock,$triggerblock);
                   5784:         }
                   5785:     } else {
1.490     raeburn  5786:         $udom = $env{'user.domain'};
                   5787:         $uname = $env{'user.name'};
                   5788:     }
                   5789: 
1.502     raeburn  5790:     my $startblock = 0;
                   5791:     my $endblock = 0;
1.1062    raeburn  5792:     my $triggerblock = '';
1.1373    raeburn  5793:     my %live_courses;
                   5794:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5795:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5796:     }
1.474     raeburn  5797: 
1.490     raeburn  5798:     # If uname is for a user, and activity is course-specific, i.e.,
                   5799:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5800: 
1.490     raeburn  5801:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5802:          $activity eq 'groups' || $activity eq 'printout' ||
1.1444    raeburn  5803:          $activity eq 'search' || $activity eq 'index' ||
                   5804:          $activity eq 'reinit' || $activity eq 'alert') &&
1.1189    raeburn  5805:         ($env{'request.course.id'})) {
1.490     raeburn  5806:         foreach my $key (keys(%live_courses)) {
                   5807:             if ($key ne $env{'request.course.id'}) {
                   5808:                 delete($live_courses{$key});
                   5809:             }
                   5810:         }
                   5811:     }
                   5812: 
                   5813:     my $otheruser = 0;
                   5814:     my %own_courses;
                   5815:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5816:         # Resource belongs to user other than current user.
                   5817:         $otheruser = 1;
                   5818:         # Gather courses for current user
                   5819:         %own_courses = 
                   5820:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5821:     }
                   5822: 
                   5823:     # Gather active course roles - course coordinator, instructor, 
                   5824:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5825: 
                   5826:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5827:         my ($cdom,$cnum);
                   5828:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5829:             $cdom = $env{'course.'.$course.'.domain'};
                   5830:             $cnum = $env{'course.'.$course.'.num'};
                   5831:         } else {
1.490     raeburn  5832:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5833:         }
                   5834:         my $no_ownblock = 0;
                   5835:         my $no_userblock = 0;
1.533     raeburn  5836:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5837:             # Check if current user has 'evb' priv for this
                   5838:             if (defined($own_courses{$course})) {
                   5839:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5840:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5841:                     if ($sec ne 'none') {
                   5842:                         $checkrole .= '/'.$sec;
                   5843:                     }
                   5844:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5845:                         $no_ownblock = 1;
                   5846:                         last;
                   5847:                     }
                   5848:                 }
                   5849:             }
                   5850:             # if they have 'evb' priv and are currently not playing student
                   5851:             next if (($no_ownblock) &&
                   5852:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5853:         }
1.474     raeburn  5854:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5855:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5856:             if ($sec ne 'none') {
1.482     raeburn  5857:                 $checkrole .= '/'.$sec;
1.474     raeburn  5858:             }
1.490     raeburn  5859:             if ($otheruser) {
                   5860:                 # Resource belongs to user other than current user.
                   5861:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5862:                 my (%allroles,%userroles);
                   5863:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5864:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5865:                         my ($trole,$tdom,$tnum,$tsec);
                   5866:                         if ($entry =~ /^cr/) {
                   5867:                             ($trole,$tdom,$tnum,$tsec) = 
                   5868:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5869:                         } else {
                   5870:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5871:                         }
                   5872:                         my ($spec,$area,$trest);
                   5873:                         $area = '/'.$tdom.'/'.$tnum;
                   5874:                         $trest = $tnum;
                   5875:                         if ($tsec ne '') {
                   5876:                             $area .= '/'.$tsec;
                   5877:                             $trest .= '/'.$tsec;
                   5878:                         }
                   5879:                         $spec = $trole.'.'.$area;
                   5880:                         if ($trole =~ /^cr/) {
                   5881:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5882:                                                               $tdom,$spec,$trest,$area);
                   5883:                         } else {
                   5884:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5885:                                                                 $tdom,$spec,$trest,$area);
                   5886:                         }
                   5887:                     }
1.1276    raeburn  5888:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5889:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5890:                         if ($1) {
                   5891:                             $no_userblock = 1;
                   5892:                             last;
                   5893:                         }
1.486     raeburn  5894:                     }
                   5895:                 }
1.490     raeburn  5896:             } else {
                   5897:                 # Resource belongs to current user
                   5898:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5899:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5900:                     $no_ownblock = 1;
                   5901:                     last;
                   5902:                 }
1.474     raeburn  5903:             }
                   5904:         }
                   5905:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5906:         next if (($no_ownblock) &&
1.491     albertel 5907:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5908:         next if ($no_userblock);
1.474     raeburn  5909: 
1.1303    raeburn  5910:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5911:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5912: 
1.1062    raeburn  5913:         my ($start,$end,$trigger) = 
1.1347    raeburn  5914:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5915:         if (($start != 0) && 
                   5916:             (($startblock == 0) || ($startblock > $start))) {
                   5917:             $startblock = $start;
1.1062    raeburn  5918:             if ($trigger ne '') {
                   5919:                 $triggerblock = $trigger;
                   5920:             }
1.502     raeburn  5921:         }
                   5922:         if (($end != 0)  &&
                   5923:             (($endblock == 0) || ($endblock < $end))) {
                   5924:             $endblock = $end;
1.1062    raeburn  5925:             if ($trigger ne '') {
                   5926:                 $triggerblock = $trigger;
                   5927:             }
1.502     raeburn  5928:         }
1.490     raeburn  5929:     }
1.1062    raeburn  5930:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5931: }
                   5932: 
                   5933: sub get_blocks {
1.1347    raeburn  5934:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5935:     my $startblock = 0;
                   5936:     my $endblock = 0;
1.1062    raeburn  5937:     my $triggerblock = '';
1.490     raeburn  5938:     my $course = $cdom.'_'.$cnum;
                   5939:     $setters->{$course} = {};
                   5940:     $setters->{$course}{'staff'} = [];
                   5941:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5942:     $setters->{$course}{'triggers'} = [];
                   5943:     my (@blockers,%triggered);
                   5944:     my $now = time;
                   5945:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5946:     if ($activity eq 'docs') {
1.1348    raeburn  5947:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5948:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5949:             $blocked = 1;
                   5950:             $nosymbcache = 1;
1.1348    raeburn  5951:             $noenccheck = 1;
1.1347    raeburn  5952:         }
1.1348    raeburn  5953:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5954:         foreach my $block (@blockers) {
                   5955:             if ($block =~ /^firstaccess____(.+)$/) {
                   5956:                 my $item = $1;
                   5957:                 my $type = 'map';
                   5958:                 my $timersymb = $item;
                   5959:                 if ($item eq 'course') {
                   5960:                     $type = 'course';
                   5961:                 } elsif ($item =~ /___\d+___/) {
                   5962:                     $type = 'resource';
                   5963:                 } else {
                   5964:                     $timersymb = &Apache::lonnet::symbread($item);
                   5965:                 }
                   5966:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5967:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5968:                 $triggered{$block} = {
                   5969:                                        start => $start,
                   5970:                                        end   => $end,
                   5971:                                        type  => $type,
                   5972:                                      };
                   5973:             }
                   5974:         }
                   5975:     } else {
                   5976:         foreach my $block (keys(%commblocks)) {
                   5977:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5978:                 my ($start,$end) = ($1,$2);
                   5979:                 if ($start <= time && $end >= time) {
                   5980:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5981:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5982:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5983:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5984:                                     push(@blockers,$block);
                   5985:                                 }
                   5986:                             }
                   5987:                         }
                   5988:                     }
                   5989:                 }
                   5990:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5991:                 my $item = $1;
                   5992:                 my $timersymb = $item; 
                   5993:                 my $type = 'map';
                   5994:                 if ($item eq 'course') {
                   5995:                     $type = 'course';
                   5996:                 } elsif ($item =~ /___\d+___/) {
                   5997:                     $type = 'resource';
                   5998:                 } else {
                   5999:                     $timersymb = &Apache::lonnet::symbread($item);
                   6000:                 }
                   6001:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   6002:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   6003:                 if ($start && $end) {
                   6004:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  6005:                         if (ref($commblocks{$block}) eq 'HASH') {
                   6006:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6007:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   6008:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   6009:                                         push(@blockers,$block);
                   6010:                                         $triggered{$block} = {
                   6011:                                                                start => $start,
                   6012:                                                                end   => $end,
                   6013:                                                                type  => $type,
                   6014:                                                              };
                   6015:                                     }
                   6016:                                 }
                   6017:                             }
1.1062    raeburn  6018:                         }
                   6019:                     }
1.490     raeburn  6020:                 }
1.1062    raeburn  6021:             }
                   6022:         }
                   6023:     }
                   6024:     foreach my $blocker (@blockers) {
                   6025:         my ($staff_name,$staff_dom,$title,$blocks) =
                   6026:             &parse_block_record($commblocks{$blocker});
                   6027:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   6028:         my ($start,$end,$triggertype);
                   6029:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   6030:             ($start,$end) = ($1,$2);
                   6031:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   6032:             $start = $triggered{$blocker}{'start'};
                   6033:             $end = $triggered{$blocker}{'end'};
                   6034:             $triggertype = $triggered{$blocker}{'type'};
                   6035:         }
                   6036:         if ($start) {
                   6037:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   6038:             if ($triggertype) {
                   6039:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   6040:             } else {
                   6041:                 push(@{$$setters{$course}{'triggers'}},0);
                   6042:             }
                   6043:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   6044:                 $startblock = $start;
                   6045:                 if ($triggertype) {
                   6046:                     $triggerblock = $blocker;
1.474     raeburn  6047:                 }
                   6048:             }
1.1062    raeburn  6049:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   6050:                $endblock = $end;
                   6051:                if ($triggertype) {
                   6052:                    $triggerblock = $blocker;
                   6053:                }
                   6054:             }
1.474     raeburn  6055:         }
                   6056:     }
1.1062    raeburn  6057:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  6058: }
                   6059: 
                   6060: sub parse_block_record {
                   6061:     my ($record) = @_;
                   6062:     my ($setuname,$setudom,$title,$blocks);
                   6063:     if (ref($record) eq 'HASH') {
                   6064:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   6065:         $title = &unescape($record->{'event'});
                   6066:         $blocks = $record->{'blocks'};
                   6067:     } else {
                   6068:         my @data = split(/:/,$record,3);
                   6069:         if (scalar(@data) eq 2) {
                   6070:             $title = $data[1];
                   6071:             ($setuname,$setudom) = split(/@/,$data[0]);
                   6072:         } else {
                   6073:             ($setuname,$setudom,$title) = @data;
                   6074:         }
                   6075:         $blocks = { 'com' => 'on' };
                   6076:     }
                   6077:     return ($setuname,$setudom,$title,$blocks);
                   6078: }
                   6079: 
1.854     kalberla 6080: sub blocking_status {
1.1372    raeburn  6081:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  6082:     my %setters;
1.890     droeschl 6083: 
1.1061    raeburn  6084: # check for active blocking
1.1372    raeburn  6085:     if ($clientip eq '') {
                   6086:         $clientip = &Apache::lonnet::get_requestor_ip();
                   6087:     }
                   6088:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   6089:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  6090:     my $blocked = 0;
1.1372    raeburn  6091:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  6092:         $blocked = 1;
                   6093:     }
1.890     droeschl 6094: 
1.1061    raeburn  6095: # caller just wants to know whether a block is active
                   6096:     if (!wantarray) { return $blocked; }
                   6097: 
                   6098: # build a link to a popup window containing the details
                   6099:     my $querystring  = "?activity=$activity";
1.1351    raeburn  6100: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   6101:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  6102:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   6103:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  6104:     } elsif ($activity eq 'docs') {
1.1347    raeburn  6105:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   6106:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   6107:         if ($symb) {
                   6108:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   6109:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   6110:         }
1.1062    raeburn  6111:     }
1.1061    raeburn  6112: 
                   6113:     my $output .= <<'END_MYBLOCK';
                   6114: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   6115:     var options = "width=" + w + ",height=" + h + ",";
                   6116:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   6117:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   6118:     var newWin = window.open(url, wdwName, options);
                   6119:     newWin.focus();
                   6120: }
1.890     droeschl 6121: END_MYBLOCK
1.854     kalberla 6122: 
1.1061    raeburn  6123:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 6124:   
1.1061    raeburn  6125:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  6126:     my $text = &mt('Communication Blocked');
1.1217    raeburn  6127:     my $class = 'LC_comblock';
1.1062    raeburn  6128:     if ($activity eq 'docs') {
                   6129:         $text = &mt('Content Access Blocked');
1.1217    raeburn  6130:         $class = '';
1.1063    raeburn  6131:     } elsif ($activity eq 'printout') {
                   6132:         $text = &mt('Printing Blocked');
1.1232    raeburn  6133:     } elsif ($activity eq 'passwd') {
                   6134:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  6135:     } elsif ($activity eq 'grades') {
                   6136:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  6137:     } elsif ($activity eq 'search') {
                   6138:         $text = &mt('Search Blocked');
1.1444    raeburn  6139:     } elsif ($activity eq 'index') {
                   6140:         $text = &mt('Content Index Blocked');
1.1282    raeburn  6141:     } elsif ($activity eq 'alert') {
                   6142:         $text = &mt('Checking Critical Messages Blocked');
                   6143:     } elsif ($activity eq 'reinit') {
                   6144:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  6145:     } elsif ($activity eq 'about') {
                   6146:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  6147:     } elsif ($activity eq 'wishlist') {
                   6148:         $text = &mt('Access to Stored Links Blocked');
                   6149:     } elsif ($activity eq 'annotate') {
                   6150:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  6151:     }
1.1061    raeburn  6152:     $output .= <<"END_BLOCK";
1.1217    raeburn  6153: <div class='$class'>
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'>
                   6156:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 6157:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 6158:   title='$text'>$text</a>
1.867     kalberla 6159: </div>
                   6160: 
                   6161: END_BLOCK
1.474     raeburn  6162: 
1.1061    raeburn  6163:     return ($blocked, $output);
1.854     kalberla 6164: }
1.490     raeburn  6165: 
1.60      matthew  6166: ###############################################
                   6167: 
1.682     raeburn  6168: sub check_ip_acc {
1.1201    raeburn  6169:     my ($acc,$clientip)=@_;
1.682     raeburn  6170:     &Apache::lonxml::debug("acc is $acc");
                   6171:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   6172:         return 1;
                   6173:     }
1.1339    raeburn  6174:     my ($ip,$allowed);
                   6175:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   6176:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   6177:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   6178:     } else {
1.1350    raeburn  6179:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   6180:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  6181:     }
1.682     raeburn  6182: 
                   6183:     my $name;
1.1219    raeburn  6184:     my %access = (
                   6185:                      allowfrom => 1,
                   6186:                      denyfrom  => 0,
                   6187:                  );
                   6188:     my @allows;
                   6189:     my @denies;
                   6190:     foreach my $item (split(',',$acc)) {
                   6191:         $item =~ s/^\s*//;
                   6192:         $item =~ s/\s*$//;
                   6193:         my $pattern;
                   6194:         if ($item =~ /^\!(.+)$/) {
                   6195:             push(@denies,$1);
                   6196:         } else {
                   6197:             push(@allows,$item);
                   6198:         }
                   6199:    }
                   6200:    my $numdenies = scalar(@denies);
                   6201:    my $numallows = scalar(@allows);
                   6202:    my $count = 0;
                   6203:    foreach my $pattern (@denies,@allows) {
                   6204:         $count ++; 
                   6205:         my $acctype = 'allowfrom';
                   6206:         if ($count <= $numdenies) {
                   6207:             $acctype = 'denyfrom';
                   6208:         }
1.682     raeburn  6209:         if ($pattern =~ /\*$/) {
                   6210:             #35.8.*
                   6211:             $pattern=~s/\*//;
1.1219    raeburn  6212:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6213:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   6214:             #35.8.3.[34-56]
                   6215:             my $low=$2;
                   6216:             my $high=$3;
                   6217:             $pattern=$1;
                   6218:             if ($ip =~ /^\Q$pattern\E/) {
                   6219:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  6220:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  6221:             }
                   6222:         } elsif ($pattern =~ /^\*/) {
                   6223:             #*.msu.edu
                   6224:             $pattern=~s/\*//;
                   6225:             if (!defined($name)) {
                   6226:                 use Socket;
                   6227:                 my $netaddr=inet_aton($ip);
                   6228:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6229:             }
1.1219    raeburn  6230:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  6231:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   6232:             #127.0.0.1
1.1219    raeburn  6233:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6234:         } else {
                   6235:             #some.name.com
                   6236:             if (!defined($name)) {
                   6237:                 use Socket;
                   6238:                 my $netaddr=inet_aton($ip);
                   6239:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6240:             }
1.1219    raeburn  6241:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   6242:         }
                   6243:         if ($allowed =~ /^(0|1)$/) { last; }
                   6244:     }
                   6245:     if ($allowed eq '') {
                   6246:         if ($numdenies && !$numallows) {
                   6247:             $allowed = 1;
                   6248:         } else {
                   6249:             $allowed = 0;
1.682     raeburn  6250:         }
                   6251:     }
                   6252:     return $allowed;
                   6253: }
                   6254: 
                   6255: ###############################################
                   6256: 
1.60      matthew  6257: =pod
                   6258: 
1.112     bowersj2 6259: =head1 Domain Template Functions
                   6260: 
                   6261: =over 4
                   6262: 
                   6263: =item * &determinedomain()
1.60      matthew  6264: 
                   6265: Inputs: $domain (usually will be undef)
                   6266: 
1.63      www      6267: Returns: Determines which domain should be used for designs
1.60      matthew  6268: 
                   6269: =cut
1.54      www      6270: 
1.60      matthew  6271: ###############################################
1.63      www      6272: sub determinedomain {
                   6273:     my $domain=shift;
1.531     albertel 6274:     if (! $domain) {
1.60      matthew  6275:         # Determine domain if we have not been given one
1.893     raeburn  6276:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 6277:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   6278:         if ($env{'request.role.domain'}) { 
                   6279:             $domain=$env{'request.role.domain'}; 
1.60      matthew  6280:         }
                   6281:     }
1.63      www      6282:     return $domain;
                   6283: }
                   6284: ###############################################
1.517     raeburn  6285: 
1.518     albertel 6286: sub devalidate_domconfig_cache {
                   6287:     my ($udom)=@_;
                   6288:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   6289: }
                   6290: 
                   6291: # ---------------------- Get domain configuration for a domain
                   6292: sub get_domainconf {
                   6293:     my ($udom) = @_;
                   6294:     my $cachetime=1800;
                   6295:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   6296:     if (defined($cached)) { return %{$result}; }
                   6297: 
                   6298:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  6299: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  6300:     my (%designhash,%legacy);
1.518     albertel 6301:     if (keys(%domconfig) > 0) {
                   6302:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  6303:             if (keys(%{$domconfig{'login'}})) {
                   6304:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  6305:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  6306:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   6307:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6308:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   6309:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   6310:                                         if ($key eq 'loginvia') {
                   6311:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   6312:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   6313:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   6314:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   6315: 
                   6316:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   6317:                                                 } else {
                   6318:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   6319:                                                 }
1.948     raeburn  6320:                                             }
1.1208    raeburn  6321:                                         } elsif ($key eq 'headtag') {
                   6322:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   6323:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  6324:                                             }
1.946     raeburn  6325:                                         }
1.1208    raeburn  6326:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   6327:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   6328:                                         }
1.946     raeburn  6329:                                     }
                   6330:                                 }
                   6331:                             }
1.1366    raeburn  6332:                         } elsif ($key eq 'saml') {
                   6333:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6334:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6335:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6336:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6337:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6338:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6339:                                         }
                   6340:                                     }
                   6341:                                 }
                   6342:                             }
1.946     raeburn  6343:                         } else {
                   6344:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6345:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6346:                                     $domconfig{'login'}{$key}{$img};
                   6347:                             }
1.699     raeburn  6348:                         }
                   6349:                     } else {
                   6350:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6351:                     }
1.632     raeburn  6352:                 }
                   6353:             } else {
                   6354:                 $legacy{'login'} = 1;
1.518     albertel 6355:             }
1.632     raeburn  6356:         } else {
                   6357:             $legacy{'login'} = 1;
1.518     albertel 6358:         }
                   6359:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6360:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6361:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6362:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6363:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6364:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6365:                         }
1.518     albertel 6366:                     }
                   6367:                 }
1.632     raeburn  6368:             } else {
                   6369:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6370:             }
1.632     raeburn  6371:         } else {
                   6372:             $legacy{'rolecolors'} = 1;
1.518     albertel 6373:         }
1.948     raeburn  6374:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6375:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6376:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6377:             }
                   6378:         }
1.632     raeburn  6379:         if (keys(%legacy) > 0) {
                   6380:             my %legacyhash = &get_legacy_domconf($udom);
                   6381:             foreach my $item (keys(%legacyhash)) {
                   6382:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6383:                     if ($legacy{'login'}) { 
                   6384:                         $designhash{$item} = $legacyhash{$item};
                   6385:                     }
                   6386:                 } else {
                   6387:                     if ($legacy{'rolecolors'}) {
                   6388:                         $designhash{$item} = $legacyhash{$item};
                   6389:                     }
1.518     albertel 6390:                 }
                   6391:             }
                   6392:         }
1.632     raeburn  6393:     } else {
                   6394:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6395:     }
                   6396:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6397: 				  $cachetime);
                   6398:     return %designhash;
                   6399: }
                   6400: 
1.632     raeburn  6401: sub get_legacy_domconf {
                   6402:     my ($udom) = @_;
                   6403:     my %legacyhash;
                   6404:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6405:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6406:     if (-e $designfile) {
1.1317    raeburn  6407:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6408:             while (my $line = <$fh>) {
                   6409:                 next if ($line =~ /^\#/);
                   6410:                 chomp($line);
                   6411:                 my ($key,$val)=(split(/\=/,$line));
                   6412:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6413:             }
                   6414:             close($fh);
                   6415:         }
                   6416:     }
1.1026    raeburn  6417:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6418:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6419:     }
                   6420:     return %legacyhash;
                   6421: }
                   6422: 
1.63      www      6423: =pod
                   6424: 
1.112     bowersj2 6425: =item * &domainlogo()
1.63      www      6426: 
                   6427: Inputs: $domain (usually will be undef)
                   6428: 
                   6429: Returns: A link to a domain logo, if the domain logo exists.
                   6430: If the domain logo does not exist, a description of the domain.
                   6431: 
                   6432: =cut
1.112     bowersj2 6433: 
1.63      www      6434: ###############################################
                   6435: sub domainlogo {
1.517     raeburn  6436:     my $domain = &determinedomain(shift);
1.518     albertel 6437:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6438:     # See if there is a logo
                   6439:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6440:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6441:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6442: 	    if ($imgsrc =~ m{^/res/}) {
                   6443: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6444: 		&Apache::lonnet::repcopy($local_name);
                   6445: 	    }
                   6446: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6447:         }
                   6448:         my $alttext = $domain;
                   6449:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6450:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6451:         }
                   6452:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6453:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6454:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6455:     } else {
1.60      matthew  6456:         return '';
1.59      www      6457:     }
                   6458: }
1.63      www      6459: ##############################################
                   6460: 
                   6461: =pod
                   6462: 
1.112     bowersj2 6463: =item * &designparm()
1.63      www      6464: 
                   6465: Inputs: $which parameter; $domain (usually will be undef)
                   6466: 
                   6467: Returns: value of designparamter $which
                   6468: 
                   6469: =cut
1.112     bowersj2 6470: 
1.397     albertel 6471: 
1.400     albertel 6472: ##############################################
1.397     albertel 6473: sub designparm {
                   6474:     my ($which,$domain)=@_;
                   6475:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6476:         return $env{'environment.color.'.$which};
1.96      www      6477:     }
1.63      www      6478:     $domain=&determinedomain($domain);
1.1016    raeburn  6479:     my %domdesign;
                   6480:     unless ($domain eq 'public') {
                   6481:         %domdesign = &get_domainconf($domain);
                   6482:     }
1.520     raeburn  6483:     my $output;
1.517     raeburn  6484:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6485:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6486:     } else {
1.520     raeburn  6487:         $output = $defaultdesign{$which};
                   6488:     }
                   6489:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6490:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6491:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6492:             if ($output =~ m{^/res/}) {
                   6493:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6494:                 &Apache::lonnet::repcopy($local_name);
                   6495:             }
1.520     raeburn  6496:             $output = &lonhttpdurl($output);
                   6497:         }
1.63      www      6498:     }
1.520     raeburn  6499:     return $output;
1.63      www      6500: }
1.59      www      6501: 
1.822     bisitz   6502: ##############################################
                   6503: =pod
                   6504: 
1.832     bisitz   6505: =item * &authorspace()
                   6506: 
1.1028    raeburn  6507: Inputs: $url (usually will be undef).
1.832     bisitz   6508: 
1.1132    raeburn  6509: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6510:          directory being viewed (or for which action is being taken). 
                   6511:          If $url is provided, and begins /priv/<domain>/<uname>
                   6512:          the path will be that portion of the $context argument.
                   6513:          Otherwise the path will be for the author space of the current
                   6514:          user when the current role is author, or for that of the 
                   6515:          co-author/assistant co-author space when the current role 
                   6516:          is co-author or assistant co-author.
1.832     bisitz   6517: 
                   6518: =cut
                   6519: 
                   6520: sub authorspace {
1.1028    raeburn  6521:     my ($url) = @_;
                   6522:     if ($url ne '') {
                   6523:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6524:            return $1;
                   6525:         }
                   6526:     }
1.832     bisitz   6527:     my $caname = '';
1.1024    www      6528:     my $cadom = '';
1.1028    raeburn  6529:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6530:         ($cadom,$caname) =
1.832     bisitz   6531:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6532:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6533:         $caname = $env{'user.name'};
1.1024    www      6534:         $cadom = $env{'user.domain'};
1.832     bisitz   6535:     }
1.1028    raeburn  6536:     if (($caname ne '') && ($cadom ne '')) {
                   6537:         return "/priv/$cadom/$caname/";
                   6538:     }
                   6539:     return;
1.832     bisitz   6540: }
                   6541: 
                   6542: ##############################################
                   6543: =pod
                   6544: 
1.822     bisitz   6545: =item * &head_subbox()
                   6546: 
                   6547: Inputs: $content (contains HTML code with page functions, etc.)
                   6548: 
                   6549: Returns: HTML div with $content
                   6550:          To be included in page header
                   6551: 
                   6552: =cut
                   6553: 
                   6554: sub head_subbox {
                   6555:     my ($content)=@_;
                   6556:     my $output =
1.993     raeburn  6557:         '<div class="LC_head_subbox">'
1.822     bisitz   6558:        .$content
                   6559:        .'</div>'
                   6560: }
                   6561: 
                   6562: ##############################################
                   6563: =pod
                   6564: 
                   6565: =item * &CSTR_pageheader()
                   6566: 
1.1026    raeburn  6567: Input: (optional) filename from which breadcrumb trail is built.
                   6568:        In most cases no input as needed, as $env{'request.filename'}
                   6569:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6570:        frameset flag
                   6571:        If page header is being requested for use in a frameset, then
                   6572:        the second (option) argument -- frameset will be true, and
                   6573:        the target attribute set for links should be target="_parent".
1.1433    raeburn  6574:        If $title is supplied as the third arg, that will be used to 
1.1407    raeburn  6575:        the left of the breadcrumbs tail for the current path.
1.822     bisitz   6576: 
                   6577: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6578:          To be included on Authoring Space pages
1.822     bisitz   6579: 
                   6580: =cut
                   6581: 
                   6582: sub CSTR_pageheader {
1.1407    raeburn  6583:     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  6584:     if ($trailfile eq '') {
                   6585:         $trailfile = $env{'request.filename'};
                   6586:     }
                   6587: 
                   6588: # this is for resources; directories have customtitle, and crumbs
                   6589: # and select recent are created in lonpubdir.pm
                   6590: 
                   6591:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6592:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6593:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6594:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6595:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6596: 
                   6597:     my $parentpath = '';
                   6598:     my $lastitem = '';
                   6599:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6600:         $parentpath = $1;
                   6601:         $lastitem = $2;
                   6602:     } else {
                   6603:         $lastitem = $thisdisfn;
                   6604:     }
1.921     bisitz   6605: 
1.1406    raeburn  6606:     my $crsauthor;
1.1246    raeburn  6607:     if (($env{'request.course.id'}) &&
                   6608:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6609:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6610:         $crsauthor = 1;
1.1406    raeburn  6611:         if ($title eq '') {
                   6612:             $title = &mt('Course Authoring Space');
                   6613:         }
                   6614:     } elsif ($title eq '') {
1.1246    raeburn  6615:         $title = &mt('Authoring Space');
                   6616:     }
                   6617: 
1.1379    raeburn  6618:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6619:     if ($frameset) {
                   6620:         $target = ' target="_parent"';
                   6621:         $crumbtarget = '_parent';
                   6622:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6623:         $target = '';
                   6624:         $crumbtarget = '';
1.1379    raeburn  6625:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6626:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6627:         $crumbtarget = $env{'request.deeplink.target'};
                   6628:     }
1.1313    raeburn  6629: 
1.921     bisitz   6630:     my $output =
1.1407    raeburn  6631:          '<div>'
1.822     bisitz   6632:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6633:         .'<b>'.$title.'</b> '
1.1314    raeburn  6634:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6635:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6636: 
                   6637:     if ($lastitem) {
                   6638:         $output .=
                   6639:              '<span class="LC_filename">'
                   6640:             .$lastitem
                   6641:             .'</span>';
                   6642:     }
1.1245    raeburn  6643: 
1.1246    raeburn  6644:     if ($crsauthor) {
1.1379    raeburn  6645:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6646:     } else {
                   6647:         $output .=
                   6648:              '<br />'
1.1314    raeburn  6649:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6650:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6651:             .'</form>'
1.1379    raeburn  6652:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6653:     }
1.1407    raeburn  6654:     $output .= '</div>';
1.921     bisitz   6655: 
                   6656:     return $output;
1.822     bisitz   6657: }
                   6658: 
1.1419    raeburn  6659: ##############################################
                   6660: =pod
                   6661: 
                   6662: =item * &nocodemirror()
                   6663: 
                   6664: Input: None
                   6665: 
                   6666: Returns: 1 if CodeMirror is deactivated based on
                   6667:          user's preference, or domain default,
                   6668:          if user indicated use of default.
                   6669: 
                   6670: =cut
                   6671: 
1.1416    raeburn  6672: sub nocodemirror {
                   6673:     my $nocodem = $env{'environment.nocodemirror'};
                   6674:     unless ($nocodem) {
                   6675:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   6676:         if ($domdefs{'nocodemirror'}) {
                   6677:             $nocodem = 'yes';
                   6678:         }
                   6679:     }
1.1417    raeburn  6680:     if ($nocodem eq 'yes') {
                   6681:         return 1;
                   6682:     }
                   6683:     return;
1.1416    raeburn  6684: }
                   6685: 
1.1419    raeburn  6686: ##############################################
                   6687: =pod
                   6688: 
                   6689: =item * &permitted_editors()
                   6690: 
1.1422    raeburn  6691: Input: $uri (optional)
1.1419    raeburn  6692: 
                   6693: Returns: %editors hash in which keys are editors
1.1429    raeburn  6694:          permitted in current Authoring Space,
                   6695:          or in current course for web pages
                   6696:          created in a course.
                   6697: 
1.1419    raeburn  6698:          Value for each key is 1. Possible keys
1.1429    raeburn  6699:          are: edit, xml, and daxe.
                   6700: 
                   6701:          For a regular Authoring Space, if no specific
1.1419    raeburn  6702:          set of editors has been set for the Author
                   6703:          who owns the Authoring Space, then the
                   6704:          domain default will be used.  If no domain
                   6705:          default has been set, then the keys will be
                   6706:          edit and xml.
                   6707: 
1.1429    raeburn  6708:          For a course author, or for web pages created
                   6709:          in a course, if no specific set of editors has
                   6710:          been set for the course, then the domain
                   6711:          course default will be used. If no domain
                   6712:          course default has been set, then the keys
                   6713:          will be edit and xml.
                   6714: 
1.1419    raeburn  6715: =cut
                   6716: 
1.1418    raeburn  6717: sub permitted_editors {
1.1422    raeburn  6718:     my ($uri) = @_;
1.1429    raeburn  6719:     my ($is_author,$is_coauthor,$is_course,$auname,$audom,%editors);
1.1418    raeburn  6720:     if ($env{'request.role'} =~ m{^au\./}) {
                   6721:         $is_author = 1;
                   6722:     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
                   6723:         ($audom,$auname) = ($1,$2);
                   6724:         if (($audom ne '') && ($auname ne '')) {
                   6725:             if (($env{'user.domain'} eq $audom) &&
                   6726:                 ($env{'user.name'} eq $auname)) {
                   6727:                 $is_author = 1;
                   6728:             } else {
                   6729:                 $is_coauthor = 1;
                   6730:             }
                   6731:         }
                   6732:     } elsif ($env{'request.course.id'}) {
1.1429    raeburn  6733:         my ($cdom,$cnum);
                   6734:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6735:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6736:         if (($env{'request.editurl'} =~ m{^/priv/\Q$cdom/$cnum\E/}) ||
1.1430    raeburn  6737:             ($env{'request.editurl'} =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}) ||
                   6738:             ($uri =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/})) {
1.1429    raeburn  6739:             $is_course = 1;
                   6740:         } elsif ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
1.1418    raeburn  6741:             ($audom,$auname) = ($1,$2);
                   6742:         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6743:             ($audom,$auname) = ($1,$2);
1.1422    raeburn  6744:         } elsif (($uri eq '/daxesave') &&
1.1429    raeburn  6745:                  (($env{'form.path'} =~ m{^/daxeopen/priv/\Q$cdom/$cnum\E/}) ||
                   6746:                   ($env{'form.path'} =~ m{^/daxeopen/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}))) {
                   6747:             $is_course = 1;
                   6748:         } elsif (($uri eq '/daxesave') &&
1.1422    raeburn  6749:                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
                   6750:             ($audom,$auname) = ($1,$2);
1.1418    raeburn  6751:         }
1.1429    raeburn  6752:         unless ($is_course) {
                   6753:             if (($audom ne '') && ($auname ne '')) {
                   6754:                 if (($env{'user.domain'} eq $audom) &&
                   6755:                     ($env{'user.name'} eq $auname)) {
                   6756:                     $is_author = 1;
                   6757:                 } else {
                   6758:                     $is_coauthor = 1;
                   6759:                 }
1.1418    raeburn  6760:             }
                   6761:         }
                   6762:     }
                   6763:     if ($is_author) {
                   6764:         if (exists($env{'environment.editors'})) {
                   6765:             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
                   6766:         } else {
                   6767:             %editors = ( edit => 1,
                   6768:                          xml => 1,
                   6769:                        );
                   6770:         }
                   6771:     } elsif ($is_coauthor) {
                   6772:         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
                   6773:             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
                   6774:         } else {
                   6775:             %editors = ( edit => 1,
                   6776:                          xml => 1,
                   6777:                        );
                   6778:         }
1.1429    raeburn  6779:     } elsif ($is_course) {
                   6780:         if (exists($env{'course.'.$env{'request.course.id'}.'.internal.crseditors'})) {
                   6781:             map { $editors{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.crseditors'});
                   6782:         } else {
                   6783:             my %domdefaults = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
                   6784:             if (exists($domdefaults{'crseditors'})) {
                   6785:                 map { $editors{$_} = 1; } split(/,/,$domdefaults{'crseditors'});
                   6786:             } else {
                   6787:                 %editors = ( edit => 1,
                   6788:                              xml => 1,
                   6789:                            );
                   6790:             }
                   6791:         }
1.1418    raeburn  6792:     } else {
                   6793:         %editors = ( edit => 1,
                   6794:                      xml => 1,
                   6795:                    );
                   6796:     }
                   6797:     return %editors;
                   6798: }
                   6799: 
1.60      matthew  6800: ###############################################
                   6801: ###############################################
                   6802: 
                   6803: =pod
                   6804: 
1.112     bowersj2 6805: =back
                   6806: 
1.549     albertel 6807: =head1 HTML Helpers
1.112     bowersj2 6808: 
                   6809: =over 4
                   6810: 
                   6811: =item * &bodytag()
1.60      matthew  6812: 
                   6813: Returns a uniform header for LON-CAPA web pages.
                   6814: 
                   6815: Inputs: 
                   6816: 
1.112     bowersj2 6817: =over 4
                   6818: 
                   6819: =item * $title, A title to be displayed on the page.
                   6820: 
                   6821: =item * $function, the current role (can be undef).
                   6822: 
                   6823: =item * $addentries, extra parameters for the <body> tag.
                   6824: 
                   6825: =item * $bodyonly, if defined, only return the <body> tag.
                   6826: 
                   6827: =item * $domain, if defined, force a given domain.
                   6828: 
                   6829: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6830:             text interface only)
1.60      matthew  6831: 
1.814     bisitz   6832: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6833:                      navigational links
1.317     albertel 6834: 
1.338     albertel 6835: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6836: 
1.460     albertel 6837: =item * $args, optional argument valid values are
                   6838:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6839:             use_absolute     -> for external resource or syllabus, this will
                   6840:                                 contain https://<hostname> if server uses
                   6841:                                 https (as per hosts.tab), but request is for http
                   6842:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6843: 
1.1096    raeburn  6844: =item * $advtoolsref, optional argument, ref to an array containing
                   6845:             inlineremote items to be added in "Functions" menu below
                   6846:             breadcrumbs.
                   6847: 
1.1316    raeburn  6848: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6849:             course, if LON-CAPA is in LTI Provider context. Value is
                   6850:             the scope of use, i.e., launch was for access to a single, a map
                   6851:             or the entire course.
                   6852: 
                   6853: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6854:             context, this will contain the URL for the landing item in
                   6855:             the course, after launch from an LTI Consumer
                   6856: 
1.1318    raeburn  6857: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6858:             context, this will contain a reference to hash of items
                   6859:             to be included in the page header and/or inline menu.
                   6860: 
1.1385    raeburn  6861: =item * $menucoll, optional argument, if specific menu collection is in
                   6862:             effect, either set as the default for the course, or set for
                   6863:             the deeplink paramater for $env{'request.deeplink.login'}
                   6864:             then $menucoll will be the number of that collection. 
                   6865: 
                   6866: =item * $menuref, optional argument, reference to a hash, containing the
                   6867:             menu options included for the menu in effect, based on the
                   6868:             configuration for the numbered menu collection in use.  
                   6869: 
                   6870: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6871:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6872:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6873:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6874:             being called a second time.
                   6875: 
1.112     bowersj2 6876: =back
                   6877: 
1.60      matthew  6878: Returns: A uniform header for LON-CAPA web pages.  
                   6879: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6880: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6881: other decorations will be returned.
                   6882: 
                   6883: =cut
                   6884: 
1.54      www      6885: sub bodytag {
1.831     bisitz   6886:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6887:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6888:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6889: 
1.954     raeburn  6890:     my $public;
                   6891:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6892:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6893:         $public = 1;
                   6894:     }
1.460     albertel 6895:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6896:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6897:     my $hostname = $args->{'hostname'};
1.339     albertel 6898: 
1.183     matthew  6899:     $function = &get_users_function() if (!$function);
1.339     albertel 6900:     my $font =   &designparm($function.'.font',$domain);
                   6901:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6902: 
1.803     bisitz   6903:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6904: 		   'bgcolor' => $pgbg,
1.339     albertel 6905: 		   'text'    => $font,
                   6906:                    'alink'   => &designparm($function.'.alink',$domain),
                   6907: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6908: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6909:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6910: 
1.63      www      6911:  # role and realm
1.1178    raeburn  6912:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6913:     if ($realm) {
                   6914:         $realm = '/'.$realm;
                   6915:     }
1.1357    raeburn  6916:     if ($role eq 'ca') {
1.479     albertel 6917:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6918:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6919:     } 
1.55      www      6920: # realm
1.1357    raeburn  6921:     my ($cid,$sec);
1.258     albertel 6922:     if ($env{'request.course.id'}) {
1.1357    raeburn  6923:         $cid = $env{'request.course.id'};
                   6924:         if ($env{'request.course.sec'}) {
                   6925:             $sec = $env{'request.course.sec'};
                   6926:         }
                   6927:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6928:         if (&Apache::lonnet::is_course($1,$2)) {
                   6929:             $cid = $1.'_'.$2;
                   6930:             $sec = $3;
                   6931:         }
                   6932:     }
                   6933:     if ($cid) {
1.378     raeburn  6934:         if ($env{'request.role'} !~ /^cr/) {
                   6935:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6936:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6937:             if ($env{'request.role.desc'}) {
                   6938:                 $role = $env{'request.role.desc'};
                   6939:             } else {
                   6940:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6941:             }
1.1257    raeburn  6942:         } else {
                   6943:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6944:         }
1.1357    raeburn  6945:         if ($sec) {
                   6946:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6947:         }   
1.1357    raeburn  6948: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6949:     } else {
                   6950:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6951:     }
1.433     albertel 6952: 
1.438     albertel 6953:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6954: 
1.101     www      6955: # construct main body tag
1.359     albertel 6956:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6957: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6958: 
1.1131    raeburn  6959:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6960: 
1.1130    raeburn  6961:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6962:         return $bodytag;
1.1130    raeburn  6963:     }
1.359     albertel 6964: 
1.954     raeburn  6965:     if ($public) {
1.433     albertel 6966: 	undef($role);
                   6967:     }
1.1318    raeburn  6968: 
1.1359    raeburn  6969:     my $showcrstitle = 1;
1.1357    raeburn  6970:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6971:         if (ref($ltimenu) eq 'HASH') {
                   6972:             unless ($ltimenu->{'role'}) {
                   6973:                 undef($role);
                   6974:             }
                   6975:             unless ($ltimenu->{'coursetitle'}) {
1.1359    raeburn  6976:                 $showcrstitle = 0;
                   6977:             }
                   6978:         }
                   6979:     } elsif (($cid) && ($menucoll)) {
                   6980:         if (ref($menuref) eq 'HASH') {
                   6981:             unless ($menuref->{'role'}) {
                   6982:                 undef($role);
                   6983:             }
                   6984:             unless ($menuref->{'crs'}) {
                   6985:                 $showcrstitle = 0;
1.1318    raeburn  6986:             }
                   6987:         }
                   6988:     }
                   6989: 
1.762     bisitz   6990:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6991:     #
                   6992:     # Extra info if you are the DC
                   6993:     my $dc_info = '';
1.1359    raeburn  6994:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6995:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6996:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6997:         $dc_info =~ s/\s+$//;
1.359     albertel 6998:     }
                   6999: 
1.1237    raeburn  7000:     my $crstype;
1.1357    raeburn  7001:     if ($cid) {
                   7002:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  7003:     } elsif ($args->{'crstype'}) {
                   7004:         $crstype = $args->{'crstype'};
                   7005:     }
                   7006:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   7007:         undef($role);
                   7008:     } else {
1.1242    raeburn  7009:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  7010:     }
1.853     droeschl 7011: 
1.903     droeschl 7012:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   7013: 
                   7014:         #    if ($env{'request.state'} eq 'construct') {
                   7015:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   7016:         #    }
                   7017: 
1.1440    raeburn  7018:         my $need_endlcint;
                   7019:         unless ($args->{'switchserver'}) {
                   7020:             $bodytag .= Apache::lonhtmlcommon::scripttag(
                   7021:                 Apache::lonmenu::utilityfunctions($httphost), 'start');
                   7022:             $need_endlcint = 1;
                   7023:         }
1.359     albertel 7024: 
1.1427    raeburn  7025:         my $collapsible;
1.1423    raeburn  7026:         if ($args->{'collapsible_header'} ne '') {
1.1427    raeburn  7027:             $collapsible = 1;
                   7028:             my ($menustate,$tiptext,$divclass);
                   7029:             if ($args->{'start_collapsed'}) {
                   7030:                 $menustate = 'collapsed';
                   7031:                 $tiptext = 'display';
                   7032:                 $divclass = 'hidden';
                   7033:             } else {
                   7034:                 $menustate = 'expanded';
                   7035:                 $tiptext = 'hide';
                   7036:                 $divclass = 'shown';
                   7037:             }
                   7038:             my $alttext = &mt('menu state: '.$menustate);
                   7039:             my $tooltip = &mt($tiptext.' standard menus');
1.1421    raeburn  7040:             $bodytag .= <<"END";
                   7041: <div id="LC_expandingContainer" style="display:inline;">
                   7042: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
1.1427    raeburn  7043: <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>
                   7044: <div class="LC_menus_content $divclass">
1.1421    raeburn  7045: END
                   7046:         }
1.1318    raeburn  7047:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  7048:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  7049:                                                               $args->{'links_disabled'},
1.1421    raeburn  7050:                                                               $args->{'links_target'},
1.1427    raeburn  7051:                                                               $collapsible);
1.1454    raeburn  7052:             my $labeltext = &HTML::Entities::encode(&mt('Primary links'));
1.1318    raeburn  7053:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   7054:                 if ($dc_info) {
                   7055:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   7056:                 }
1.1456    raeburn  7057:                 $bodytag .= qq|<div id="LC_nav_bar" role="navigation" aria-label="$labeltext">$left $role</div>|;
1.1454    raeburn  7058:                 unless (($realm eq '') && ($dc_info eq '')) {
                   7059:                     $bodytag .= qq|<div id="LC_realm" role="complementary"><em>$realm</em> $dc_info</div>|;
                   7060:                 }
1.1440    raeburn  7061:                 if ($need_endlcint) {
                   7062:                     $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7063:                 }
1.1318    raeburn  7064:                 return $bodytag;
                   7065:             }
1.894     droeschl 7066: 
1.1457    raeburn  7067:             $bodytag .= '<div class="LC_landmark" style="margin: 3px 0 0 0;" role="navigation" aria-label="'.$labeltext.'">';
1.1318    raeburn  7068:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   7069:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   7070:             }
1.916     droeschl 7071: 
1.1454    raeburn  7072:             $bodytag .= $right.'</div>';
1.852     droeschl 7073: 
1.1318    raeburn  7074:             if ($dc_info) {
                   7075:                 $dc_info = &dc_courseid_toggle($dc_info);
                   7076:             }
1.1454    raeburn  7077:             unless (($realm eq '') && ($dc_info eq '')) {
1.1457    raeburn  7078:                 $bodytag .= qq|<div id="LC_realm" role="complementary">$realm $dc_info</div>|;
1.1454    raeburn  7079:             }
1.1457    raeburn  7080:             $bodytag .= qq|<div style="clear: both; margin: 5px 0 0 0;"></div>|;
1.917     raeburn  7081:         }
1.916     droeschl 7082: 
1.1169    raeburn  7083:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  7084:         if ($args->{'no_secondary_menu'}) {
1.1440    raeburn  7085:             if ($need_endlcint) {
                   7086:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7087:             }
1.1168    raeburn  7088:             return $bodytag;
                   7089:         }
1.1169    raeburn  7090:         #don't show menus for public users
1.954     raeburn  7091:         if (!$public){
1.1318    raeburn  7092:             unless ($args->{'no_inline_menu'}) {
1.1459  ! raeburn  7093:                 $bodytag .= '<div class="LC_landmark" role="navigation" aria-label="Secondary Links">'.
        !          7094:                             Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  7095:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  7096:                                                             $menucoll,$menuref,
1.1380    raeburn  7097:                                                             $args->{'links_disabled'},
1.1459  ! raeburn  7098:                                                             $args->{'links_target'}).
        !          7099:                             '</div>'; 
1.1318    raeburn  7100:             }
1.903     droeschl 7101:             $bodytag .= Apache::lonmenu::serverform();
1.1440    raeburn  7102:             if ($need_endlcint) {
                   7103:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7104:             }
1.920     raeburn  7105:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 7106:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  7107:                                 $args->{'bread_crumbs'},'','',$hostname,
                   7108:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7109:             } elsif ($forcereg) {
                   7110:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  7111:                                 $args->{'group'},$args->{'hide_buttons'},
                   7112:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7113:             } else {
1.1459  ! raeburn  7114:                 $bodytag .=
1.1096    raeburn  7115:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   7116:                                                         $forcereg,$args->{'group'},
                   7117:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  7118:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  7119:             }
1.1440    raeburn  7120:         } else {
                   7121:             # this is to separate menu from content when there's no secondary
1.1441    raeburn  7122:             # menu. Especially needed for publicly accessible resources.
1.1459  ! raeburn  7123:             $bodytag .= '<hr style="clear:both" role="complementary" />';
1.1440    raeburn  7124:             if ($need_endlcint) {
                   7125:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7126:             }
1.235     raeburn  7127:         }
1.1423    raeburn  7128:         if ($args->{'collapsible_header'} ne '') {
                   7129:             $bodytag .= $args->{'collapsible_header'}.
                   7130:                         '<div id="LC_collapsible_separator"></div>'.
1.1421    raeburn  7131:                         '</div></div>';
                   7132:         }
1.235     raeburn  7133:         return $bodytag;
1.182     matthew  7134: }
                   7135: 
1.917     raeburn  7136: sub dc_courseid_toggle {
                   7137:     my ($dc_info) = @_;
1.980     raeburn  7138:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  7139:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  7140:            &mt('(More ...)').'</a></span>'.
                   7141:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   7142: }
                   7143: 
1.330     albertel 7144: sub make_attr_string {
                   7145:     my ($register,$attr_ref) = @_;
                   7146: 
                   7147:     if ($attr_ref && !ref($attr_ref)) {
                   7148: 	die("addentries Must be a hash ref ".
                   7149: 	    join(':',caller(1))." ".
                   7150: 	    join(':',caller(0))." ");
                   7151:     }
                   7152: 
                   7153:     if ($register) {
1.339     albertel 7154: 	my ($on_load,$on_unload);
                   7155: 	foreach my $key (keys(%{$attr_ref})) {
                   7156: 	    if      (lc($key) eq 'onload') {
                   7157: 		$on_load.=$attr_ref->{$key}.';';
                   7158: 		delete($attr_ref->{$key});
                   7159: 
                   7160: 	    } elsif (lc($key) eq 'onunload') {
                   7161: 		$on_unload.=$attr_ref->{$key}.';';
                   7162: 		delete($attr_ref->{$key});
                   7163: 	    }
                   7164: 	}
1.953     droeschl 7165: 	$attr_ref->{'onload'}  = $on_load;
                   7166: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 7167:     }
1.339     albertel 7168: 
1.330     albertel 7169:     my $attr_string;
1.1159    raeburn  7170:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 7171: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   7172:     }
                   7173:     return $attr_string;
                   7174: }
                   7175: 
                   7176: 
1.182     matthew  7177: ###############################################
1.251     albertel 7178: ###############################################
                   7179: 
                   7180: =pod
                   7181: 
                   7182: =item * &endbodytag()
                   7183: 
                   7184: Returns a uniform footer for LON-CAPA web pages.
                   7185: 
1.635     raeburn  7186: Inputs: 1 - optional reference to an args hash
                   7187: If in the hash, key for noredirectlink has a value which evaluates to true,
                   7188: a 'Continue' link is not displayed if the page contains an
                   7189: internal redirect in the <head></head> section,
                   7190: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 7191: 
                   7192: =cut
                   7193: 
                   7194: sub endbodytag {
1.635     raeburn  7195:     my ($args) = @_;
1.1080    raeburn  7196:     my $endbodytag;
                   7197:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   7198:         $endbodytag='</body>';
                   7199:     }
1.315     albertel 7200:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  7201:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  7202:             my ($endbodyjs,$idattr);
                   7203:             if ($env{'internal.head.to_opener'}) {
                   7204:                 my $linkid = 'LC_continue_link';
                   7205:                 $idattr = ' id="'.$linkid.'"';
                   7206:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   7207:                 $endbodyjs=<<ENDJS;
                   7208: <script type="text/javascript">
                   7209: // <![CDATA[
                   7210: function ebFunction(evt) {
                   7211:     evt.preventDefault();
                   7212:     var dest = '$redirect_for_js';
                   7213:     if (window.opener != null && !window.opener.closed) {
                   7214:         window.opener.location.href=dest;
                   7215:         window.close();
                   7216:     } else {
                   7217:         window.location.href=dest;
                   7218:     }
                   7219:     return false;
                   7220: }
                   7221: 
                   7222: \$(document).ready(function () {
                   7223:   if (document.getElementById('$linkid')) {
                   7224:     var clickelem = document.getElementById('$linkid');
                   7225:     clickelem.addEventListener('click',ebFunction,false);
                   7226:   }
                   7227: });
                   7228: // ]]>
                   7229: </script>
                   7230: ENDJS
                   7231:             }
1.635     raeburn  7232: 	    $endbodytag=
1.1386    raeburn  7233: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  7234: 	        &mt('Continue').'</a>'.
                   7235: 	        $endbodytag;
                   7236:         }
1.315     albertel 7237:     }
1.1411    raeburn  7238:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   7239:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   7240:     }
1.251     albertel 7241:     return $endbodytag;
                   7242: }
                   7243: 
1.352     albertel 7244: =pod
                   7245: 
                   7246: =item * &standard_css()
                   7247: 
                   7248: Returns a style sheet
                   7249: 
                   7250: Inputs: (all optional)
                   7251:             domain         -> force to color decorate a page for a specific
                   7252:                                domain
                   7253:             function       -> force usage of a specific rolish color scheme
                   7254:             bgcolor        -> override the default page bgcolor
                   7255: 
                   7256: =cut
                   7257: 
1.343     albertel 7258: sub standard_css {
1.345     albertel 7259:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 7260:     $function  = &get_users_function() if (!$function);
                   7261:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   7262:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 7263:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 7264: #second colour for later usage
1.345     albertel 7265:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 7266:     my $pgbg_or_bgcolor =
                   7267: 	         $bgcolor ||
1.352     albertel 7268: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 7269:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 7270:     my $alink  = &designparm($function.'.alink', $domain);
                   7271:     my $vlink  = &designparm($function.'.vlink', $domain);
                   7272:     my $link   = &designparm($function.'.link',  $domain);
                   7273: 
1.602     albertel 7274:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 7275:     my $mono                 = 'monospace';
1.850     bisitz   7276:     my $data_table_head      = $sidebg;
                   7277:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   7278:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 7279:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 7280:     my $data_table_highlight = '#FFFF00';
1.352     albertel 7281:     my $mail_new             = '#FFBB77';
                   7282:     my $mail_new_hover       = '#DD9955';
                   7283:     my $mail_read            = '#BBBB77';
                   7284:     my $mail_read_hover      = '#999944';
                   7285:     my $mail_replied         = '#AAAA88';
                   7286:     my $mail_replied_hover   = '#888855';
                   7287:     my $mail_other           = '#99BBBB';
                   7288:     my $mail_other_hover     = '#669999';
1.391     albertel 7289:     my $table_header         = '#DDDDDD';
1.489     raeburn  7290:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   7291:     my $lg_border_color      = '#C8C8C8';
1.952     onken    7292:     my $button_hover         = '#BF2317';
1.392     albertel 7293: 
1.608     albertel 7294:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   7295:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   7296:                                              : '0 3px 0 4px';
1.448     albertel 7297: 
1.523     albertel 7298: 
1.343     albertel 7299:     return <<END;
1.947     droeschl 7300: 
                   7301: /* needed for iframe to allow 100% height in FF */
                   7302: body, html { 
                   7303:     margin: 0;
                   7304:     padding: 0 0.5%;
                   7305:     height: 99%; /* to avoid scrollbars */
                   7306: }
                   7307: 
1.795     www      7308: body {
1.911     bisitz   7309:   font-family: $sans;
                   7310:   line-height:130%;
                   7311:   font-size:0.83em;
                   7312:   color:$font;
1.1436    raeburn  7313:   background-color: $pgbg_or_bgcolor;
1.795     www      7314: }
                   7315: 
1.959     onken    7316: a:focus,
                   7317: a:focus img {
1.795     www      7318:   color: red;
                   7319: }
1.698     harmsja  7320: 
1.911     bisitz   7321: form, .inline {
                   7322:   display: inline;
1.795     www      7323: }
1.721     harmsja  7324: 
1.1453    raeburn  7325: .LC_landmark {
                   7326:   margin: 0;
                   7327:   padding: 0;
                   7328:   border: none;
                   7329: }
                   7330: 
1.1443    raeburn  7331: .LC_visually_hidden:not(:focus):not(:active) {
                   7332:     clip-path: inset(50%);
                   7333:     height: 1px;
                   7334:     overflow: hidden;
                   7335:     position: absolute;
                   7336:     white-space: nowrap;
                   7337:     width: 1px;
                   7338:     display: inline;
                   7339: }
                   7340: 
1.1453    raeburn  7341: .LC_heading_2 {
                   7342:   font-size: 1.17em;
                   7343: }
                   7344: 
1.1458    raeburn  7345: .LC_heading_3 {
                   7346:   font-size: 1.0em;
                   7347: }
                   7348: 
1.1421    raeburn  7349: .LC_menus_content.shown{
1.1428    raeburn  7350:   display: block;
1.1421    raeburn  7351: }
                   7352: 
                   7353: .LC_menus_content.hidden {
                   7354:   display: none;
                   7355: }
                   7356: 
1.795     www      7357: .LC_right {
1.911     bisitz   7358:   text-align:right;
1.795     www      7359: }
                   7360: 
1.1449    raeburn  7361: .LC_center {
                   7362:   text-align:center;
                   7363: }
                   7364: 
1.795     www      7365: .LC_middle {
1.911     bisitz   7366:   vertical-align:middle;
1.795     www      7367: }
1.721     harmsja  7368: 
1.1130    raeburn  7369: .LC_floatleft {
                   7370:   float: left;
                   7371: }
                   7372: 
                   7373: .LC_floatright {
                   7374:   float: right;
                   7375: }
                   7376: 
1.911     bisitz   7377: .LC_400Box {
                   7378:   width:400px;
                   7379: }
1.721     harmsja  7380: 
1.1421    raeburn  7381: #LC_collapsible_separator {
                   7382:     border: 1px solid black;
                   7383:     width: 99.9%;
                   7384:     height: 0px;
                   7385: }
                   7386: 
1.947     droeschl 7387: .LC_iframecontainer {
                   7388:     width: 98%;
                   7389:     margin: 0;
                   7390:     position: fixed;
                   7391:     top: 8.5em;
                   7392:     bottom: 0;
                   7393: }
                   7394: 
                   7395: .LC_iframecontainer iframe{
                   7396:     border: none;
                   7397:     width: 100%;
                   7398:     height: 100%;
                   7399: }
                   7400: 
1.778     bisitz   7401: .LC_filename {
                   7402:   font-family: $mono;
                   7403:   white-space:pre;
1.921     bisitz   7404:   font-size: 120%;
1.778     bisitz   7405: }
                   7406: 
                   7407: .LC_fileicon {
                   7408:   border: none;
                   7409:   height: 1.3em;
                   7410:   vertical-align: text-bottom;
                   7411:   margin-right: 0.3em;
                   7412:   text-decoration:none;
                   7413: }
                   7414: 
1.1008    www      7415: .LC_setting {
                   7416:   text-decoration:underline;
                   7417: }
                   7418: 
1.350     albertel 7419: .LC_error {
                   7420:   color: red;
                   7421: }
1.795     www      7422: 
1.1097    bisitz   7423: .LC_warning {
                   7424:   color: darkorange;
                   7425: }
                   7426: 
1.457     albertel 7427: .LC_diff_removed {
1.733     bisitz   7428:   color: red;
1.394     albertel 7429: }
1.532     albertel 7430: 
                   7431: .LC_info,
1.457     albertel 7432: .LC_success,
                   7433: .LC_diff_added {
1.350     albertel 7434:   color: green;
                   7435: }
1.795     www      7436: 
1.802     bisitz   7437: div.LC_confirm_box {
                   7438:   background-color: #FAFAFA;
                   7439:   border: 1px solid $lg_border_color;
                   7440:   margin-right: 0;
                   7441:   padding: 5px;
                   7442: }
                   7443: 
                   7444: div.LC_confirm_box .LC_error img,
                   7445: div.LC_confirm_box .LC_success img {
                   7446:   vertical-align: middle;
                   7447: }
                   7448: 
1.1242    raeburn  7449: .LC_maxwidth {
                   7450:   max-width: 100%;
                   7451:   height: auto;
                   7452: }
                   7453: 
1.1243    raeburn  7454: .LC_textsize_mobile {
                   7455:   \@media only screen and (max-device-width: 480px) {
                   7456:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   7457:   }
                   7458: }
                   7459: 
1.440     albertel 7460: .LC_icon {
1.771     droeschl 7461:   border: none;
1.790     droeschl 7462:   vertical-align: middle;
1.771     droeschl 7463: }
                   7464: 
1.543     albertel 7465: .LC_docs_spacer {
                   7466:   width: 25px;
                   7467:   height: 1px;
1.771     droeschl 7468:   border: none;
1.543     albertel 7469: }
1.346     albertel 7470: 
1.532     albertel 7471: .LC_internal_info {
1.735     bisitz   7472:   color: #999999;
1.532     albertel 7473: }
                   7474: 
1.794     www      7475: .LC_discussion {
1.1050    www      7476:   background: $data_table_dark;
1.911     bisitz   7477:   border: 1px solid black;
                   7478:   margin: 2px;
1.794     www      7479: }
                   7480: 
                   7481: .LC_disc_action_left {
1.1050    www      7482:   background: $sidebg;
1.911     bisitz   7483:   text-align: left;
1.1050    www      7484:   padding: 4px;
                   7485:   margin: 2px;
1.794     www      7486: }
                   7487: 
                   7488: .LC_disc_action_right {
1.1050    www      7489:   background: $sidebg;
1.911     bisitz   7490:   text-align: right;
1.1050    www      7491:   padding: 4px;
                   7492:   margin: 2px;
1.794     www      7493: }
                   7494: 
                   7495: .LC_disc_new_item {
1.911     bisitz   7496:   background: white;
                   7497:   border: 2px solid red;
1.1050    www      7498:   margin: 4px;
                   7499:   padding: 4px;
1.794     www      7500: }
                   7501: 
                   7502: .LC_disc_old_item {
1.911     bisitz   7503:   background: white;
1.1050    www      7504:   margin: 4px;
                   7505:   padding: 4px;
1.794     www      7506: }
                   7507: 
1.458     albertel 7508: table.LC_pastsubmission {
                   7509:   border: 1px solid black;
                   7510:   margin: 2px;
                   7511: }
                   7512: 
1.924     bisitz   7513: table#LC_menubuttons {
1.345     albertel 7514:   width: 100%;
                   7515:   background: $pgbg;
1.392     albertel 7516:   border: 2px;
1.402     albertel 7517:   border-collapse: separate;
1.803     bisitz   7518:   padding: 0;
1.345     albertel 7519: }
1.392     albertel 7520: 
1.801     tempelho 7521: table#LC_title_bar a {
                   7522:   color: $fontmenu;
                   7523: }
1.836     bisitz   7524: 
1.807     droeschl 7525: table#LC_title_bar {
1.819     tempelho 7526:   clear: both;
1.836     bisitz   7527:   display: none;
1.807     droeschl 7528: }
                   7529: 
1.795     www      7530: table#LC_title_bar,
1.933     droeschl 7531: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 7532: table#LC_title_bar.LC_with_remote {
1.359     albertel 7533:   width: 100%;
1.392     albertel 7534:   border-color: $pgbg;
                   7535:   border-style: solid;
                   7536:   border-width: $border;
1.379     albertel 7537:   background: $pgbg;
1.801     tempelho 7538:   color: $fontmenu;
1.392     albertel 7539:   border-collapse: collapse;
1.803     bisitz   7540:   padding: 0;
1.819     tempelho 7541:   margin: 0;
1.359     albertel 7542: }
1.795     www      7543: 
1.933     droeschl 7544: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 7545:     margin: 0;
                   7546:     padding: 0;
1.933     droeschl 7547:     position: relative;
                   7548:     list-style: none;
1.913     droeschl 7549: }
1.933     droeschl 7550: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 7551:     display: inline;
                   7552: }
1.933     droeschl 7553: 
                   7554: .LC_breadcrumb_tools_navigation {
1.913     droeschl 7555:     padding: 0;
1.933     droeschl 7556:     margin: 0;
                   7557:     float: left;
1.913     droeschl 7558: }
1.933     droeschl 7559: .LC_breadcrumb_tools_tools {
                   7560:     padding: 0;
                   7561:     margin: 0;
1.913     droeschl 7562:     float: right;
                   7563: }
                   7564: 
1.1240    raeburn  7565: .LC_placement_prog {
                   7566:     padding-right: 20px;
                   7567:     font-weight: bold;
                   7568:     font-size: 90%;
                   7569: }
                   7570: 
1.359     albertel 7571: table#LC_title_bar td {
                   7572:   background: $tabbg;
                   7573: }
1.795     www      7574: 
1.911     bisitz   7575: table#LC_menubuttons img {
1.803     bisitz   7576:   border: none;
1.346     albertel 7577: }
1.795     www      7578: 
1.842     droeschl 7579: .LC_breadcrumbs_component {
1.911     bisitz   7580:   float: right;
                   7581:   margin: 0 1em;
1.357     albertel 7582: }
1.842     droeschl 7583: .LC_breadcrumbs_component img {
1.911     bisitz   7584:   vertical-align: middle;
1.777     tempelho 7585: }
1.795     www      7586: 
1.1243    raeburn  7587: .LC_breadcrumbs_hoverable {
                   7588:   background: $sidebg;
                   7589: }
                   7590: 
1.383     albertel 7591: td.LC_table_cell_checkbox {
                   7592:   text-align: center;
                   7593: }
1.795     www      7594: 
                   7595: .LC_fontsize_small {
1.911     bisitz   7596:   font-size: 70%;
1.705     tempelho 7597: }
                   7598: 
1.844     bisitz   7599: #LC_breadcrumbs {
1.911     bisitz   7600:   clear:both;
                   7601:   background: $sidebg;
                   7602:   border-bottom: 1px solid $lg_border_color;
                   7603:   line-height: 2.5em;
1.933     droeschl 7604:   overflow: hidden;
1.911     bisitz   7605:   margin: 0;
                   7606:   padding: 0;
1.995     raeburn  7607:   text-align: left;
1.819     tempelho 7608: }
1.862     bisitz   7609: 
1.1098    bisitz   7610: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7611:   clear:both;
                   7612:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7613:   border: 1px solid $sidebg;
1.1098    bisitz   7614:   margin: 0 0 10px 0;
1.966     bisitz   7615:   padding: 3px;
1.995     raeburn  7616:   text-align: left;
1.822     bisitz   7617: }
                   7618: 
1.795     www      7619: .LC_fontsize_medium {
1.911     bisitz   7620:   font-size: 85%;
1.705     tempelho 7621: }
                   7622: 
1.795     www      7623: .LC_fontsize_large {
1.911     bisitz   7624:   font-size: 120%;
1.705     tempelho 7625: }
                   7626: 
1.346     albertel 7627: .LC_menubuttons_inline_text {
                   7628:   color: $font;
1.698     harmsja  7629:   font-size: 90%;
1.701     harmsja  7630:   padding-left:3px;
1.346     albertel 7631: }
                   7632: 
1.934     droeschl 7633: .LC_menubuttons_inline_text img{
                   7634:   vertical-align: middle;
                   7635: }
                   7636: 
1.1051    www      7637: li.LC_menubuttons_inline_text img {
1.951     onken    7638:   cursor:pointer;
1.1002    droeschl 7639:   text-decoration: none;
1.951     onken    7640: }
                   7641: 
1.526     www      7642: .LC_menubuttons_link {
                   7643:   text-decoration: none;
                   7644: }
1.795     www      7645: 
1.522     albertel 7646: .LC_menubuttons_category {
1.521     www      7647:   color: $font;
1.526     www      7648:   background: $pgbg;
1.521     www      7649:   font-size: larger;
                   7650:   font-weight: bold;
                   7651: }
                   7652: 
1.346     albertel 7653: td.LC_menubuttons_text {
1.911     bisitz   7654:   color: $font;
1.346     albertel 7655: }
1.706     harmsja  7656: 
1.346     albertel 7657: .LC_current_location {
                   7658:   background: $tabbg;
                   7659: }
1.795     www      7660: 
1.1286    raeburn  7661: td.LC_zero_height {
                   7662:   line-height: 0; 
                   7663:   cellpadding: 0;
                   7664: }
                   7665: 
1.938     bisitz   7666: table.LC_data_table {
1.347     albertel 7667:   border: 1px solid #000000;
1.402     albertel 7668:   border-collapse: separate;
1.426     albertel 7669:   border-spacing: 1px;
1.610     albertel 7670:   background: $pgbg;
1.347     albertel 7671: }
1.795     www      7672: 
1.422     albertel 7673: .LC_data_table_dense {
                   7674:   font-size: small;
                   7675: }
1.795     www      7676: 
1.507     raeburn  7677: table.LC_nested_outer {
                   7678:   border: 1px solid #000000;
1.589     raeburn  7679:   border-collapse: collapse;
1.803     bisitz   7680:   border-spacing: 0;
1.507     raeburn  7681:   width: 100%;
                   7682: }
1.795     www      7683: 
1.879     raeburn  7684: table.LC_innerpickbox,
1.507     raeburn  7685: table.LC_nested {
1.803     bisitz   7686:   border: none;
1.589     raeburn  7687:   border-collapse: collapse;
1.803     bisitz   7688:   border-spacing: 0;
1.507     raeburn  7689:   width: 100%;
                   7690: }
1.795     www      7691: 
1.911     bisitz   7692: table.LC_data_table tr th,
                   7693: table.LC_calendar tr th,
1.879     raeburn  7694: table.LC_prior_tries tr th,
                   7695: table.LC_innerpickbox tr th {
1.349     albertel 7696:   font-weight: bold;
                   7697:   background-color: $data_table_head;
1.801     tempelho 7698:   color:$fontmenu;
1.701     harmsja  7699:   font-size:90%;
1.347     albertel 7700: }
1.795     www      7701: 
1.879     raeburn  7702: table.LC_innerpickbox tr th,
                   7703: table.LC_innerpickbox tr td {
                   7704:   vertical-align: top;
                   7705: }
                   7706: 
1.711     raeburn  7707: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7708:   background-color: #CCCCCC;
1.711     raeburn  7709:   font-weight: bold;
                   7710:   text-align: left;
                   7711: }
1.795     www      7712: 
1.912     bisitz   7713: table.LC_data_table tr.LC_odd_row > td {
                   7714:   background-color: $data_table_light;
                   7715:   padding: 2px;
                   7716:   vertical-align: top;
                   7717: }
                   7718: 
1.809     bisitz   7719: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7720:   background-color: $data_table_light;
1.912     bisitz   7721:   vertical-align: top;
                   7722: }
                   7723: 
                   7724: table.LC_data_table tr.LC_even_row > td {
                   7725:   background-color: $data_table_dark;
1.425     albertel 7726:   padding: 2px;
1.900     bisitz   7727:   vertical-align: top;
1.347     albertel 7728: }
1.795     www      7729: 
1.809     bisitz   7730: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7731:   background-color: $data_table_dark;
1.900     bisitz   7732:   vertical-align: top;
1.347     albertel 7733: }
1.795     www      7734: 
1.425     albertel 7735: table.LC_data_table tr.LC_data_table_highlight td {
                   7736:   background-color: $data_table_darker;
                   7737: }
1.795     www      7738: 
1.639     raeburn  7739: table.LC_data_table tr td.LC_leftcol_header {
                   7740:   background-color: $data_table_head;
                   7741:   font-weight: bold;
                   7742: }
1.795     www      7743: 
1.451     albertel 7744: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7745: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7746:   font-weight: bold;
                   7747:   font-style: italic;
                   7748:   text-align: center;
                   7749:   padding: 8px;
1.347     albertel 7750: }
1.795     www      7751: 
1.1114    raeburn  7752: table.LC_data_table tr.LC_empty_row td,
                   7753: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7754:   background-color: $sidebg;
                   7755: }
                   7756: 
                   7757: table.LC_nested tr.LC_empty_row td {
                   7758:   background-color: #FFFFFF;
                   7759: }
                   7760: 
1.890     droeschl 7761: table.LC_caption {
                   7762: }
                   7763: 
1.507     raeburn  7764: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7765:   padding: 4ex
                   7766: }
1.795     www      7767: 
1.507     raeburn  7768: table.LC_nested_outer tr th {
                   7769:   font-weight: bold;
1.801     tempelho 7770:   color:$fontmenu;
1.507     raeburn  7771:   background-color: $data_table_head;
1.701     harmsja  7772:   font-size: small;
1.507     raeburn  7773:   border-bottom: 1px solid #000000;
                   7774: }
1.795     www      7775: 
1.507     raeburn  7776: table.LC_nested_outer tr td.LC_subheader {
                   7777:   background-color: $data_table_head;
                   7778:   font-weight: bold;
                   7779:   font-size: small;
                   7780:   border-bottom: 1px solid #000000;
                   7781:   text-align: right;
1.451     albertel 7782: }
1.795     www      7783: 
1.507     raeburn  7784: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7785:   background-color: #CCCCCC;
1.451     albertel 7786:   font-weight: bold;
                   7787:   font-size: small;
1.507     raeburn  7788:   text-align: center;
                   7789: }
1.795     www      7790: 
1.589     raeburn  7791: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7792: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7793:   text-align: left;
1.451     albertel 7794: }
1.795     www      7795: 
1.507     raeburn  7796: table.LC_nested td {
1.735     bisitz   7797:   background-color: #FFFFFF;
1.451     albertel 7798:   font-size: small;
1.507     raeburn  7799: }
1.795     www      7800: 
1.507     raeburn  7801: table.LC_nested_outer tr th.LC_right_item,
                   7802: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7803: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7804: table.LC_nested tr td.LC_right_item {
1.451     albertel 7805:   text-align: right;
                   7806: }
                   7807: 
1.507     raeburn  7808: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7809:   background-color: #EEEEEE;
1.451     albertel 7810: }
                   7811: 
1.473     raeburn  7812: table.LC_createuser {
                   7813: }
                   7814: 
                   7815: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7816:   font-size: small;
1.473     raeburn  7817: }
                   7818: 
                   7819: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7820:   background-color: #CCCCCC;
1.473     raeburn  7821:   font-weight: bold;
                   7822:   text-align: center;
                   7823: }
                   7824: 
1.349     albertel 7825: table.LC_calendar {
                   7826:   border: 1px solid #000000;
                   7827:   border-collapse: collapse;
1.917     raeburn  7828:   width: 98%;
1.349     albertel 7829: }
1.795     www      7830: 
1.349     albertel 7831: table.LC_calendar_pickdate {
                   7832:   font-size: xx-small;
                   7833: }
1.795     www      7834: 
1.349     albertel 7835: table.LC_calendar tr td {
                   7836:   border: 1px solid #000000;
                   7837:   vertical-align: top;
1.917     raeburn  7838:   width: 14%;
1.349     albertel 7839: }
1.795     www      7840: 
1.349     albertel 7841: table.LC_calendar tr td.LC_calendar_day_empty {
                   7842:   background-color: $data_table_dark;
                   7843: }
1.795     www      7844: 
1.779     bisitz   7845: table.LC_calendar tr td.LC_calendar_day_current {
                   7846:   background-color: $data_table_highlight;
1.777     tempelho 7847: }
1.795     www      7848: 
1.938     bisitz   7849: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7850:   background-color: $mail_new;
                   7851: }
1.795     www      7852: 
1.938     bisitz   7853: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7854:   background-color: $mail_new_hover;
                   7855: }
1.795     www      7856: 
1.938     bisitz   7857: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7858:   background-color: $mail_read;
                   7859: }
1.795     www      7860: 
1.938     bisitz   7861: /*
                   7862: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7863:   background-color: $mail_read_hover;
                   7864: }
1.938     bisitz   7865: */
1.795     www      7866: 
1.938     bisitz   7867: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7868:   background-color: $mail_replied;
                   7869: }
1.795     www      7870: 
1.938     bisitz   7871: /*
                   7872: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7873:   background-color: $mail_replied_hover;
                   7874: }
1.938     bisitz   7875: */
1.795     www      7876: 
1.938     bisitz   7877: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7878:   background-color: $mail_other;
                   7879: }
1.795     www      7880: 
1.938     bisitz   7881: /*
                   7882: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7883:   background-color: $mail_other_hover;
                   7884: }
1.938     bisitz   7885: */
1.494     raeburn  7886: 
1.777     tempelho 7887: table.LC_data_table tr > td.LC_browser_file,
                   7888: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7889:   background: #AAEE77;
1.389     albertel 7890: }
1.795     www      7891: 
1.777     tempelho 7892: table.LC_data_table tr > td.LC_browser_file_locked,
                   7893: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7894:   background: #FFAA99;
1.387     albertel 7895: }
1.795     www      7896: 
1.777     tempelho 7897: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7898:   background: #888888;
1.779     bisitz   7899: }
1.795     www      7900: 
1.777     tempelho 7901: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7902: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7903:   background: #F8F866;
1.777     tempelho 7904: }
1.795     www      7905: 
1.696     bisitz   7906: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7907:   background: #E0E8FF;
1.387     albertel 7908: }
1.696     bisitz   7909: 
1.707     bisitz   7910: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7911:   /* background: #77FF77; */
1.707     bisitz   7912: }
1.795     www      7913: 
1.707     bisitz   7914: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7915:   border-right: 8px solid #FFFF77;
1.707     bisitz   7916: }
1.795     www      7917: 
1.707     bisitz   7918: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7919:   border-right: 8px solid #FFAA77;
1.707     bisitz   7920: }
1.795     www      7921: 
1.707     bisitz   7922: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7923:   border-right: 8px solid #FF7777;
1.707     bisitz   7924: }
1.795     www      7925: 
1.707     bisitz   7926: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7927:   border-right: 8px solid #AAFF77;
1.707     bisitz   7928: }
1.795     www      7929: 
1.707     bisitz   7930: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7931:   border-right: 8px solid #11CC55;
1.707     bisitz   7932: }
                   7933: 
1.388     albertel 7934: span.LC_current_location {
1.701     harmsja  7935:   font-size:larger;
1.388     albertel 7936:   background: $pgbg;
                   7937: }
1.387     albertel 7938: 
1.1029    www      7939: span.LC_current_nav_location {
                   7940:   font-weight:bold;
                   7941:   background: $sidebg;
                   7942: }
                   7943: 
1.395     albertel 7944: span.LC_parm_menu_item {
                   7945:   font-size: larger;
                   7946: }
1.795     www      7947: 
1.395     albertel 7948: span.LC_parm_scope_all {
                   7949:   color: red;
                   7950: }
1.795     www      7951: 
1.395     albertel 7952: span.LC_parm_scope_folder {
                   7953:   color: green;
                   7954: }
1.795     www      7955: 
1.395     albertel 7956: span.LC_parm_scope_resource {
                   7957:   color: orange;
                   7958: }
1.795     www      7959: 
1.395     albertel 7960: span.LC_parm_part {
                   7961:   color: blue;
                   7962: }
1.795     www      7963: 
1.911     bisitz   7964: span.LC_parm_folder,
                   7965: span.LC_parm_symb {
1.395     albertel 7966:   font-size: x-small;
                   7967:   font-family: $mono;
                   7968:   color: #AAAAAA;
                   7969: }
                   7970: 
1.977     bisitz   7971: ul.LC_parm_parmlist li {
                   7972:   display: inline-block;
                   7973:   padding: 0.3em 0.8em;
                   7974:   vertical-align: top;
                   7975:   width: 150px;
                   7976:   border-top:1px solid $lg_border_color;
                   7977: }
                   7978: 
1.795     www      7979: td.LC_parm_overview_level_menu,
                   7980: td.LC_parm_overview_map_menu,
                   7981: td.LC_parm_overview_parm_selectors,
                   7982: td.LC_parm_overview_restrictions  {
1.396     albertel 7983:   border: 1px solid black;
                   7984:   border-collapse: collapse;
                   7985: }
1.795     www      7986: 
1.1285    raeburn  7987: span.LC_parm_recursive,
                   7988: td.LC_parm_recursive {
                   7989:   font-weight: bold;
                   7990:   font-size: smaller;
                   7991: }
                   7992: 
1.396     albertel 7993: table.LC_parm_overview_restrictions td {
                   7994:   border-width: 1px 4px 1px 4px;
                   7995:   border-style: solid;
                   7996:   border-color: $pgbg;
                   7997:   text-align: center;
                   7998: }
1.795     www      7999: 
1.396     albertel 8000: table.LC_parm_overview_restrictions th {
                   8001:   background: $tabbg;
                   8002:   border-width: 1px 4px 1px 4px;
                   8003:   border-style: solid;
                   8004:   border-color: $pgbg;
                   8005: }
1.795     www      8006: 
1.1459  ! raeburn  8007: h1.LC_helpmenu {
        !          8008:   display: inline;
        !          8009:   font-size: 100%;
        !          8010:   font-weight: normal;
        !          8011:   line-height: 1em;
        !          8012:   margin: 0;
        !          8013:   padding: 0;
        !          8014:   border: 0;
1.398     albertel 8015: }
1.795     www      8016: 
1.1456    raeburn  8017: .LC_helpdesk_headbox {
                   8018:   border: 2px groove threedface;
                   8019:   padding: 1em;
                   8020: }
                   8021: 
                   8022: h1.LC_helpdesk_legend {
                   8023:   float: left;
                   8024:   margin: -1.7em 0 0;
                   8025:   padding: 0 .5em;
1.397     albertel 8026:   background: $pgbg;
1.1456    raeburn  8027:   font-size: 1em;
                   8028:   font-weight: bold;
                   8029: }
                   8030: 
                   8031: h1.LC_helpdesk_title {
                   8032:   display: inline;
                   8033:   font-size: 1em;
                   8034:   line-height: 2.5em;
                   8035:   margin: 0;
1.803     bisitz   8036:   padding: 0;
1.1456    raeburn  8037:   vertical-align: bottom;
1.397     albertel 8038: }
1.795     www      8039: 
1.1456    raeburn  8040: .LC_helpdesk_links {
                   8041:   border: 1px solid black;
                   8042:   padding: 3px;
1.397     albertel 8043:   background: $tabbg;
1.399     albertel 8044:   text-align: center;
                   8045:   font-weight: bold;
1.1456    raeburn  8046:   display: inline;
                   8047:   margin-right: -6px;
                   8048: }
                   8049: 
                   8050: .LC_helpdesk_img,
                   8051: .LC_helpdesk_text {
                   8052:   padding: 0;
                   8053:   margin: 0;
                   8054:   border: 0;
                   8055:   display: inline;
1.397     albertel 8056: }
1.396     albertel 8057: 
1.1456    raeburn  8058: .LC_helpdesk_img a:link,
                   8059: .LC_helpdesk_img a:visited,
                   8060: .LC_helpdesk_img a:active,
                   8061: .LC_helpdesk_text a:link,
                   8062: .LC_helpdesk_text a:visited,
                   8063: .LC_helpdesk_text a:active {
1.397     albertel 8064:   text-decoration: none;
                   8065:   color: $font;
                   8066: }
1.795     www      8067: 
1.1456    raeburn  8068: div.LC_helpdesk_text a:hover {
1.397     albertel 8069:   text-decoration: underline;
                   8070:   color: $vlink;
                   8071: }
1.396     albertel 8072: 
1.417     albertel 8073: .LC_chrt_popup_exists {
                   8074:   border: 1px solid #339933;
                   8075:   margin: -1px;
                   8076: }
1.795     www      8077: 
1.417     albertel 8078: .LC_chrt_popup_up {
                   8079:   border: 1px solid yellow;
                   8080:   margin: -1px;
                   8081: }
1.795     www      8082: 
1.417     albertel 8083: .LC_chrt_popup {
                   8084:   border: 1px solid #8888FF;
                   8085:   background: #CCCCFF;
                   8086: }
1.795     www      8087: 
1.421     albertel 8088: table.LC_pick_box {
                   8089:   border-collapse: separate;
                   8090:   background: white;
                   8091:   border: 1px solid black;
                   8092:   border-spacing: 1px;
                   8093: }
1.795     www      8094: 
1.1454    raeburn  8095: table.LC_pick_box th.LC_pick_box_title {
1.850     bisitz   8096:   background: $sidebg;
1.421     albertel 8097:   font-weight: bold;
1.900     bisitz   8098:   text-align: left;
1.740     bisitz   8099:   vertical-align: top;
1.421     albertel 8100:   width: 184px;
                   8101:   padding: 8px;
                   8102: }
1.795     www      8103: 
1.579     raeburn  8104: table.LC_pick_box td.LC_pick_box_value {
                   8105:   text-align: left;
                   8106:   padding: 8px;
                   8107: }
1.795     www      8108: 
1.579     raeburn  8109: table.LC_pick_box td.LC_pick_box_select {
                   8110:   text-align: left;
                   8111:   padding: 8px;
                   8112: }
1.795     www      8113: 
1.424     albertel 8114: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   8115:   padding: 0;
1.421     albertel 8116:   height: 1px;
                   8117:   background: black;
                   8118: }
1.795     www      8119: 
1.421     albertel 8120: table.LC_pick_box td.LC_pick_box_submit {
                   8121:   text-align: right;
                   8122: }
1.795     www      8123: 
1.579     raeburn  8124: table.LC_pick_box td.LC_evenrow_value {
                   8125:   text-align: left;
                   8126:   padding: 8px;
                   8127:   background-color: $data_table_light;
                   8128: }
1.795     www      8129: 
1.579     raeburn  8130: table.LC_pick_box td.LC_oddrow_value {
                   8131:   text-align: left;
                   8132:   padding: 8px;
                   8133:   background-color: $data_table_light;
                   8134: }
1.795     www      8135: 
1.579     raeburn  8136: span.LC_helpform_receipt_cat {
                   8137:   font-weight: bold;
                   8138: }
1.795     www      8139: 
1.424     albertel 8140: table.LC_group_priv_box {
                   8141:   background: white;
                   8142:   border: 1px solid black;
                   8143:   border-spacing: 1px;
                   8144: }
1.795     www      8145: 
1.424     albertel 8146: table.LC_group_priv_box td.LC_pick_box_title {
                   8147:   background: $tabbg;
                   8148:   font-weight: bold;
                   8149:   text-align: right;
                   8150:   width: 184px;
                   8151: }
1.795     www      8152: 
1.424     albertel 8153: table.LC_group_priv_box td.LC_groups_fixed {
                   8154:   background: $data_table_light;
                   8155:   text-align: center;
                   8156: }
1.795     www      8157: 
1.424     albertel 8158: table.LC_group_priv_box td.LC_groups_optional {
                   8159:   background: $data_table_dark;
                   8160:   text-align: center;
                   8161: }
1.795     www      8162: 
1.424     albertel 8163: table.LC_group_priv_box td.LC_groups_functionality {
                   8164:   background: $data_table_darker;
                   8165:   text-align: center;
                   8166:   font-weight: bold;
                   8167: }
1.795     www      8168: 
1.424     albertel 8169: table.LC_group_priv td {
                   8170:   text-align: left;
1.803     bisitz   8171:   padding: 0;
1.424     albertel 8172: }
                   8173: 
                   8174: .LC_navbuttons {
                   8175:   margin: 2ex 0ex 2ex 0ex;
                   8176: }
1.795     www      8177: 
1.423     albertel 8178: .LC_topic_bar {
                   8179:   font-weight: bold;
                   8180:   background: $tabbg;
1.918     wenzelju 8181:   margin: 1em 0em 1em 2em;
1.805     bisitz   8182:   padding: 3px;
1.918     wenzelju 8183:   font-size: 1.2em;
1.423     albertel 8184: }
1.795     www      8185: 
1.423     albertel 8186: .LC_topic_bar span {
1.918     wenzelju 8187:   left: 0.5em;
                   8188:   position: absolute;
1.423     albertel 8189:   vertical-align: middle;
1.918     wenzelju 8190:   font-size: 1.2em;
1.423     albertel 8191: }
1.795     www      8192: 
1.423     albertel 8193: table.LC_course_group_status {
                   8194:   margin: 20px;
                   8195: }
1.795     www      8196: 
1.423     albertel 8197: table.LC_status_selector td {
                   8198:   vertical-align: top;
                   8199:   text-align: center;
1.424     albertel 8200:   padding: 4px;
                   8201: }
1.795     www      8202: 
1.599     albertel 8203: div.LC_feedback_link {
1.616     albertel 8204:   clear: both;
1.829     kalberla 8205:   background: $sidebg;
1.779     bisitz   8206:   width: 100%;
1.829     kalberla 8207:   padding-bottom: 10px;
                   8208:   border: 1px $tabbg solid;
1.833     kalberla 8209:   height: 22px;
                   8210:   line-height: 22px;
                   8211:   padding-top: 5px;
                   8212: }
                   8213: 
                   8214: div.LC_feedback_link img {
                   8215:   height: 22px;
1.867     kalberla 8216:   vertical-align:middle;
1.829     kalberla 8217: }
                   8218: 
1.911     bisitz   8219: div.LC_feedback_link a {
1.829     kalberla 8220:   text-decoration: none;
1.489     raeburn  8221: }
1.795     www      8222: 
1.867     kalberla 8223: div.LC_comblock {
1.911     bisitz   8224:   display:inline;
1.867     kalberla 8225:   color:$font;
                   8226:   font-size:90%;
                   8227: }
                   8228: 
                   8229: div.LC_feedback_link div.LC_comblock {
                   8230:   padding-left:5px;
                   8231: }
                   8232: 
                   8233: div.LC_feedback_link div.LC_comblock a {
                   8234:   color:$font;
                   8235: }
                   8236: 
1.489     raeburn  8237: span.LC_feedback_link {
1.858     bisitz   8238:   /* background: $feedback_link_bg; */
1.599     albertel 8239:   font-size: larger;
                   8240: }
1.795     www      8241: 
1.599     albertel 8242: span.LC_message_link {
1.858     bisitz   8243:   /* background: $feedback_link_bg; */
1.599     albertel 8244:   font-size: larger;
                   8245:   position: absolute;
                   8246:   right: 1em;
1.489     raeburn  8247: }
1.421     albertel 8248: 
1.515     albertel 8249: table.LC_prior_tries {
1.524     albertel 8250:   border: 1px solid #000000;
                   8251:   border-collapse: separate;
                   8252:   border-spacing: 1px;
1.515     albertel 8253: }
1.523     albertel 8254: 
1.515     albertel 8255: table.LC_prior_tries td {
1.524     albertel 8256:   padding: 2px;
1.515     albertel 8257: }
1.523     albertel 8258: 
                   8259: .LC_answer_correct {
1.795     www      8260:   background: lightgreen;
                   8261:   color: darkgreen;
                   8262:   padding: 6px;
1.523     albertel 8263: }
1.795     www      8264: 
1.523     albertel 8265: .LC_answer_charged_try {
1.797     www      8266:   background: #FFAAAA;
1.795     www      8267:   color: darkred;
                   8268:   padding: 6px;
1.523     albertel 8269: }
1.795     www      8270: 
1.779     bisitz   8271: .LC_answer_not_charged_try,
1.523     albertel 8272: .LC_answer_no_grade,
                   8273: .LC_answer_late {
1.795     www      8274:   background: lightyellow;
1.523     albertel 8275:   color: black;
1.795     www      8276:   padding: 6px;
1.523     albertel 8277: }
1.795     www      8278: 
1.523     albertel 8279: .LC_answer_previous {
1.795     www      8280:   background: lightblue;
                   8281:   color: darkblue;
                   8282:   padding: 6px;
1.523     albertel 8283: }
1.795     www      8284: 
1.779     bisitz   8285: .LC_answer_no_message {
1.777     tempelho 8286:   background: #FFFFFF;
                   8287:   color: black;
1.795     www      8288:   padding: 6px;
1.779     bisitz   8289: }
1.795     www      8290: 
1.1334    raeburn  8291: .LC_answer_unknown,
                   8292: .LC_answer_warning {
1.779     bisitz   8293:   background: orange;
                   8294:   color: black;
1.795     www      8295:   padding: 6px;
1.777     tempelho 8296: }
1.795     www      8297: 
1.1446    raeburn  8298: .LC_prob_status {
1.1447    raeburn  8299:   margin-top: 5px;
1.1446    raeburn  8300:   padding-top: 0;
                   8301:   padding-left: 0;
                   8302:   padding-bottom: 0;
                   8303:   padding-right: 5px;
                   8304: }
                   8305: 
1.1448    raeburn  8306: .LC_mail_actions {
                   8307:   float: left;
                   8308:   padding: 0;
                   8309:   margin: 6px;
                   8310: }
                   8311: 
                   8312: .LC_vertical_line {
                   8313:   width: 1px;
                   8314:   background-color: black;
                   8315:   height: 4em;
                   8316:   float: left;
                   8317:   margin: 0;
                   8318:   padding: 0;
                   8319: }
                   8320: 
1.529     albertel 8321: span.LC_prior_numerical,
                   8322: span.LC_prior_string,
                   8323: span.LC_prior_custom,
                   8324: span.LC_prior_reaction,
                   8325: span.LC_prior_math {
1.925     bisitz   8326:   font-family: $mono;
1.523     albertel 8327:   white-space: pre;
                   8328: }
                   8329: 
1.525     albertel 8330: span.LC_prior_string {
1.925     bisitz   8331:   font-family: $mono;
1.525     albertel 8332:   white-space: pre;
                   8333: }
                   8334: 
1.523     albertel 8335: table.LC_prior_option {
                   8336:   width: 100%;
                   8337:   border-collapse: collapse;
                   8338: }
1.795     www      8339: 
1.911     bisitz   8340: table.LC_prior_rank,
1.795     www      8341: table.LC_prior_match {
1.528     albertel 8342:   border-collapse: collapse;
                   8343: }
1.795     www      8344: 
1.528     albertel 8345: table.LC_prior_option tr td,
                   8346: table.LC_prior_rank tr td,
                   8347: table.LC_prior_match tr td {
1.524     albertel 8348:   border: 1px solid #000000;
1.515     albertel 8349: }
                   8350: 
1.855     bisitz   8351: .LC_nobreak {
1.544     albertel 8352:   white-space: nowrap;
1.519     raeburn  8353: }
                   8354: 
1.576     raeburn  8355: span.LC_cusr_emph {
                   8356:   font-style: italic;
                   8357: }
                   8358: 
1.633     raeburn  8359: span.LC_cusr_subheading {
                   8360:   font-weight: normal;
                   8361:   font-size: 85%;
                   8362: }
                   8363: 
1.861     bisitz   8364: div.LC_docs_entry_move {
1.859     bisitz   8365:   border: 1px solid #BBBBBB;
1.545     albertel 8366:   background: #DDDDDD;
1.861     bisitz   8367:   width: 22px;
1.859     bisitz   8368:   padding: 1px;
                   8369:   margin: 0;
1.545     albertel 8370: }
                   8371: 
1.861     bisitz   8372: table.LC_data_table tr > td.LC_docs_entry_commands,
                   8373: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 8374:   font-size: x-small;
                   8375: }
1.795     www      8376: 
1.861     bisitz   8377: .LC_docs_entry_parameter {
                   8378:   white-space: nowrap;
                   8379: }
                   8380: 
1.544     albertel 8381: .LC_docs_copy {
1.545     albertel 8382:   color: #000099;
1.544     albertel 8383: }
1.795     www      8384: 
1.544     albertel 8385: .LC_docs_cut {
1.545     albertel 8386:   color: #550044;
1.544     albertel 8387: }
1.795     www      8388: 
1.544     albertel 8389: .LC_docs_rename {
1.545     albertel 8390:   color: #009900;
1.544     albertel 8391: }
1.795     www      8392: 
1.544     albertel 8393: .LC_docs_remove {
1.545     albertel 8394:   color: #990000;
                   8395: }
                   8396: 
1.1284    raeburn  8397: .LC_docs_alias {
                   8398:   color: #440055;  
                   8399: }
                   8400: 
1.1286    raeburn  8401: .LC_domprefs_email,
1.1284    raeburn  8402: .LC_docs_alias_name,
1.547     albertel 8403: .LC_docs_reinit_warn,
                   8404: .LC_docs_ext_edit {
                   8405:   font-size: x-small;
                   8406: }
                   8407: 
1.545     albertel 8408: table.LC_docs_adddocs td,
                   8409: table.LC_docs_adddocs th {
                   8410:   border: 1px solid #BBBBBB;
                   8411:   padding: 4px;
                   8412:   background: #DDDDDD;
1.543     albertel 8413: }
                   8414: 
1.584     albertel 8415: table.LC_sty_begin {
                   8416:   background: #BBFFBB;
                   8417: }
1.795     www      8418: 
1.584     albertel 8419: table.LC_sty_end {
                   8420:   background: #FFBBBB;
                   8421: }
                   8422: 
1.589     raeburn  8423: table.LC_double_column {
1.803     bisitz   8424:   border-width: 0;
1.589     raeburn  8425:   border-collapse: collapse;
                   8426:   width: 100%;
                   8427:   padding: 2px;
                   8428: }
                   8429: 
                   8430: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  8431:   top: 2px;
1.589     raeburn  8432:   left: 2px;
                   8433:   width: 47%;
                   8434:   vertical-align: top;
                   8435: }
                   8436: 
                   8437: table.LC_double_column tr td.LC_right_col {
                   8438:   top: 2px;
1.779     bisitz   8439:   right: 2px;
1.589     raeburn  8440:   width: 47%;
                   8441:   vertical-align: top;
                   8442: }
                   8443: 
1.591     raeburn  8444: div.LC_left_float {
                   8445:   float: left;
                   8446:   padding-right: 5%;
1.597     albertel 8447:   padding-bottom: 4px;
1.591     raeburn  8448: }
                   8449: 
                   8450: div.LC_clear_float_header {
1.597     albertel 8451:   padding-bottom: 2px;
1.591     raeburn  8452: }
                   8453: 
                   8454: div.LC_clear_float_footer {
1.597     albertel 8455:   padding-top: 10px;
1.591     raeburn  8456:   clear: both;
                   8457: }
                   8458: 
1.597     albertel 8459: div.LC_grade_show_user {
1.941     bisitz   8460: /*  border-left: 5px solid $sidebg; */
                   8461:   border-top: 5px solid #000000;
                   8462:   margin: 50px 0 0 0;
1.936     bisitz   8463:   padding: 15px 0 5px 10px;
1.597     albertel 8464: }
1.795     www      8465: 
1.936     bisitz   8466: div.LC_grade_show_user_odd_row {
1.941     bisitz   8467: /*  border-left: 5px solid #000000; */
                   8468: }
                   8469: 
                   8470: div.LC_grade_show_user div.LC_Box {
                   8471:   margin-right: 50px;
1.597     albertel 8472: }
                   8473: 
                   8474: div.LC_grade_submissions,
                   8475: div.LC_grade_message_center,
1.936     bisitz   8476: div.LC_grade_info_links {
1.597     albertel 8477:   margin: 5px;
                   8478:   width: 99%;
                   8479:   background: #FFFFFF;
                   8480: }
1.795     www      8481: 
1.597     albertel 8482: div.LC_grade_submissions_header,
1.936     bisitz   8483: div.LC_grade_message_center_header {
1.705     tempelho 8484:   font-weight: bold;
                   8485:   font-size: large;
1.597     albertel 8486: }
1.795     www      8487: 
1.597     albertel 8488: div.LC_grade_submissions_body,
1.936     bisitz   8489: div.LC_grade_message_center_body {
1.597     albertel 8490:   border: 1px solid black;
                   8491:   width: 99%;
                   8492:   background: #FFFFFF;
                   8493: }
1.795     www      8494: 
1.613     albertel 8495: table.LC_scantron_action {
                   8496:   width: 100%;
                   8497: }
1.795     www      8498: 
1.613     albertel 8499: table.LC_scantron_action tr th {
1.698     harmsja  8500:   font-weight:bold;
                   8501:   font-style:normal;
1.613     albertel 8502: }
1.795     www      8503: 
1.779     bisitz   8504: .LC_edit_problem_header,
1.614     albertel 8505: div.LC_edit_problem_footer {
1.705     tempelho 8506:   font-weight: normal;
                   8507:   font-size:  medium;
1.602     albertel 8508:   margin: 2px;
1.1060    bisitz   8509:   background-color: $sidebg;
1.600     albertel 8510: }
1.795     www      8511: 
1.600     albertel 8512: div.LC_edit_problem_header,
1.602     albertel 8513: div.LC_edit_problem_header div,
1.614     albertel 8514: div.LC_edit_problem_footer,
                   8515: div.LC_edit_problem_footer div,
1.602     albertel 8516: div.LC_edit_problem_editxml_header,
                   8517: div.LC_edit_problem_editxml_header div {
1.1205    golterma 8518:   z-index: 100;
1.600     albertel 8519: }
1.795     www      8520: 
1.600     albertel 8521: div.LC_edit_problem_header_title {
1.705     tempelho 8522:   font-weight: bold;
                   8523:   font-size: larger;
1.602     albertel 8524:   background: $tabbg;
                   8525:   padding: 3px;
1.1060    bisitz   8526:   margin: 0 0 5px 0;
1.602     albertel 8527: }
1.795     www      8528: 
1.602     albertel 8529: table.LC_edit_problem_header_title {
                   8530:   width: 100%;
1.600     albertel 8531:   background: $tabbg;
1.602     albertel 8532: }
                   8533: 
1.1205    golterma 8534: div.LC_edit_actionbar {
                   8535:     background-color: $sidebg;
1.1218    droeschl 8536:     margin: 0;
                   8537:     padding: 0;
                   8538:     line-height: 200%;
1.602     albertel 8539: }
1.795     www      8540: 
1.1218    droeschl 8541: div.LC_edit_actionbar div{
                   8542:     padding: 0;
                   8543:     margin: 0;
                   8544:     display: inline-block;
1.600     albertel 8545: }
1.795     www      8546: 
1.1124    bisitz   8547: .LC_edit_opt {
                   8548:   padding-left: 1em;
                   8549:   white-space: nowrap;
                   8550: }
                   8551: 
1.1152    golterma 8552: .LC_edit_problem_latexhelper{
                   8553:     text-align: right;
                   8554: }
                   8555: 
                   8556: #LC_edit_problem_colorful div{
                   8557:     margin-left: 40px;
                   8558: }
                   8559: 
1.1205    golterma 8560: #LC_edit_problem_codemirror div{
                   8561:     margin-left: 0px;
                   8562: }
                   8563: 
1.911     bisitz   8564: img.stift {
1.803     bisitz   8565:   border-width: 0;
                   8566:   vertical-align: middle;
1.677     riegler  8567: }
1.680     riegler  8568: 
1.923     bisitz   8569: table td.LC_mainmenu_col_fieldset {
1.680     riegler  8570:   vertical-align: top;
1.777     tempelho 8571: }
1.795     www      8572: 
1.716     raeburn  8573: div.LC_createcourse {
1.911     bisitz   8574:   margin: 10px 10px 10px 10px;
1.716     raeburn  8575: }
                   8576: 
1.917     raeburn  8577: .LC_dccid {
1.1130    raeburn  8578:   float: right;
1.917     raeburn  8579:   margin: 0.2em 0 0 0;
                   8580:   padding: 0;
                   8581:   font-size: 90%;
                   8582:   display:none;
                   8583: }
                   8584: 
1.897     wenzelju 8585: ol.LC_primary_menu a:hover,
1.721     harmsja  8586: ol#LC_MenuBreadcrumbs a:hover,
                   8587: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 8588: ul#LC_secondary_menu a:hover,
1.721     harmsja  8589: .LC_FormSectionClearButton input:hover
1.795     www      8590: ul.LC_TabContent   li:hover a {
1.952     onken    8591:   color:$button_hover;
1.911     bisitz   8592:   text-decoration:none;
1.693     droeschl 8593: }
                   8594: 
1.779     bisitz   8595: h1 {
1.911     bisitz   8596:   padding: 0;
                   8597:   line-height:130%;
1.693     droeschl 8598: }
1.698     harmsja  8599: 
1.911     bisitz   8600: h2,
                   8601: h3,
                   8602: h4,
                   8603: h5,
                   8604: h6 {
                   8605:   margin: 5px 0 5px 0;
                   8606:   padding: 0;
                   8607:   line-height:130%;
1.693     droeschl 8608: }
1.795     www      8609: 
                   8610: .LC_hcell {
1.911     bisitz   8611:   padding:3px 15px 3px 15px;
                   8612:   margin: 0;
                   8613:   background-color:$tabbg;
                   8614:   color:$fontmenu;
                   8615:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8616: }
1.795     www      8617: 
1.840     bisitz   8618: .LC_Box > .LC_hcell {
1.911     bisitz   8619:   margin: 0 -10px 10px -10px;
1.835     bisitz   8620: }
                   8621: 
1.721     harmsja  8622: .LC_noBorder {
1.911     bisitz   8623:   border: 0;
1.698     harmsja  8624: }
1.693     droeschl 8625: 
1.721     harmsja  8626: .LC_FormSectionClearButton input {
1.911     bisitz   8627:   background-color:transparent;
                   8628:   border: none;
                   8629:   cursor:pointer;
                   8630:   text-decoration:underline;
1.693     droeschl 8631: }
1.763     bisitz   8632: 
                   8633: .LC_help_open_topic {
1.911     bisitz   8634:   color: #FFFFFF;
                   8635:   background-color: #EEEEFF;
                   8636:   margin: 1px;
                   8637:   padding: 4px;
                   8638:   border: 1px solid #000033;
                   8639:   white-space: nowrap;
                   8640:   /* vertical-align: middle; */
1.759     neumanie 8641: }
1.693     droeschl 8642: 
1.911     bisitz   8643: dl,
                   8644: ul,
                   8645: div,
                   8646: fieldset {
                   8647:   margin: 10px 10px 10px 0;
                   8648:   /* overflow: hidden; */
1.693     droeschl 8649: }
1.795     www      8650: 
1.1404    raeburn  8651: fieldset#LC_selectuser {
                   8652:     margin: 0;
                   8653:     padding: 0;
                   8654: }
                   8655: 
1.1211    raeburn  8656: article.geogebraweb div {
                   8657:     margin: 0;
                   8658: }
                   8659: 
1.838     bisitz   8660: fieldset > legend {
1.911     bisitz   8661:   font-weight: bold;
                   8662:   padding: 0 5px 0 5px;
1.838     bisitz   8663: }
                   8664: 
1.813     bisitz   8665: #LC_nav_bar {
1.911     bisitz   8666:   float: left;
1.995     raeburn  8667:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8668:   margin: 0 0 2px 0;
1.807     droeschl 8669: }
                   8670: 
1.916     droeschl 8671: #LC_realm {
                   8672:   margin: 0.2em 0 0 0;
                   8673:   padding: 0;
                   8674:   font-weight: bold;
                   8675:   text-align: center;
1.995     raeburn  8676:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8677: }
                   8678: 
1.911     bisitz   8679: #LC_nav_bar em {
                   8680:   font-weight: bold;
                   8681:   font-style: normal;
1.807     droeschl 8682: }
                   8683: 
1.897     wenzelju 8684: ol.LC_primary_menu {
1.934     droeschl 8685:   margin: 0;
1.1076    raeburn  8686:   padding: 0;
1.807     droeschl 8687: }
                   8688: 
1.852     droeschl 8689: ol#LC_PathBreadcrumbs {
1.911     bisitz   8690:   margin: 0;
1.693     droeschl 8691: }
                   8692: 
1.897     wenzelju 8693: ol.LC_primary_menu li {
1.1076    raeburn  8694:   color: RGB(80, 80, 80);
                   8695:   vertical-align: middle;
                   8696:   text-align: left;
                   8697:   list-style: none;
1.1205    golterma 8698:   position: relative;
1.1076    raeburn  8699:   float: left;
1.1205    golterma 8700:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8701:   line-height: 1.5em;
1.1076    raeburn  8702: }
                   8703: 
1.1205    golterma 8704: ol.LC_primary_menu li a,
                   8705: ol.LC_primary_menu li p {
1.1076    raeburn  8706:   display: block;
                   8707:   margin: 0;
                   8708:   padding: 0 5px 0 10px;
                   8709:   text-decoration: none;
                   8710: }
                   8711: 
1.1205    golterma 8712: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8713:   display: inline-block;
                   8714:   width: 95%;
                   8715:   text-align: left;
                   8716: }
                   8717: 
                   8718: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8719:   display: inline-block;	
                   8720:   width: 5%;
                   8721:   float: right;
                   8722:   text-align: right;
                   8723:   font-size: 70%;
                   8724: }
                   8725: 
                   8726: ol.LC_primary_menu ul {
1.1076    raeburn  8727:   display: none;
1.1205    golterma 8728:   width: 15em;
1.1076    raeburn  8729:   background-color: $data_table_light;
1.1205    golterma 8730:   position: absolute;
                   8731:   top: 100%;
1.1076    raeburn  8732: }
                   8733: 
1.1205    golterma 8734: ol.LC_primary_menu ul ul {
                   8735:   left: 100%;
                   8736:   top: 0;
                   8737: }
                   8738: 
                   8739: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8740:   display: block;
                   8741:   position: absolute;
                   8742:   margin: 0;
                   8743:   padding: 0;
1.1078    raeburn  8744:   z-index: 2;
1.1076    raeburn  8745: }
                   8746: 
                   8747: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8748: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8749:   font-size: 90%;
1.911     bisitz   8750:   vertical-align: top;
1.1076    raeburn  8751:   float: none;
1.1079    raeburn  8752:   border-left: 1px solid black;
                   8753:   border-right: 1px solid black;
1.1205    golterma 8754: /* A dark bottom border to visualize different menu options; 
                   8755: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8756:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8757: }
                   8758: 
1.1205    golterma 8759: ol.LC_primary_menu li li p:hover {
                   8760:   color:$button_hover;
                   8761:   text-decoration:none;
                   8762:   background-color:$data_table_dark;
1.1076    raeburn  8763: }
                   8764: 
                   8765: ol.LC_primary_menu li li a:hover {
                   8766:    color:$button_hover;
                   8767:    background-color:$data_table_dark;
1.693     droeschl 8768: }
                   8769: 
1.1205    golterma 8770: /* Font-size equal to the size of the predecessors*/
                   8771: ol.LC_primary_menu li:hover li li {
                   8772:   font-size: 100%;
                   8773: }
                   8774: 
1.897     wenzelju 8775: ol.LC_primary_menu li img {
1.911     bisitz   8776:   vertical-align: bottom;
1.934     droeschl 8777:   height: 1.1em;
1.1077    raeburn  8778:   margin: 0.2em 0 0 0;
1.693     droeschl 8779: }
                   8780: 
1.897     wenzelju 8781: ol.LC_primary_menu a {
1.911     bisitz   8782:   color: RGB(80, 80, 80);
                   8783:   text-decoration: none;
1.693     droeschl 8784: }
1.795     www      8785: 
1.949     droeschl 8786: ol.LC_primary_menu a.LC_new_message {
                   8787:   font-weight:bold;
                   8788:   color: darkred;
                   8789: }
                   8790: 
1.975     raeburn  8791: ol.LC_docs_parameters {
                   8792:   margin-left: 0;
                   8793:   padding: 0;
                   8794:   list-style: none;
                   8795: }
                   8796: 
                   8797: ol.LC_docs_parameters li {
                   8798:   margin: 0;
                   8799:   padding-right: 20px;
                   8800:   display: inline;
                   8801: }
                   8802: 
1.976     raeburn  8803: ol.LC_docs_parameters li:before {
                   8804:   content: "\\002022 \\0020";
                   8805: }
                   8806: 
                   8807: li.LC_docs_parameters_title {
                   8808:   font-weight: bold;
                   8809: }
                   8810: 
                   8811: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8812:   content: "";
                   8813: }
                   8814: 
1.897     wenzelju 8815: ul#LC_secondary_menu {
1.1107    raeburn  8816:   clear: right;
1.911     bisitz   8817:   color: $fontmenu;
                   8818:   background: $tabbg;
                   8819:   list-style: none;
                   8820:   padding: 0;
                   8821:   margin: 0;
                   8822:   width: 100%;
1.995     raeburn  8823:   text-align: left;
1.1107    raeburn  8824:   float: left;
1.808     droeschl 8825: }
                   8826: 
1.897     wenzelju 8827: ul#LC_secondary_menu li {
1.911     bisitz   8828:   font-weight: bold;
                   8829:   line-height: 1.8em;
1.1107    raeburn  8830:   border-right: 1px solid black;
                   8831:   float: left;
                   8832: }
                   8833: 
                   8834: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8835:   background-color: $data_table_light;
                   8836: }
                   8837: 
                   8838: ul#LC_secondary_menu li a {
1.911     bisitz   8839:   padding: 0 0.8em;
1.1107    raeburn  8840: }
                   8841: 
                   8842: ul#LC_secondary_menu li ul {
                   8843:   display: none;
                   8844: }
                   8845: 
                   8846: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8847:   display: block;
                   8848:   position: absolute;
                   8849:   margin: 0;
                   8850:   padding: 0;
                   8851:   list-style:none;
                   8852:   float: none;
                   8853:   background-color: $data_table_light;
                   8854:   z-index: 2;
                   8855:   margin-left: -1px;
                   8856: }
                   8857: 
                   8858: ul#LC_secondary_menu li ul li {
                   8859:   font-size: 90%;
                   8860:   vertical-align: top;
                   8861:   border-left: 1px solid black;
1.911     bisitz   8862:   border-right: 1px solid black;
1.1119    raeburn  8863:   background-color: $data_table_light;
1.1107    raeburn  8864:   list-style:none;
                   8865:   float: none;
                   8866: }
                   8867: 
                   8868: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8869:   background-color: $data_table_dark;
1.807     droeschl 8870: }
                   8871: 
1.847     tempelho 8872: ul.LC_TabContent {
1.911     bisitz   8873:   display:block;
                   8874:   background: $sidebg;
                   8875:   border-bottom: solid 1px $lg_border_color;
                   8876:   list-style:none;
1.1020    raeburn  8877:   margin: -1px -10px 0 -10px;
1.911     bisitz   8878:   padding: 0;
1.693     droeschl 8879: }
                   8880: 
1.795     www      8881: ul.LC_TabContent li,
                   8882: ul.LC_TabContentBigger li {
1.911     bisitz   8883:   float:left;
1.741     harmsja  8884: }
1.795     www      8885: 
1.897     wenzelju 8886: ul#LC_secondary_menu li a {
1.911     bisitz   8887:   color: $fontmenu;
                   8888:   text-decoration: none;
1.693     droeschl 8889: }
1.795     www      8890: 
1.721     harmsja  8891: ul.LC_TabContent {
1.952     onken    8892:   min-height:20px;
1.721     harmsja  8893: }
1.795     www      8894: 
                   8895: ul.LC_TabContent li {
1.911     bisitz   8896:   vertical-align:middle;
1.959     onken    8897:   padding: 0 16px 0 10px;
1.911     bisitz   8898:   background-color:$tabbg;
                   8899:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8900:   border-left: solid 1px $font;
1.721     harmsja  8901: }
1.795     www      8902: 
1.847     tempelho 8903: ul.LC_TabContent .right {
1.911     bisitz   8904:   float:right;
1.847     tempelho 8905: }
                   8906: 
1.911     bisitz   8907: ul.LC_TabContent li a,
                   8908: ul.LC_TabContent li {
                   8909:   color:rgb(47,47,47);
                   8910:   text-decoration:none;
                   8911:   font-size:95%;
                   8912:   font-weight:bold;
1.952     onken    8913:   min-height:20px;
                   8914: }
                   8915: 
1.959     onken    8916: ul.LC_TabContent li a:hover,
                   8917: ul.LC_TabContent li a:focus {
1.952     onken    8918:   color: $button_hover;
1.959     onken    8919:   background:none;
                   8920:   outline:none;
1.952     onken    8921: }
                   8922: 
                   8923: ul.LC_TabContent li:hover {
                   8924:   color: $button_hover;
                   8925:   cursor:pointer;
1.721     harmsja  8926: }
1.795     www      8927: 
1.911     bisitz   8928: ul.LC_TabContent li.active {
1.952     onken    8929:   color: $font;
1.911     bisitz   8930:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8931:   border-bottom:solid 1px #FFFFFF;
                   8932:   cursor: default;
1.744     ehlerst  8933: }
1.795     www      8934: 
1.959     onken    8935: ul.LC_TabContent li.active a {
                   8936:   color:$font;
                   8937:   background:#FFFFFF;
                   8938:   outline: none;
                   8939: }
1.1047    raeburn  8940: 
                   8941: ul.LC_TabContent li.goback {
                   8942:   float: left;
                   8943:   border-left: none;
                   8944: }
                   8945: 
1.870     tempelho 8946: #maincoursedoc {
1.911     bisitz   8947:   clear:both;
1.870     tempelho 8948: }
                   8949: 
                   8950: ul.LC_TabContentBigger {
1.911     bisitz   8951:   display:block;
                   8952:   list-style:none;
                   8953:   padding: 0;
1.870     tempelho 8954: }
                   8955: 
1.795     www      8956: ul.LC_TabContentBigger li {
1.911     bisitz   8957:   vertical-align:bottom;
                   8958:   height: 30px;
                   8959:   font-size:110%;
                   8960:   font-weight:bold;
                   8961:   color: #737373;
1.841     tempelho 8962: }
                   8963: 
1.957     onken    8964: ul.LC_TabContentBigger li.active {
                   8965:   position: relative;
                   8966:   top: 1px;
                   8967: }
                   8968: 
1.870     tempelho 8969: ul.LC_TabContentBigger li a {
1.911     bisitz   8970:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8971:   height: 30px;
                   8972:   line-height: 30px;
                   8973:   text-align: center;
                   8974:   display: block;
                   8975:   text-decoration: none;
1.958     onken    8976:   outline: none;  
1.741     harmsja  8977: }
1.795     www      8978: 
1.870     tempelho 8979: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8980:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8981:   color:$font;
1.744     ehlerst  8982: }
1.795     www      8983: 
1.870     tempelho 8984: ul.LC_TabContentBigger li b {
1.911     bisitz   8985:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8986:   display: block;
                   8987:   float: left;
                   8988:   padding: 0 30px;
1.957     onken    8989:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8990: }
                   8991: 
1.956     onken    8992: ul.LC_TabContentBigger li:hover b {
                   8993:   color:$button_hover;
                   8994: }
                   8995: 
1.870     tempelho 8996: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8997:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8998:   color:$font;
1.957     onken    8999:   border: 0;
1.741     harmsja  9000: }
1.693     droeschl 9001: 
1.870     tempelho 9002: 
1.862     bisitz   9003: ul.LC_CourseBreadcrumbs {
                   9004:   background: $sidebg;
1.1020    raeburn  9005:   height: 2em;
1.862     bisitz   9006:   padding-left: 10px;
1.1020    raeburn  9007:   margin: 0;
1.862     bisitz   9008:   list-style-position: inside;
                   9009: }
                   9010: 
1.911     bisitz   9011: ol#LC_MenuBreadcrumbs,
1.862     bisitz   9012: ol#LC_PathBreadcrumbs {
1.911     bisitz   9013:   padding-left: 10px;
                   9014:   margin: 0;
1.933     droeschl 9015:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 9016: }
                   9017: 
1.911     bisitz   9018: ol#LC_MenuBreadcrumbs li,
                   9019: ol#LC_PathBreadcrumbs li,
1.862     bisitz   9020: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   9021:   display: inline;
1.933     droeschl 9022:   white-space: normal;  
1.693     droeschl 9023: }
                   9024: 
1.823     bisitz   9025: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   9026: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   9027:   text-decoration: none;
                   9028:   font-size:90%;
1.693     droeschl 9029: }
1.795     www      9030: 
1.969     droeschl 9031: ol#LC_MenuBreadcrumbs h1 {
                   9032:   display: inline;
                   9033:   font-size: 90%;
                   9034:   line-height: 2.5em;
                   9035:   margin: 0;
                   9036:   padding: 0;
                   9037: }
                   9038: 
1.795     www      9039: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   9040:   text-decoration:none;
                   9041:   font-size:100%;
                   9042:   font-weight:bold;
1.693     droeschl 9043: }
1.795     www      9044: 
1.840     bisitz   9045: .LC_Box {
1.911     bisitz   9046:   border: solid 1px $lg_border_color;
                   9047:   padding: 0 10px 10px 10px;
1.746     neumanie 9048: }
1.795     www      9049: 
1.1020    raeburn  9050: .LC_DocsBox {
                   9051:   border: solid 1px $lg_border_color;
                   9052:   padding: 0 0 10px 10px;
                   9053: }
                   9054: 
1.795     www      9055: .LC_AboutMe_Image {
1.911     bisitz   9056:   float:left;
                   9057:   margin-right:10px;
1.747     neumanie 9058: }
1.795     www      9059: 
                   9060: .LC_Clear_AboutMe_Image {
1.911     bisitz   9061:   clear:left;
1.747     neumanie 9062: }
1.795     www      9063: 
1.721     harmsja  9064: dl.LC_ListStyleClean dt {
1.911     bisitz   9065:   padding-right: 5px;
                   9066:   display: table-header-group;
1.693     droeschl 9067: }
                   9068: 
1.721     harmsja  9069: dl.LC_ListStyleClean dd {
1.911     bisitz   9070:   display: table-row;
1.693     droeschl 9071: }
                   9072: 
1.721     harmsja  9073: .LC_ListStyleClean,
                   9074: .LC_ListStyleSimple,
                   9075: .LC_ListStyleNormal,
1.795     www      9076: .LC_ListStyleSpecial {
1.911     bisitz   9077:   /* display:block; */
                   9078:   list-style-position: inside;
                   9079:   list-style-type: none;
                   9080:   overflow: hidden;
                   9081:   padding: 0;
1.693     droeschl 9082: }
                   9083: 
1.721     harmsja  9084: .LC_ListStyleSimple li,
                   9085: .LC_ListStyleSimple dd,
                   9086: .LC_ListStyleNormal li,
                   9087: .LC_ListStyleNormal dd,
                   9088: .LC_ListStyleSpecial li,
1.795     www      9089: .LC_ListStyleSpecial dd {
1.911     bisitz   9090:   margin: 0;
                   9091:   padding: 5px 5px 5px 10px;
                   9092:   clear: both;
1.693     droeschl 9093: }
                   9094: 
1.721     harmsja  9095: .LC_ListStyleClean li,
                   9096: .LC_ListStyleClean dd {
1.911     bisitz   9097:   padding-top: 0;
                   9098:   padding-bottom: 0;
1.693     droeschl 9099: }
                   9100: 
1.721     harmsja  9101: .LC_ListStyleSimple dd,
1.795     www      9102: .LC_ListStyleSimple li {
1.911     bisitz   9103:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 9104: }
                   9105: 
1.721     harmsja  9106: .LC_ListStyleSpecial li,
                   9107: .LC_ListStyleSpecial dd {
1.911     bisitz   9108:   list-style-type: none;
                   9109:   background-color: RGB(220, 220, 220);
                   9110:   margin-bottom: 4px;
1.693     droeschl 9111: }
                   9112: 
1.721     harmsja  9113: table.LC_SimpleTable {
1.911     bisitz   9114:   margin:5px;
                   9115:   border:solid 1px $lg_border_color;
1.795     www      9116: }
1.693     droeschl 9117: 
1.721     harmsja  9118: table.LC_SimpleTable tr {
1.911     bisitz   9119:   padding: 0;
                   9120:   border:solid 1px $lg_border_color;
1.693     droeschl 9121: }
1.795     www      9122: 
                   9123: table.LC_SimpleTable thead {
1.911     bisitz   9124:   background:rgb(220,220,220);
1.693     droeschl 9125: }
                   9126: 
1.721     harmsja  9127: div.LC_columnSection {
1.911     bisitz   9128:   display: block;
                   9129:   clear: both;
                   9130:   overflow: hidden;
                   9131:   margin: 0;
1.693     droeschl 9132: }
                   9133: 
1.721     harmsja  9134: div.LC_columnSection>* {
1.911     bisitz   9135:   float: left;
                   9136:   margin: 10px 20px 10px 0;
                   9137:   overflow:hidden;
1.693     droeschl 9138: }
1.721     harmsja  9139: 
1.795     www      9140: table em {
1.911     bisitz   9141:   font-weight: bold;
                   9142:   font-style: normal;
1.748     schulted 9143: }
1.795     www      9144: 
1.779     bisitz   9145: table.LC_tableBrowseRes,
1.795     www      9146: table.LC_tableOfContent {
1.911     bisitz   9147:   border:none;
                   9148:   border-spacing: 1px;
                   9149:   padding: 3px;
                   9150:   background-color: #FFFFFF;
                   9151:   font-size: 90%;
1.753     droeschl 9152: }
1.789     droeschl 9153: 
1.911     bisitz   9154: table.LC_tableOfContent {
                   9155:   border-collapse: collapse;
1.789     droeschl 9156: }
                   9157: 
1.771     droeschl 9158: table.LC_tableBrowseRes a,
1.768     schulted 9159: table.LC_tableOfContent a {
1.911     bisitz   9160:   background-color: transparent;
                   9161:   text-decoration: none;
1.753     droeschl 9162: }
                   9163: 
1.795     www      9164: table.LC_tableOfContent img {
1.911     bisitz   9165:   border: none;
                   9166:   height: 1.3em;
                   9167:   vertical-align: text-bottom;
                   9168:   margin-right: 0.3em;
1.753     droeschl 9169: }
1.757     schulted 9170: 
1.795     www      9171: a#LC_content_toolbar_firsthomework {
1.911     bisitz   9172:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  9173: }
                   9174: 
1.795     www      9175: a#LC_content_toolbar_everything {
1.911     bisitz   9176:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  9177: }
                   9178: 
1.795     www      9179: a#LC_content_toolbar_uncompleted {
1.911     bisitz   9180:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  9181: }
                   9182: 
1.795     www      9183: #LC_content_toolbar_clearbubbles {
1.911     bisitz   9184:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  9185: }
                   9186: 
1.795     www      9187: a#LC_content_toolbar_changefolder {
1.911     bisitz   9188:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 9189: }
                   9190: 
1.795     www      9191: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   9192:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 9193: }
                   9194: 
1.1043    raeburn  9195: a#LC_content_toolbar_edittoplevel {
                   9196:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   9197: }
                   9198: 
1.1384    raeburn  9199: a#LC_content_toolbar_printout {
                   9200:   background-image:url(/res/adm/pages/printout.gif);
                   9201: }
                   9202: 
1.795     www      9203: ul#LC_toolbar li a:hover {
1.911     bisitz   9204:   background-position: bottom center;
1.757     schulted 9205: }
                   9206: 
1.795     www      9207: ul#LC_toolbar {
1.911     bisitz   9208:   padding: 0;
                   9209:   margin: 2px;
                   9210:   list-style:none;
1.1449    raeburn  9211:   display:inline;
1.911     bisitz   9212:   background-color:white;
1.1082    raeburn  9213:   overflow: auto;
1.757     schulted 9214: }
                   9215: 
1.795     www      9216: ul#LC_toolbar li {
1.911     bisitz   9217:   border:1px solid white;
                   9218:   padding: 0;
                   9219:   margin: 0;
                   9220:   float: left;
                   9221:   display:inline;
                   9222:   vertical-align:middle;
1.1082    raeburn  9223:   white-space: nowrap;
1.911     bisitz   9224: }
1.757     schulted 9225: 
1.783     amueller 9226: 
1.795     www      9227: a.LC_toolbarItem {
1.911     bisitz   9228:   display:block;
                   9229:   padding: 0;
                   9230:   margin: 0;
                   9231:   height: 32px;
                   9232:   width: 32px;
                   9233:   color:white;
                   9234:   border: none;
                   9235:   background-repeat:no-repeat;
                   9236:   background-color:transparent;
1.757     schulted 9237: }
                   9238: 
1.1449    raeburn  9239: .LC_navtools {
                   9240:   display: inline-block;
                   9241:   padding: 0;
                   9242:   margin: 2px;
                   9243:   vertical-align: middle;
                   9244: }
                   9245: 
1.915     droeschl 9246: ul.LC_funclist {
                   9247:     margin: 0;
                   9248:     padding: 0.5em 1em 0.5em 0;
                   9249: }
                   9250: 
1.933     droeschl 9251: ul.LC_funclist > li:first-child {
                   9252:     font-weight:bold; 
                   9253:     margin-left:0.8em;
                   9254: }
                   9255: 
1.915     droeschl 9256: ul.LC_funclist + ul.LC_funclist {
                   9257:     /* 
                   9258:        left border as a seperator if we have more than
                   9259:        one list 
                   9260:     */
                   9261:     border-left: 1px solid $sidebg;
                   9262:     /* 
                   9263:        this hides the left border behind the border of the 
                   9264:        outer box if element is wrapped to the next 'line' 
                   9265:     */
                   9266:     margin-left: -1px;
                   9267: }
                   9268: 
1.843     bisitz   9269: ul.LC_funclist li {
1.915     droeschl 9270:   display: inline;
1.782     bisitz   9271:   white-space: nowrap;
1.915     droeschl 9272:   margin: 0 0 0 25px;
                   9273:   line-height: 150%;
1.782     bisitz   9274: }
                   9275: 
1.974     wenzelju 9276: .LC_hidden {
                   9277:   display: none;
                   9278: }
                   9279: 
1.1030    www      9280: .LCmodal-overlay {
                   9281: 		position:fixed;
                   9282: 		top:0;
                   9283: 		right:0;
                   9284: 		bottom:0;
                   9285: 		left:0;
                   9286: 		height:100%;
                   9287: 		width:100%;
                   9288: 		margin:0;
                   9289: 		padding:0;
                   9290: 		background:#999;
                   9291: 		opacity:.75;
                   9292: 		filter: alpha(opacity=75);
                   9293: 		-moz-opacity: 0.75;
                   9294: 		z-index:101;
                   9295: }
                   9296: 
                   9297: * html .LCmodal-overlay {   
                   9298: 		position: absolute;
                   9299: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   9300: }
                   9301: 
                   9302: .LCmodal-window {
                   9303: 		position:fixed;
                   9304: 		top:50%;
                   9305: 		left:50%;
                   9306: 		margin:0;
                   9307: 		padding:0;
                   9308: 		z-index:102;
                   9309: 	}
                   9310: 
                   9311: * html .LCmodal-window {
                   9312: 		position:absolute;
                   9313: }
                   9314: 
                   9315: .LCclose-window {
                   9316: 		position:absolute;
                   9317: 		width:32px;
                   9318: 		height:32px;
                   9319: 		right:8px;
                   9320: 		top:8px;
                   9321: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   9322: 		text-indent:-99999px;
                   9323: 		overflow:hidden;
                   9324: 		cursor:pointer;
                   9325: }
                   9326: 
1.1369    raeburn  9327: .LCisDisabled {
                   9328:   cursor: not-allowed;
                   9329:   opacity: 0.5;
                   9330: }
                   9331: 
                   9332: a[aria-disabled="true"] {
                   9333:   color: currentColor;
                   9334:   display: inline-block;  /* For IE11/ MS Edge bug */
                   9335:   pointer-events: none;
                   9336:   text-decoration: none;
                   9337: }
                   9338: 
1.1335    raeburn  9339: pre.LC_wordwrap {
                   9340:   white-space: pre-wrap;
                   9341:   white-space: -moz-pre-wrap;
                   9342:   white-space: -pre-wrap;
                   9343:   white-space: -o-pre-wrap;
                   9344:   word-wrap: break-word;
                   9345: }
                   9346: 
1.1100    raeburn  9347: /*
1.1231    damieng  9348:   styles used for response display
                   9349: */
                   9350: div.LC_radiofoil, div.LC_rankfoil {
                   9351:   margin: .5em 0em .5em 0em;
                   9352: }
                   9353: table.LC_itemgroup {
                   9354:   margin-top: 1em;
                   9355: }
                   9356: 
                   9357: /*
1.1100    raeburn  9358:   styles used by TTH when "Default set of options to pass to tth/m
                   9359:   when converting TeX" in course settings has been set
                   9360: 
                   9361:   option passed: -t
                   9362: 
                   9363: */
                   9364: 
                   9365: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   9366: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   9367: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   9368: td div.norm {line-height:normal;}
                   9369: 
                   9370: /*
                   9371:   option passed -y3
                   9372: */
                   9373: 
                   9374: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   9375: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   9376: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   9377: 
1.1230    damieng  9378: /*
                   9379:   sections with roles, for content only
                   9380: */
                   9381: section[class^="role-"] {
                   9382:   padding-left: 10px;
                   9383:   padding-right: 5px;
                   9384:   margin-top: 8px;
                   9385:   margin-bottom: 8px;
                   9386:   border: 1px solid #2A4;
                   9387:   border-radius: 5px;
                   9388:   box-shadow: 0px 1px 1px #BBB;
                   9389: }
                   9390: section[class^="role-"]>h1 {
                   9391:   position: relative;
                   9392:   margin: 0px;
                   9393:   padding-top: 10px;
                   9394:   padding-left: 40px;
                   9395: }
                   9396: section[class^="role-"]>h1:before {
                   9397:   position: absolute;
                   9398:   left: -5px;
                   9399:   top: 5px;
                   9400: }
                   9401: section.role-activity>h1:before {
                   9402:   content:url('/adm/daxe/images/section_icons/activity.png');
                   9403: }
                   9404: section.role-advice>h1:before {
                   9405:   content:url('/adm/daxe/images/section_icons/advice.png');
                   9406: }
                   9407: section.role-bibliography>h1:before {
                   9408:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   9409: }
                   9410: section.role-citation>h1:before {
                   9411:   content:url('/adm/daxe/images/section_icons/citation.png');
                   9412: }
                   9413: section.role-conclusion>h1:before {
                   9414:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   9415: }
                   9416: section.role-definition>h1:before {
                   9417:   content:url('/adm/daxe/images/section_icons/definition.png');
                   9418: }
                   9419: section.role-demonstration>h1:before {
                   9420:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   9421: }
                   9422: section.role-example>h1:before {
                   9423:   content:url('/adm/daxe/images/section_icons/example.png');
                   9424: }
                   9425: section.role-explanation>h1:before {
                   9426:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   9427: }
                   9428: section.role-introduction>h1:before {
                   9429:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   9430: }
                   9431: section.role-method>h1:before {
                   9432:   content:url('/adm/daxe/images/section_icons/method.png');
                   9433: }
                   9434: section.role-more_information>h1:before {
                   9435:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   9436: }
                   9437: section.role-objectives>h1:before {
                   9438:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   9439: }
                   9440: section.role-prerequisites>h1:before {
                   9441:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   9442: }
                   9443: section.role-remark>h1:before {
                   9444:   content:url('/adm/daxe/images/section_icons/remark.png');
                   9445: }
                   9446: section.role-reminder>h1:before {
                   9447:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   9448: }
                   9449: section.role-summary>h1:before {
                   9450:   content:url('/adm/daxe/images/section_icons/summary.png');
                   9451: }
                   9452: section.role-syntax>h1:before {
                   9453:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   9454: }
                   9455: section.role-warning>h1:before {
                   9456:   content:url('/adm/daxe/images/section_icons/warning.png');
                   9457: }
                   9458: 
1.1269    raeburn  9459: #LC_minitab_header {
                   9460:   float:left;
                   9461:   width:100%;
                   9462:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   9463:   font-size:93%;
                   9464:   line-height:normal;
                   9465:   margin: 0.5em 0 0.5em 0;
                   9466: }
                   9467: #LC_minitab_header ul {
                   9468:   margin:0;
                   9469:   padding:10px 10px 0;
                   9470:   list-style:none;
                   9471: }
                   9472: #LC_minitab_header li {
                   9473:   float:left;
                   9474:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   9475:   margin:0;
                   9476:   padding:0 0 0 9px;
                   9477: }
                   9478: #LC_minitab_header a {
                   9479:   display:block;
                   9480:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   9481:   padding:5px 15px 4px 6px;
                   9482: }
                   9483: #LC_minitab_header #LC_current_minitab {
                   9484:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   9485: }
                   9486: #LC_minitab_header #LC_current_minitab a {
                   9487:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   9488:   padding-bottom:5px;
                   9489: }
                   9490: 
                   9491: 
1.343     albertel 9492: END
                   9493: }
                   9494: 
1.306     albertel 9495: =pod
                   9496: 
                   9497: =item * &headtag()
                   9498: 
                   9499: Returns a uniform footer for LON-CAPA web pages.
                   9500: 
1.307     albertel 9501: Inputs: $title - optional title for the head
                   9502:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 9503:         $args - optional arguments
1.319     albertel 9504:             force_register - if is true call registerurl so the remote is 
                   9505:                              informed
1.415     albertel 9506:             redirect       -> array ref of
                   9507:                                    1- seconds before redirect occurs
                   9508:                                    2- url to redirect to
                   9509:                                    3- whether the side effect should occur
1.315     albertel 9510:                            (side effect of setting 
                   9511:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  9512:                                redirected to)
                   9513:                                    4- whether the redirect target should be
                   9514:                                       the opener of the current (pop-up)
                   9515:                                       window (side effect of setting
                   9516:                                       $env{'internal.head.to_opener'} to
                   9517:                                       1, if true.
1.1388    raeburn  9518:                                    5- whether encrypt check should be skipped
1.352     albertel 9519:             domain         -> force to color decorate a page for a specific
                   9520:                                domain
                   9521:             function       -> force usage of a specific rolish color scheme
                   9522:             bgcolor        -> override the default page bgcolor
1.460     albertel 9523:             no_auto_mt_title
                   9524:                            -> prevent &mt()ing the title arg
1.464     albertel 9525: 
1.306     albertel 9526: =cut
                   9527: 
                   9528: sub headtag {
1.313     albertel 9529:     my ($title,$head_extra,$args) = @_;
1.306     albertel 9530:     
1.363     albertel 9531:     my $function = $args->{'function'} || &get_users_function();
                   9532:     my $domain   = $args->{'domain'}   || &determinedomain();
                   9533:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  9534:     my $httphost = $args->{'use_absolute'};
1.418     albertel 9535:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 9536: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 9537: 		   #time(),
1.418     albertel 9538: 		   $env{'environment.color.timestamp'},
1.363     albertel 9539: 		   $function,$domain,$bgcolor);
                   9540: 
1.369     www      9541:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 9542: 
1.308     albertel 9543:     my $result =
                   9544: 	'<head>'.
1.1160    raeburn  9545: 	&font_settings($args);
1.319     albertel 9546: 
1.1188    raeburn  9547:     my $inhibitprint;
                   9548:     if ($args->{'print_suppress'}) {
                   9549:         $inhibitprint = &print_suppression();
                   9550:     }
1.1064    raeburn  9551: 
1.1439    raeburn  9552:     if (!$args->{'frameset'} && !$args->{'switchserver'}) {
1.461     albertel 9553: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   9554:     }
1.962     droeschl 9555:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   9556:         $result .= Apache::lonxml::display_title();
1.319     albertel 9557:     }
1.436     albertel 9558:     if (!$args->{'no_nav_bar'} 
                   9559: 	&& !$args->{'only_body'}
1.1438    raeburn  9560: 	&& !$args->{'frameset'}
                   9561: 	&& !$args->{'switchserver'}) {
1.1154    raeburn  9562: 	$result .= &help_menu_js($httphost);
1.1032    www      9563:         $result.=&modal_window();
1.1038    www      9564:         $result.=&togglebox_script();
1.1034    www      9565:         $result.=&wishlist_window();
1.1041    www      9566:         $result.=&LCprogressbarUpdate_script();
1.1034    www      9567:     } else {
                   9568:         if ($args->{'add_modal'}) {
                   9569:            $result.=&modal_window();
                   9570:         }
                   9571:         if ($args->{'add_wishlist'}) {
                   9572:            $result.=&wishlist_window();
                   9573:         }
1.1038    www      9574:         if ($args->{'add_togglebox'}) {
                   9575:            $result.=&togglebox_script();
                   9576:         }
1.1041    www      9577:         if ($args->{'add_progressbar'}) {
                   9578:            $result.=&LCprogressbarUpdate_script();
                   9579:         }
1.436     albertel 9580:     }
1.314     albertel 9581:     if (ref($args->{'redirect'})) {
1.1388    raeburn  9582: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   9583:         if (!$skip_enc_check) {
                   9584:             $url = &Apache::lonenc::check_encrypt($url);
                   9585:         }
1.414     albertel 9586: 	if (!$inhibit_continue) {
                   9587: 	    $env{'internal.head.redirect'} = $url;
                   9588: 	}
1.1386    raeburn  9589: 	$result.=<<"ADDMETA";
1.313     albertel 9590: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  9591: ADDMETA
                   9592:         if ($to_opener) {
                   9593:             $env{'internal.head.to_opener'} = 1;
                   9594:             my $dest = &js_escape($url);
                   9595:             my $timeout = int($time * 1000);
                   9596:             $result .=<<"ENDJS";
                   9597: <script type="text/javascript">
                   9598: // <![CDATA[
                   9599: function LC_To_Opener() {
                   9600:     var dest = '$dest';
                   9601:     if (dest != '') {
                   9602:         if (window.opener != null && !window.opener.closed) {
                   9603:             window.opener.location.href=dest;
                   9604:             window.close();
                   9605:         } else {
                   9606:             window.location.href=dest;
                   9607:         }
                   9608:     }
                   9609: }
                   9610: \$(document).ready(function () {
                   9611:     setTimeout('LC_To_Opener()',$timeout);
                   9612: });
                   9613: // ]]>
                   9614: </script>
                   9615: ENDJS
                   9616:         } else {
                   9617:             $result.=<<"ADDMETA";
1.344     albertel 9618: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9619: ADDMETA
1.1386    raeburn  9620:         }
1.1210    raeburn  9621:     } else {
                   9622:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9623:             my $requrl = $env{'request.uri'};
                   9624:             if ($requrl eq '') {
                   9625:                 $requrl = $ENV{'REQUEST_URI'};
                   9626:                 $requrl =~ s/\?.+$//;
                   9627:             }
                   9628:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9629:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9630:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9631:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9632:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9633:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9634:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9635:                     my ($offload,$offloadoth);
1.1210    raeburn  9636:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9637:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9638:                             $offload = 1;
1.1353    raeburn  9639:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9640:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9641:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9642:                                     $offloadoth = 1;
                   9643:                                     $dom_in_use = $env{'user.domain'};
                   9644:                                 }
                   9645:                             }
1.1340    raeburn  9646:                         }
                   9647:                     }
                   9648:                     unless ($offload) {
                   9649:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9650:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9651:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9652:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9653:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9654:                                         $offload = 1;
1.1352    raeburn  9655:                                         $offloadoth = 1;
1.1340    raeburn  9656:                                         $dom_in_use = $env{'user.domain'};
                   9657:                                     }
1.1210    raeburn  9658:                                 }
1.1340    raeburn  9659:                             }
                   9660:                         }
                   9661:                     }
                   9662:                     if ($offload) {
1.1358    raeburn  9663:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9664:                         if (($newserver eq '') && ($offloadoth)) {
                   9665:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9666:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9667:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9668:                             }
                   9669:                         }
1.1340    raeburn  9670:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9671:                             my $numsec = 5;
                   9672:                             my $timeout = $numsec * 1000;
                   9673:                             my ($newurl,$locknum,%locks,$msg);
                   9674:                             if ($env{'request.role.adv'}) {
                   9675:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9676:                             }
                   9677:                             my $disable_submit = 0;
                   9678:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9679:                                 $disable_submit = 1;
                   9680:                             }
                   9681:                             if ($locknum) {
                   9682:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9683:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9684:                                        join(", ",sort(values(%locks)))."\n";
                   9685:                                 if (&show_course()) {
                   9686:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9687:                                 } else {
                   9688:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9689:                                 }
1.1340    raeburn  9690:                             } else {
                   9691:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9692:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9693:                                 }
                   9694:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9695:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9696:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9697:                                     $newurl .= '&role='.$env{'request.role'};
                   9698:                                 }
                   9699:                                 if ($env{'request.symb'}) {
                   9700:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9701:                                     if ($shownsymb =~ m{^/enc/}) {
                   9702:                                         my $reqdmajor = 2;
                   9703:                                         my $reqdminor = 11;
                   9704:                                         my $reqdsubminor = 3;
                   9705:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9706:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9707:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9708:                                         if (($major eq '' && $minor eq '') ||
                   9709:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9710:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9711:                                              ($reqdsubminor > $subminor))))) {
                   9712:                                             undef($shownsymb);
                   9713:                                         }
1.1210    raeburn  9714:                                     }
1.1340    raeburn  9715:                                     if ($shownsymb) {
                   9716:                                         &js_escape(\$shownsymb);
                   9717:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9718:                                     }
1.1340    raeburn  9719:                                 } else {
                   9720:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9721:                                     &js_escape(\$shownurl);
                   9722:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9723:                                 }
1.1340    raeburn  9724:                             }
                   9725:                             &js_escape(\$msg);
                   9726:                             $result.=<<OFFLOAD
1.1210    raeburn  9727: <meta http-equiv="pragma" content="no-cache" />
                   9728: <script type="text/javascript">
1.1215    raeburn  9729: // <![CDATA[
1.1210    raeburn  9730: function LC_Offload_Now() {
                   9731:     var dest = "$newurl";
                   9732:     if (dest != '') {
                   9733:         window.location.href="$newurl";
                   9734:     }
                   9735: }
1.1214    raeburn  9736: \$(document).ready(function () {
                   9737:     window.alert('$msg');
                   9738:     if ($disable_submit) {
1.1210    raeburn  9739:         \$(".LC_hwk_submit").prop("disabled", true);
                   9740:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9741:     }
                   9742:     setTimeout('LC_Offload_Now()', $timeout);
                   9743: });
1.1215    raeburn  9744: // ]]>
1.1210    raeburn  9745: </script>
                   9746: OFFLOAD
                   9747:                         }
                   9748:                     }
                   9749:                 }
                   9750:             }
                   9751:         }
1.313     albertel 9752:     }
1.306     albertel 9753:     if (!defined($title)) {
                   9754: 	$title = 'The LearningOnline Network with CAPA';
                   9755:     }
1.460     albertel 9756:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1432    raeburn  9757:     if ($title =~ /^LON-CAPA\s+/) {
                   9758:         $result .= '<title> '.$title.'</title>';
                   9759:     } else {
                   9760:         $result .= '<title> LON-CAPA '.$title.'</title>';
                   9761:     }
                   9762:     $result .= "\n".'<link rel="stylesheet" type="text/css" href="'.$url.'"';
1.1168    raeburn  9763:     if (!$args->{'frameset'}) {
                   9764:         $result .= ' /';
                   9765:     }
                   9766:     $result .= '>' 
1.1064    raeburn  9767:         .$inhibitprint
1.414     albertel 9768: 	.$head_extra;
1.1242    raeburn  9769:     my $clientmobile;
                   9770:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9771:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9772:     } else {
                   9773:         $clientmobile = $env{'browser.mobile'};
                   9774:     }
                   9775:     if ($clientmobile) {
1.1137    raeburn  9776:         $result .= '
1.1435    raeburn  9777: <meta name="viewport" content="width=device-width, initial-scale=1.0">
1.1137    raeburn  9778: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9779:     }
1.1455    raeburn  9780:     $result .= '<meta name="google" content="notranslate"';
                   9781:     if (!$args->{'frameset'}) {
                   9782:         $result .= ' /';
                   9783:     }
                   9784:     $result .= '>'."\n";
1.962     droeschl 9785:     return $result.'</head>';
1.306     albertel 9786: }
                   9787: 
                   9788: =pod
                   9789: 
1.340     albertel 9790: =item * &font_settings()
                   9791: 
                   9792: Returns neccessary <meta> to set the proper encoding
                   9793: 
1.1160    raeburn  9794: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9795: 
                   9796: =cut
                   9797: 
                   9798: sub font_settings {
1.1160    raeburn  9799:     my ($args) = @_;
1.340     albertel 9800:     my $headerstring='';
1.1160    raeburn  9801:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9802:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9803:         $headerstring.=
                   9804:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9805:         if (!$args->{'frameset'}) {
                   9806: 	    $headerstring.= ' /';
                   9807:         }
                   9808: 	$headerstring .= '>'."\n";
1.340     albertel 9809:     }
                   9810:     return $headerstring;
                   9811: }
                   9812: 
1.341     albertel 9813: =pod
                   9814: 
1.1064    raeburn  9815: =item * &print_suppression()
                   9816: 
                   9817: In course context returns css which causes the body to be blank when media="print",
                   9818: if printout generation is unavailable for the current resource.
                   9819: 
                   9820: This could be because:
                   9821: 
                   9822: (a) printstartdate is in the future
                   9823: 
                   9824: (b) printenddate is in the past
                   9825: 
                   9826: (c) there is an active exam block with "printout"
                   9827: functionality blocked
                   9828: 
                   9829: Users with pav, pfo or evb privileges are exempt.
                   9830: 
                   9831: Inputs: none
                   9832: 
                   9833: =cut
                   9834: 
                   9835: 
                   9836: sub print_suppression {
                   9837:     my $noprint;
                   9838:     if ($env{'request.course.id'}) {
                   9839:         my $scope = $env{'request.course.id'};
                   9840:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9841:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9842:             return;
                   9843:         }
                   9844:         if ($env{'request.course.sec'} ne '') {
                   9845:             $scope .= "/$env{'request.course.sec'}";
                   9846:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9847:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9848:                 return;
1.1064    raeburn  9849:             }
                   9850:         }
                   9851:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9852:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9853:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9854:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9855:         if ($blocked) {
                   9856:             my $checkrole = "cm./$cdom/$cnum";
                   9857:             if ($env{'request.course.sec'} ne '') {
                   9858:                 $checkrole .= "/$env{'request.course.sec'}";
                   9859:             }
                   9860:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9861:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9862:                 $noprint = 1;
                   9863:             }
                   9864:         }
                   9865:         unless ($noprint) {
                   9866:             my $symb = &Apache::lonnet::symbread();
                   9867:             if ($symb ne '') {
                   9868:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9869:                 if (ref($navmap)) {
                   9870:                     my $res = $navmap->getBySymb($symb);
                   9871:                     if (ref($res)) {
                   9872:                         if (!$res->resprintable()) {
                   9873:                             $noprint = 1;
                   9874:                         }
                   9875:                     }
                   9876:                 }
                   9877:             }
                   9878:         }
                   9879:         if ($noprint) {
                   9880:             return <<"ENDSTYLE";
                   9881: <style type="text/css" media="print">
                   9882:     body { display:none }
                   9883: </style>
                   9884: ENDSTYLE
                   9885:         }
                   9886:     }
                   9887:     return;
                   9888: }
                   9889: 
                   9890: =pod
                   9891: 
1.341     albertel 9892: =item * &xml_begin()
                   9893: 
                   9894: Returns the needed doctype and <html>
                   9895: 
                   9896: Inputs: none
                   9897: 
                   9898: =cut
                   9899: 
                   9900: sub xml_begin {
1.1168    raeburn  9901:     my ($is_frameset) = @_;
1.341     albertel 9902:     my $output='';
                   9903: 
                   9904:     if ($env{'browser.mathml'}) {
                   9905: 	$output='<?xml version="1.0"?>'
                   9906:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9907: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9908:             
                   9909: #	    .'<!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">] >'
                   9910: 	    .'<!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">'
                   9911:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9912: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9913:     } elsif ($is_frameset) {
                   9914:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
1.1459  ! raeburn  9915:                 '<html lang="en">'."\n";
1.341     albertel 9916:     } else {
1.1168    raeburn  9917: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9918:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9919:     }
                   9920:     return $output;
                   9921: }
1.340     albertel 9922: 
                   9923: =pod
                   9924: 
1.306     albertel 9925: =item * &start_page()
                   9926: 
                   9927: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9928: 
1.648     raeburn  9929: Inputs:
                   9930: 
                   9931: =over 4
                   9932: 
                   9933: $title - optional title for the page
                   9934: 
                   9935: $head_extra - optional extra HTML to incude inside the <head>
                   9936: 
                   9937: $args - additional optional args supported are:
                   9938: 
                   9939: =over 8
                   9940: 
                   9941:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9942:                                     arg on
1.814     bisitz   9943:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9944:              add_entries    -> additional attributes to add to the  <body>
                   9945:              domain         -> force to color decorate a page for a 
1.317     albertel 9946:                                     specific domain
1.648     raeburn  9947:              function       -> force usage of a specific rolish color
1.317     albertel 9948:                                     scheme
1.648     raeburn  9949:              redirect       -> see &headtag()
                   9950:              bgcolor        -> override the default page bg color
                   9951:              js_ready       -> return a string ready for being used in 
1.317     albertel 9952:                                     a javascript writeln
1.648     raeburn  9953:              html_encode    -> return a string ready for being used in 
1.320     albertel 9954:                                     a html attribute
1.648     raeburn  9955:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9956:                                     $forcereg arg
1.648     raeburn  9957:              frameset       -> if true will start with a <frameset>
1.330     albertel 9958:                                     rather than <body>
1.648     raeburn  9959:              skip_phases    -> hash ref of 
1.338     albertel 9960:                                     head -> skip the <html><head> generation
                   9961:                                     body -> skip all <body> generation
1.648     raeburn  9962:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9963:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9964:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1437    raeburn  9965:              bread_crumbs_style -> breadcrumbs are contained within <div id="LC_breadcrumbs">,
                   9966:                                    and &standard_css() contains CSS for #LC_breadcrumbs, if you want
                   9967:                                    to override those values, or add to them, specify the value to
                   9968:                                    include in the style attribute to include in the div tag by using
                   9969:                                    bread_crumbs_style (e.g., overflow: visible)
1.1272    raeburn  9970:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9971:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9972:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9973:                                specific group
                   9974:              use_absolute   -> for request for external resource or syllabus, this
                   9975:                                will contain https://<hostname> if server uses
                   9976:                                https (as per hosts.tab), but request is for http
                   9977:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9978:              links_disabled -> Links in primary and secondary menus are disabled
                   9979:                                (Can enable them once page has loaded - see lonroles.pm
                   9980:                                for an example).
1.1380    raeburn  9981:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9982: 
1.648     raeburn  9983: =back
1.460     albertel 9984: 
1.648     raeburn  9985: =back
1.562     albertel 9986: 
1.306     albertel 9987: =cut
                   9988: 
                   9989: sub start_page {
1.309     albertel 9990:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9991:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9992: 
1.315     albertel 9993:     $env{'internal.start_page'}++;
1.1359    raeburn  9994:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9995: 
1.338     albertel 9996:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9997:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9998:     }
1.1316    raeburn  9999: 
                   10000:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  10001:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   10002:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   10003:                 $args->{'no_primary_menu'} = 1;
                   10004:             }
                   10005:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   10006:                 $args->{'no_inline_menu'} = 1;
                   10007:             }
                   10008:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   10009:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   10010:             }
                   10011:         } else {
                   10012:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10013:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   10014:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   10015:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   10016:                     $args->{'no_primary_menu'} = 1;
                   10017:                 }
                   10018:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   10019:                     $args->{'no_inline_menu'} = 1;
                   10020:                 }
                   10021:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   10022:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   10023:                 }
                   10024:             }
                   10025:         }
1.1316    raeburn  10026:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   10027:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   10028:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  10029:     } elsif ($env{'request.course.id'}) {
                   10030:         my $expiretime=600;
                   10031:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   10032:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   10033:         }
                   10034:         my ($deeplinkmenu,$menuref);
                   10035:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   10036:         if ($menucoll) {
                   10037:             if (ref($menuref) eq 'HASH') {
                   10038:                 %menu = %{$menuref};
                   10039:             }
                   10040:             if ($menu{'top'} eq 'n') {
                   10041:                 $args->{'no_primary_menu'} = 1;
                   10042:             }
                   10043:             if ($menu{'inline'} eq 'n') {
                   10044:                 unless (&Apache::lonnet::allowed('opa')) {
                   10045:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10046:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10047:                     my $crstype = &course_type();
                   10048:                     my $now = time;
                   10049:                     my $ccrole;
                   10050:                     if ($crstype eq 'Community') {
                   10051:                         $ccrole = 'co';
                   10052:                     } else {
                   10053:                         $ccrole = 'cc';
                   10054:                     }
                   10055:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   10056:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   10057:                         if ((($start) && ($start<0)) ||
                   10058:                             (($end) && ($end<$now))  ||
                   10059:                             (($start) && ($now<$start))) {
                   10060:                             $args->{'no_inline_menu'} = 1;
                   10061:                         }
                   10062:                     } else {
                   10063:                         $args->{'no_inline_menu'} = 1;
                   10064:                     }
                   10065:                 }
                   10066:             }
                   10067:         }
1.1316    raeburn  10068:     }
1.1359    raeburn  10069: 
1.1385    raeburn  10070:     my $showncrumbs;
1.338     albertel 10071:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   10072: 	if ($args->{'frameset'}) {
                   10073: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   10074: 						$args->{'add_entries'});
                   10075: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   10076:         } else {
                   10077:             $result .=
                   10078:                 &bodytag($title, 
                   10079:                          $args->{'function'},       $args->{'add_entries'},
                   10080:                          $args->{'only_body'},      $args->{'domain'},
                   10081:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  10082:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  10083:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   10084:                          \%menu,\$showncrumbs);
1.831     bisitz   10085:         }
1.330     albertel 10086:     }
1.338     albertel 10087: 
1.315     albertel 10088:     if ($args->{'js_ready'}) {
1.713     kaisler  10089: 		$result = &js_ready($result);
1.315     albertel 10090:     }
1.320     albertel 10091:     if ($args->{'html_encode'}) {
1.713     kaisler  10092: 		$result = &html_encode($result);
                   10093:     }
                   10094: 
1.813     bisitz   10095:     # Preparation for new and consistent functionlist at top of screen
                   10096:     # if ($args->{'functionlist'}) {
                   10097:     #            $result .= &build_functionlist();
                   10098:     #}
                   10099: 
1.964     droeschl 10100:     # Don't add anything more if only_body wanted or in const space
                   10101:     return $result if    $args->{'only_body'} 
                   10102:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   10103: 
                   10104:     #Breadcrumbs
1.758     kaisler  10105:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  10106:         unless ($showncrumbs) {
1.758     kaisler  10107: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   10108: 		#if any br links exists, add them to the breadcrumbs
                   10109: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   10110: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   10111: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   10112: 			}
                   10113: 		}
1.1096    raeburn  10114:                 # if @advtools array contains items add then to the breadcrumbs
                   10115:                 if (@advtools > 0) {
                   10116:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   10117:                 }
1.1272    raeburn  10118:                 my $menulink;
                   10119:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   10120:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  10121:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  10122:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   10123:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   10124:                      (!$env{'request.role.adv'}))) {
                   10125:                     $menulink = 0;
                   10126:                 } else {
                   10127:                     undef($menulink);
                   10128:                 }
1.1385    raeburn  10129:                 my $linkprotout;
                   10130:                 if ($env{'request.deeplink.login'}) {
                   10131:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   10132:                     if ($linkprotout) {
                   10133:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   10134:                     }
                   10135:                 }
1.758     kaisler  10136: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   10137: 		if(exists($args->{'bread_crumbs_component'})){
1.1437    raeburn  10138: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},
                   10139:                                                                        '',$menulink,'',
                   10140:                                                                        $args->{'bread_crumbs_style'});
1.1237    raeburn  10141:                 } else {
1.1437    raeburn  10142: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink,'',
                   10143:                                                                        $args->{'bread_crumbs_style'});
1.758     kaisler  10144: 		}
1.1385    raeburn  10145:         }
1.320     albertel 10146:     }
1.315     albertel 10147:     return $result;
1.306     albertel 10148: }
                   10149: 
                   10150: sub end_page {
1.315     albertel 10151:     my ($args) = @_;
                   10152:     $env{'internal.end_page'}++;
1.330     albertel 10153:     my $result;
1.335     albertel 10154:     if ($args->{'discussion'}) {
                   10155: 	my ($target,$parser);
                   10156: 	if (ref($args->{'discussion'})) {
                   10157: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   10158: 				$args->{'discussion'}{'parser'});
                   10159: 	}
                   10160: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   10161:     }
1.330     albertel 10162:     if ($args->{'frameset'}) {
                   10163: 	$result .= '</frameset>';
                   10164:     } else {
1.635     raeburn  10165: 	$result .= &endbodytag($args);
1.330     albertel 10166:     }
1.1080    raeburn  10167:     unless ($args->{'notbody'}) {
                   10168:         $result .= "\n</html>";
                   10169:     }
1.330     albertel 10170: 
1.315     albertel 10171:     if ($args->{'js_ready'}) {
1.317     albertel 10172: 	$result = &js_ready($result);
1.315     albertel 10173:     }
1.335     albertel 10174: 
1.320     albertel 10175:     if ($args->{'html_encode'}) {
                   10176: 	$result = &html_encode($result);
                   10177:     }
1.335     albertel 10178: 
1.315     albertel 10179:     return $result;
                   10180: }
                   10181: 
1.1359    raeburn  10182: sub menucoll_in_effect {
                   10183:     my ($menucoll,$deeplinkmenu,%menu);
                   10184:     if ($env{'request.course.id'}) {
                   10185:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  10186:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  10187:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  10188:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10189:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10190:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   10191:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   10192:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10193:                     if (ref($navmap)) {
                   10194:                         $deeplink = $navmap->get_mapparam(undef,
                   10195:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   10196:                                                           '0.deeplink');
1.1370    raeburn  10197:                     } else {
                   10198:                         $check_login_symb = 1;
1.1362    raeburn  10199:                     }
                   10200:                 } else {
1.1370    raeburn  10201:                     my $symb = &Apache::lonnet::symbread();
                   10202:                     if ($symb) {
                   10203:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   10204:                     } else {
                   10205:                         $check_login_symb = 1;
                   10206:                     }
1.1362    raeburn  10207:                 }
                   10208:             } else {
1.1370    raeburn  10209:                 $check_login_symb = 1;
                   10210:             }
                   10211:             if ($check_login_symb) {
1.1362    raeburn  10212:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   10213:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   10214:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   10215:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10216:                     if (ref($navmap)) {
                   10217:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   10218:                     }
                   10219:                 } else {
                   10220:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   10221:                 }
                   10222:             }
1.1359    raeburn  10223:             if ($deeplink ne '') {
1.1378    raeburn  10224:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  10225:                 if ($display =~ /^\d+$/) {
                   10226:                     $deeplinkmenu = 1;
                   10227:                     $menucoll = $display;
                   10228:                 }
                   10229:             }
                   10230:         }
                   10231:         if ($menucoll) {
                   10232:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   10233:         }
                   10234:     }
                   10235:     return ($menucoll,$deeplinkmenu,\%menu);
                   10236: }
                   10237: 
1.1362    raeburn  10238: sub deeplink_login_symb {
                   10239:     my ($cnum,$cdom) = @_;
                   10240:     my $login_symb;
                   10241:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  10242:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   10243:     }
                   10244:     return $login_symb;
                   10245: }
                   10246: 
                   10247: sub symb_from_tinyurl {
                   10248:     my ($url,$cnum,$cdom) = @_;
                   10249:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   10250:         my $key = $1;
                   10251:         my ($tinyurl,$login);
                   10252:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   10253:         if (defined($cached)) {
                   10254:             $tinyurl = $result;
                   10255:         } else {
                   10256:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   10257:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   10258:             if ($currtiny{$key} ne '') {
                   10259:                 $tinyurl = $currtiny{$key};
                   10260:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  10261:             }
1.1364    raeburn  10262:         }
                   10263:         if ($tinyurl ne '') {
                   10264:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   10265:             if (wantarray) {
                   10266:                 return ($cnumreq,$symb);
                   10267:             } elsif ($cnumreq eq $cnum) {
                   10268:                 return $symb;
1.1362    raeburn  10269:             }
                   10270:         }
                   10271:     }
1.1364    raeburn  10272:     if (wantarray) {
                   10273:         return ();
                   10274:     } else {
                   10275:         return;
                   10276:     }
1.1362    raeburn  10277: }
                   10278: 
1.1405    raeburn  10279: sub usable_exttools {
                   10280:     my %tooltypes;
                   10281:     if ($env{'request.course.id'}) {
                   10282:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   10283:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   10284:                %tooltypes = (
                   10285:                              crs => 1,
                   10286:                              dom => 1,
                   10287:                             );
                   10288:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   10289:                $tooltypes{'crs'} = 1;
                   10290:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   10291:                $tooltypes{'dom'} = 1;
                   10292:            }
                   10293:         } else {
                   10294:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10295:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10296:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   10297:             if ($crstype eq '') {
                   10298:                 $crstype = 'course';
                   10299:             }
                   10300:             if ($crstype eq 'course') {
                   10301:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   10302:                     $crstype = 'official';
                   10303:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   10304:                     $crstype = 'textbook';
                   10305:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   10306:                     $crstype = 'lti';
                   10307:                 } else {
                   10308:                     $crstype = 'unofficial';
                   10309:                 }
                   10310:             }
                   10311:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   10312:             if ($domdefaults{$crstype.'domexttool'}) {
                   10313:                 $tooltypes{'dom'} = 1;
                   10314:             }
                   10315:             if ($domdefaults{$crstype.'exttool'}) {
                   10316:                 $tooltypes{'crs'} = 1;
                   10317:             }
                   10318:         }
                   10319:     }
                   10320:     return %tooltypes;
                   10321: }
                   10322: 
1.1034    www      10323: sub wishlist_window {
                   10324:     return(<<'ENDWISHLIST');
1.1046    raeburn  10325: <script type="text/javascript">
1.1034    www      10326: // <![CDATA[
                   10327: // <!-- BEGIN LON-CAPA Internal
                   10328: function set_wishlistlink(title, path) {
                   10329:     if (!title) {
                   10330:         title = document.title;
                   10331:         title = title.replace(/^LON-CAPA /,'');
                   10332:     }
1.1175    raeburn  10333:     title = encodeURIComponent(title);
1.1203    raeburn  10334:     title = title.replace("'","\\\'");
1.1034    www      10335:     if (!path) {
                   10336:         path = location.pathname;
                   10337:     }
1.1175    raeburn  10338:     path = encodeURIComponent(path);
1.1203    raeburn  10339:     path = path.replace("'","\\\'");
1.1034    www      10340:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   10341:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   10342: }
                   10343: // END LON-CAPA Internal -->
                   10344: // ]]>
                   10345: </script>
                   10346: ENDWISHLIST
                   10347: }
                   10348: 
1.1030    www      10349: sub modal_window {
                   10350:     return(<<'ENDMODAL');
1.1046    raeburn  10351: <script type="text/javascript">
1.1030    www      10352: // <![CDATA[
                   10353: // <!-- BEGIN LON-CAPA Internal
                   10354: var modalWindow = {
                   10355: 	parent:"body",
                   10356: 	windowId:null,
                   10357: 	content:null,
                   10358: 	width:null,
                   10359: 	height:null,
                   10360: 	close:function()
                   10361: 	{
                   10362: 	        $(".LCmodal-window").remove();
                   10363: 	        $(".LCmodal-overlay").remove();
                   10364: 	},
                   10365: 	open:function()
                   10366: 	{
                   10367: 		var modal = "";
                   10368: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   10369: 		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;\">";
                   10370: 		modal += this.content;
                   10371: 		modal += "</div>";	
                   10372: 
                   10373: 		$(this.parent).append(modal);
                   10374: 
                   10375: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   10376: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   10377: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   10378: 	}
                   10379: };
1.1140    raeburn  10380: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      10381: 	{
1.1266    raeburn  10382:                 source = source.replace(/'/g,"&#39;");
1.1030    www      10383: 		modalWindow.windowId = "myModal";
                   10384: 		modalWindow.width = width;
                   10385: 		modalWindow.height = height;
1.1196    raeburn  10386: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      10387: 		modalWindow.open();
1.1208    raeburn  10388: 	};
1.1030    www      10389: // END LON-CAPA Internal -->
                   10390: // ]]>
                   10391: </script>
                   10392: ENDMODAL
                   10393: }
                   10394: 
                   10395: sub modal_link {
1.1140    raeburn  10396:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      10397:     unless ($width) { $width=480; }
                   10398:     unless ($height) { $height=400; }
1.1031    www      10399:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  10400:     unless ($transparency) { $transparency='true'; }
                   10401: 
1.1074    raeburn  10402:     my $target_attr;
                   10403:     if (defined($target)) {
                   10404:         $target_attr = 'target="'.$target.'"';
                   10405:     }
                   10406:     return <<"ENDLINK";
1.1336    raeburn  10407: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  10408: ENDLINK
1.1030    www      10409: }
                   10410: 
1.1032    www      10411: sub modal_adhoc_script {
1.1365    raeburn  10412:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   10413:     my $mathjax;
                   10414:     if ($possmathjax) {
                   10415:         $mathjax = <<'ENDJAX';
                   10416:                if (typeof MathJax == 'object') {
                   10417:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   10418:                }
                   10419: ENDJAX
                   10420:     }
1.1032    www      10421:     return (<<ENDADHOC);
1.1046    raeburn  10422: <script type="text/javascript">
1.1032    www      10423: // <![CDATA[
                   10424:         var $funcname = function()
                   10425:         {
                   10426:                 modalWindow.windowId = "myModal";
                   10427:                 modalWindow.width = $width;
                   10428:                 modalWindow.height = $height;
                   10429:                 modalWindow.content = '$content';
                   10430:                 modalWindow.open();
1.1365    raeburn  10431:                 $mathjax
1.1032    www      10432:         };  
                   10433: // ]]>
                   10434: </script>
                   10435: ENDADHOC
                   10436: }
                   10437: 
1.1041    www      10438: sub modal_adhoc_inner {
1.1365    raeburn  10439:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      10440:     my $innerwidth=$width-20;
                   10441:     $content=&js_ready(
1.1140    raeburn  10442:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   10443:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   10444:                  $content.
1.1041    www      10445:                  &end_scrollbox().
1.1140    raeburn  10446:                  &end_page()
1.1041    www      10447:              );
1.1365    raeburn  10448:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      10449: }
                   10450: 
                   10451: sub modal_adhoc_window {
1.1365    raeburn  10452:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   10453:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      10454:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   10455: }
                   10456: 
                   10457: sub modal_adhoc_launch {
                   10458:     my ($funcname,$width,$height,$content)=@_;
                   10459:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   10460: <script type="text/javascript">
                   10461: // <![CDATA[
                   10462: $funcname();
                   10463: // ]]>
                   10464: </script>
                   10465: ENDLAUNCH
                   10466: }
                   10467: 
                   10468: sub modal_adhoc_close {
                   10469:     return (<<ENDCLOSE);
                   10470: <script type="text/javascript">
                   10471: // <![CDATA[
                   10472: modalWindow.close();
                   10473: // ]]>
                   10474: </script>
                   10475: ENDCLOSE
                   10476: }
                   10477: 
1.1038    www      10478: sub togglebox_script {
                   10479:    return(<<ENDTOGGLE);
                   10480: <script type="text/javascript"> 
                   10481: // <![CDATA[
                   10482: function LCtoggleDisplay(id,hidetext,showtext) {
                   10483:    link = document.getElementById(id + "link").childNodes[0];
                   10484:    with (document.getElementById(id).style) {
                   10485:       if (display == "none" ) {
                   10486:           display = "inline";
                   10487:           link.nodeValue = hidetext;
                   10488:         } else {
                   10489:           display = "none";
                   10490:           link.nodeValue = showtext;
                   10491:        }
                   10492:    }
                   10493: }
                   10494: // ]]>
                   10495: </script>
                   10496: ENDTOGGLE
                   10497: }
                   10498: 
1.1039    www      10499: sub start_togglebox {
                   10500:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   10501:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   10502:     unless ($showtext) { $showtext=&mt('show'); }
                   10503:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   10504:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   10505:     return &start_data_table().
                   10506:            &start_data_table_header_row().
                   10507:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   10508:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   10509:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   10510:            &end_data_table_header_row().
                   10511:            '<tr id="'.$id.'" style="display:none""><td>';
                   10512: }
                   10513: 
                   10514: sub end_togglebox {
                   10515:     return '</td></tr>'.&end_data_table();
                   10516: }
                   10517: 
1.1041    www      10518: sub LCprogressbar_script {
1.1302    raeburn  10519:    my ($id,$number_to_do)=@_;
                   10520:    if ($number_to_do) {
                   10521:        return(<<ENDPROGRESS);
1.1041    www      10522: <script type="text/javascript">
                   10523: // <![CDATA[
1.1045    www      10524: \$('#progressbar$id').progressbar({
1.1041    www      10525:   value: 0,
                   10526:   change: function(event, ui) {
                   10527:     var newVal = \$(this).progressbar('option', 'value');
                   10528:     \$('.pblabel', this).text(LCprogressTxt);
                   10529:   }
                   10530: });
                   10531: // ]]>
                   10532: </script>
                   10533: ENDPROGRESS
1.1302    raeburn  10534:    } else {
                   10535:        return(<<ENDPROGRESS);
                   10536: <script type="text/javascript">
                   10537: // <![CDATA[
                   10538: \$('#progressbar$id').progressbar({
                   10539:   value: false,
                   10540:   create: function(event, ui) {
                   10541:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   10542:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   10543:   }
                   10544: });
                   10545: // ]]>
                   10546: </script>
                   10547: ENDPROGRESS
                   10548:    }
1.1041    www      10549: }
                   10550: 
                   10551: sub LCprogressbarUpdate_script {
                   10552:    return(<<ENDPROGRESSUPDATE);
                   10553: <style type="text/css">
                   10554: .ui-progressbar { position:relative; }
1.1302    raeburn  10555: .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      10556: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   10557: </style>
                   10558: <script type="text/javascript">
                   10559: // <![CDATA[
1.1045    www      10560: var LCprogressTxt='---';
                   10561: 
1.1302    raeburn  10562: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      10563:    LCprogressTxt=progresstext;
1.1302    raeburn  10564:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   10565:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   10566:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  10567:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   10568:    } else {
                   10569:        \$('#progressbar'+id).progressbar('value',percent);
                   10570:    }
1.1041    www      10571: }
                   10572: // ]]>
                   10573: </script>
                   10574: ENDPROGRESSUPDATE
                   10575: }
                   10576: 
1.1042    www      10577: my $LClastpercent;
1.1045    www      10578: my $LCidcnt;
                   10579: my $LCcurrentid;
1.1042    www      10580: 
1.1041    www      10581: sub LCprogressbar {
1.1302    raeburn  10582:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      10583:     $LClastpercent=0;
1.1045    www      10584:     $LCidcnt++;
                   10585:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  10586:     my ($starting,$content);
                   10587:     if ($number_to_do) {
                   10588:         $starting=&mt('Starting');
                   10589:         $content=(<<ENDPROGBAR);
                   10590: $preamble
1.1045    www      10591:   <div id="progressbar$LCcurrentid">
1.1041    www      10592:     <span class="pblabel">$starting</span>
                   10593:   </div>
                   10594: ENDPROGBAR
1.1302    raeburn  10595:     } else {
                   10596:         $starting=&mt('Loading...');
                   10597:         $LClastpercent='false';
                   10598:         $content=(<<ENDPROGBAR);
                   10599: $preamble
                   10600:   <div id="progressbar$LCcurrentid">
                   10601:       <div class="progress-label">$starting</div>
                   10602:   </div>
                   10603: ENDPROGBAR
                   10604:     }
                   10605:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      10606: }
                   10607: 
                   10608: sub LCprogressbarUpdate {
1.1302    raeburn  10609:     my ($r,$val,$text,$number_to_do)=@_;
                   10610:     if ($number_to_do) {
                   10611:         unless ($val) { 
                   10612:             if ($LClastpercent) {
                   10613:                 $val=$LClastpercent;
                   10614:             } else {
                   10615:                 $val=0;
                   10616:             }
                   10617:         }
                   10618:         if ($val<0) { $val=0; }
                   10619:         if ($val>100) { $val=0; }
                   10620:         $LClastpercent=$val;
                   10621:         unless ($text) { $text=$val.'%'; }
                   10622:     } else {
                   10623:         $val = 'false';
1.1042    www      10624:     }
1.1041    www      10625:     $text=&js_ready($text);
1.1044    www      10626:     &r_print($r,<<ENDUPDATE);
1.1041    www      10627: <script type="text/javascript">
                   10628: // <![CDATA[
1.1302    raeburn  10629: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10630: // ]]>
                   10631: </script>
                   10632: ENDUPDATE
1.1035    www      10633: }
                   10634: 
1.1042    www      10635: sub LCprogressbarClose {
                   10636:     my ($r)=@_;
                   10637:     $LClastpercent=0;
1.1044    www      10638:     &r_print($r,<<ENDCLOSE);
1.1042    www      10639: <script type="text/javascript">
                   10640: // <![CDATA[
1.1045    www      10641: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10642: // ]]>
                   10643: </script>
                   10644: ENDCLOSE
1.1044    www      10645: }
                   10646: 
                   10647: sub r_print {
                   10648:     my ($r,$to_print)=@_;
                   10649:     if ($r) {
                   10650:       $r->print($to_print);
                   10651:       $r->rflush();
                   10652:     } else {
                   10653:       print($to_print);
                   10654:     }
1.1042    www      10655: }
                   10656: 
1.320     albertel 10657: sub html_encode {
                   10658:     my ($result) = @_;
                   10659: 
1.322     albertel 10660:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10661:     
                   10662:     return $result;
                   10663: }
1.1044    www      10664: 
1.317     albertel 10665: sub js_ready {
                   10666:     my ($result) = @_;
                   10667: 
1.323     albertel 10668:     $result =~ s/[\n\r]/ /xmsg;
                   10669:     $result =~ s/\\/\\\\/xmsg;
                   10670:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10671:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10672:     
                   10673:     return $result;
                   10674: }
                   10675: 
1.315     albertel 10676: sub validate_page {
                   10677:     if (  exists($env{'internal.start_page'})
1.316     albertel 10678: 	  &&     $env{'internal.start_page'} > 1) {
                   10679: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10680: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10681: 				 $ENV{'request.filename'});
1.315     albertel 10682:     }
                   10683:     if (  exists($env{'internal.end_page'})
1.316     albertel 10684: 	  &&     $env{'internal.end_page'} > 1) {
                   10685: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10686: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10687: 				 $env{'request.filename'});
1.315     albertel 10688:     }
                   10689:     if (     exists($env{'internal.start_page'})
                   10690: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10691: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10692: 				 $env{'request.filename'});
1.315     albertel 10693:     }
                   10694:     if (   ! exists($env{'internal.start_page'})
                   10695: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10696: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10697: 				 $env{'request.filename'});
1.315     albertel 10698:     }
1.306     albertel 10699: }
1.315     albertel 10700: 
1.996     www      10701: 
                   10702: sub start_scrollbox {
1.1140    raeburn  10703:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10704:     unless ($outerwidth) { $outerwidth='520px'; }
                   10705:     unless ($width) { $width='500px'; }
                   10706:     unless ($height) { $height='200px'; }
1.1075    raeburn  10707:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10708:     if ($id ne '') {
1.1140    raeburn  10709:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10710:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10711:     }
1.1075    raeburn  10712:     if ($bgcolor ne '') {
                   10713:         $tdcol = "background-color: $bgcolor;";
                   10714:     }
1.1137    raeburn  10715:     my $nicescroll_js;
                   10716:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10717:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10718:     }
                   10719:     return <<"END";
                   10720: $nicescroll_js
                   10721: 
                   10722: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10723: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10724: END
                   10725: }
                   10726: 
                   10727: sub end_scrollbox {
                   10728:     return '</div></td></tr></table>';
                   10729: }
                   10730: 
                   10731: sub nicescroll_javascript {
                   10732:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10733:     my %options;
                   10734:     if (ref($cursor) eq 'HASH') {
                   10735:         %options = %{$cursor};
                   10736:     }
                   10737:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10738:         $options{'railalign'} = 'left';
                   10739:     }
                   10740:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10741:         my $function  = &get_users_function();
                   10742:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10743:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10744:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10745:         }
1.1140    raeburn  10746:     }
                   10747:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10748:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10749:             $options{'cursoropacity'}='1.0';
                   10750:         }
1.1140    raeburn  10751:     } else {
                   10752:         $options{'cursoropacity'}='1.0';
                   10753:     }
                   10754:     if ($options{'cursorfixedheight'} eq 'none') {
                   10755:         delete($options{'cursorfixedheight'});
                   10756:     } else {
                   10757:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10758:     }
                   10759:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10760:         delete($options{'railoffset'});
                   10761:     }
                   10762:     my @niceoptions;
                   10763:     while (my($key,$value) = each(%options)) {
                   10764:         if ($value =~ /^\{.+\}$/) {
                   10765:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10766:         } else {
1.1140    raeburn  10767:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10768:         }
1.1140    raeburn  10769:     }
                   10770:     my $nicescroll_js = '
1.1137    raeburn  10771: $(document).ready(
1.1140    raeburn  10772:       function() {
                   10773:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10774:       }
1.1137    raeburn  10775: );
                   10776: ';
1.1140    raeburn  10777:     if ($framecheck) {
                   10778:         $nicescroll_js .= '
                   10779: function expand_div(caller) {
                   10780:     if (top === self) {
                   10781:         document.getElementById("'.$id.'").style.width = "auto";
                   10782:         document.getElementById("'.$id.'").style.height = "auto";
                   10783:     } else {
                   10784:         try {
                   10785:             if (parent.frames) {
                   10786:                 if (parent.frames.length > 1) {
                   10787:                     var framesrc = parent.frames[1].location.href;
                   10788:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10789:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10790:                         document.getElementById("'.$id.'").style.width = "auto";
                   10791:                         document.getElementById("'.$id.'").style.height = "auto";
                   10792:                     }
                   10793:                 }
                   10794:             }
                   10795:         } catch (e) {
                   10796:             return;
                   10797:         }
1.1137    raeburn  10798:     }
1.1140    raeburn  10799:     return;
1.996     www      10800: }
1.1140    raeburn  10801: ';
                   10802:     }
                   10803:     if ($needjsready) {
                   10804:         $nicescroll_js = '
                   10805: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10806:     } else {
                   10807:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10808:     }
                   10809:     return $nicescroll_js;
1.996     www      10810: }
                   10811: 
1.318     albertel 10812: sub simple_error_page {
1.1150    bisitz   10813:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10814:     my %displayargs;
1.1151    raeburn  10815:     if (ref($args) eq 'HASH') {
                   10816:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10817:         if ($args->{'only_body'}) {
                   10818:             $displayargs{'only_body'} = 1;
                   10819:         }
                   10820:         if ($args->{'no_nav_bar'}) {
                   10821:             $displayargs{'no_nav_bar'} = 1;
                   10822:         }
1.1151    raeburn  10823:     } else {
                   10824:         $msg = &mt($msg);
                   10825:     }
1.1150    bisitz   10826: 
1.318     albertel 10827:     my $page =
1.1459  ! raeburn  10828: 	&Apache::loncommon::start_page($title,'',\%displayargs)."\n".
        !          10829:         '<div class="LC_landmark" style="clear:both"  role="main">'.
1.1150    bisitz   10830: 	'<p class="LC_error">'.$msg.'</p>'.
1.1459  ! raeburn  10831:         '</div>'.
1.318     albertel 10832: 	&Apache::loncommon::end_page();
                   10833:     if (ref($r)) {
                   10834: 	$r->print($page);
1.327     albertel 10835: 	return;
1.318     albertel 10836:     }
                   10837:     return $page;
                   10838: }
1.347     albertel 10839: 
                   10840: {
1.610     albertel 10841:     my @row_count;
1.961     onken    10842: 
                   10843:     sub start_data_table_count {
                   10844:         unshift(@row_count, 0);
                   10845:         return;
                   10846:     }
                   10847: 
                   10848:     sub end_data_table_count {
                   10849:         shift(@row_count);
                   10850:         return;
                   10851:     }
                   10852: 
1.347     albertel 10853:     sub start_data_table {
1.1018    raeburn  10854: 	my ($add_class,$id) = @_;
1.422     albertel 10855: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10856:         my $table_id;
                   10857:         if (defined($id)) {
                   10858:             $table_id = ' id="'.$id.'"';
                   10859:         }
1.961     onken    10860: 	&start_data_table_count();
1.1018    raeburn  10861: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10862:     }
                   10863: 
                   10864:     sub end_data_table {
1.961     onken    10865: 	&end_data_table_count();
1.389     albertel 10866: 	return '</table>'."\n";;
1.347     albertel 10867:     }
                   10868: 
                   10869:     sub start_data_table_row {
1.974     wenzelju 10870: 	my ($add_class, $id) = @_;
1.610     albertel 10871: 	$row_count[0]++;
                   10872: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10873: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10874:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10875:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10876:     }
1.471     banghart 10877:     
                   10878:     sub continue_data_table_row {
1.974     wenzelju 10879: 	my ($add_class, $id) = @_;
1.610     albertel 10880: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10881: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10882:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10883:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10884:     }
1.347     albertel 10885: 
                   10886:     sub end_data_table_row {
1.389     albertel 10887: 	return '</tr>'."\n";;
1.347     albertel 10888:     }
1.367     www      10889: 
1.421     albertel 10890:     sub start_data_table_empty_row {
1.707     bisitz   10891: #	$row_count[0]++;
1.421     albertel 10892: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10893:     }
                   10894: 
                   10895:     sub end_data_table_empty_row {
                   10896: 	return '</tr>'."\n";;
                   10897:     }
                   10898: 
1.367     www      10899:     sub start_data_table_header_row {
1.389     albertel 10900: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10901:     }
                   10902: 
                   10903:     sub end_data_table_header_row {
1.389     albertel 10904: 	return '</tr>'."\n";;
1.367     www      10905:     }
1.890     droeschl 10906: 
                   10907:     sub data_table_caption {
                   10908:         my $caption = shift;
                   10909:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10910:     }
1.347     albertel 10911: }
                   10912: 
1.548     albertel 10913: =pod
                   10914: 
                   10915: =item * &inhibit_menu_check($arg)
                   10916: 
                   10917: Checks for a inhibitmenu state and generates output to preserve it
                   10918: 
                   10919: Inputs:         $arg - can be any of
                   10920:                      - undef - in which case the return value is a string 
                   10921:                                to add  into arguments list of a uri
                   10922:                      - 'input' - in which case the return value is a HTML
                   10923:                                  <form> <input> field of type hidden to
                   10924:                                  preserve the value
                   10925:                      - a url - in which case the return value is the url with
                   10926:                                the neccesary cgi args added to preserve the
                   10927:                                inhibitmenu state
                   10928:                      - a ref to a url - no return value, but the string is
                   10929:                                         updated to include the neccessary cgi
                   10930:                                         args to preserve the inhibitmenu state
                   10931: 
                   10932: =cut
                   10933: 
                   10934: sub inhibit_menu_check {
                   10935:     my ($arg) = @_;
                   10936:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10937:     if ($arg eq 'input') {
                   10938: 	if ($env{'form.inhibitmenu'}) {
                   10939: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10940: 	} else {
                   10941: 	    return
                   10942: 	}
                   10943:     }
                   10944:     if ($env{'form.inhibitmenu'}) {
                   10945: 	if (ref($arg)) {
                   10946: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10947: 	} elsif ($arg eq '') {
                   10948: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10949: 	} else {
                   10950: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10951: 	}
                   10952:     }
                   10953:     if (!ref($arg)) {
                   10954: 	return $arg;
                   10955:     }
                   10956: }
                   10957: 
1.251     albertel 10958: ###############################################
1.182     matthew  10959: 
                   10960: =pod
                   10961: 
1.549     albertel 10962: =back
                   10963: 
                   10964: =head1 User Information Routines
                   10965: 
                   10966: =over 4
                   10967: 
1.405     albertel 10968: =item * &get_users_function()
1.182     matthew  10969: 
                   10970: Used by &bodytag to determine the current users primary role.
                   10971: Returns either 'student','coordinator','admin', or 'author'.
                   10972: 
                   10973: =cut
                   10974: 
                   10975: ###############################################
                   10976: sub get_users_function {
1.815     tempelho 10977:     my $function = 'norole';
1.818     tempelho 10978:     if ($env{'request.role'}=~/^(st)/) {
                   10979:         $function='student';
                   10980:     }
1.907     raeburn  10981:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10982:         $function='coordinator';
                   10983:     }
1.258     albertel 10984:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10985:         $function='admin';
                   10986:     }
1.826     bisitz   10987:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10988:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10989:         $function='author';
                   10990:     }
                   10991:     return $function;
1.54      www      10992: }
1.99      www      10993: 
                   10994: ###############################################
                   10995: 
1.233     raeburn  10996: =pod
                   10997: 
1.821     raeburn  10998: =item * &show_course()
                   10999: 
                   11000: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   11001: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   11002: 
                   11003: Inputs:
                   11004: None
                   11005: 
                   11006: Outputs:
                   11007: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   11008: 
                   11009: =cut
                   11010: 
                   11011: ###############################################
                   11012: sub show_course {
1.1408    raeburn  11013:     my ($udom,$uname) = @_;
                   11014:     if (($udom ne '') && ($uname ne '')) {
                   11015:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
1.1410    raeburn  11016:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
1.1408    raeburn  11017:                 return 0;
                   11018:             } else {
                   11019:                 return 1;
                   11020:             }
                   11021:         }
                   11022:     }
1.821     raeburn  11023:     my $course = !$env{'user.adv'};
                   11024:     if (!$env{'user.adv'}) {
                   11025:         foreach my $env (keys(%env)) {
                   11026:             next if ($env !~ m/^user\.priv\./);
                   11027:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   11028:                 $course = 0;
                   11029:                 last;
                   11030:             }
                   11031:         }
                   11032:     }
                   11033:     return $course;
                   11034: }
                   11035: 
                   11036: ###############################################
                   11037: 
                   11038: =pod
                   11039: 
1.542     raeburn  11040: =item * &check_user_status()
1.274     raeburn  11041: 
                   11042: Determines current status of supplied role for a
                   11043: specific user. Roles can be active, previous or future.
                   11044: 
                   11045: Inputs: 
                   11046: user's domain, user's username, course's domain,
1.375     raeburn  11047: course's number, optional section ID.
1.274     raeburn  11048: 
                   11049: Outputs:
                   11050: role status: active, previous or future. 
                   11051: 
                   11052: =cut
                   11053: 
                   11054: sub check_user_status {
1.412     raeburn  11055:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  11056:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  11057:     my @uroles = keys(%userinfo);
1.274     raeburn  11058:     my $srchstr;
                   11059:     my $active_chk = 'none';
1.412     raeburn  11060:     my $now = time;
1.274     raeburn  11061:     if (@uroles > 0) {
1.908     raeburn  11062:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  11063:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   11064:         } else {
1.412     raeburn  11065:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   11066:         }
                   11067:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  11068:             my $role_end = 0;
                   11069:             my $role_start = 0;
                   11070:             $active_chk = 'active';
1.412     raeburn  11071:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   11072:                 $role_end = $1;
                   11073:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   11074:                     $role_start = $1;
1.274     raeburn  11075:                 }
                   11076:             }
                   11077:             if ($role_start > 0) {
1.412     raeburn  11078:                 if ($now < $role_start) {
1.274     raeburn  11079:                     $active_chk = 'future';
                   11080:                 }
                   11081:             }
                   11082:             if ($role_end > 0) {
1.412     raeburn  11083:                 if ($now > $role_end) {
1.274     raeburn  11084:                     $active_chk = 'previous';
                   11085:                 }
                   11086:             }
                   11087:         }
                   11088:     }
                   11089:     return $active_chk;
                   11090: }
                   11091: 
                   11092: ###############################################
                   11093: 
                   11094: =pod
                   11095: 
1.405     albertel 11096: =item * &get_sections()
1.233     raeburn  11097: 
                   11098: Determines all the sections for a course including
                   11099: sections with students and sections containing other roles.
1.419     raeburn  11100: Incoming parameters: 
                   11101: 
                   11102: 1. domain
                   11103: 2. course number 
                   11104: 3. reference to array containing roles for which sections should 
                   11105: be gathered (optional).
                   11106: 4. reference to array containing status types for which sections 
                   11107: should be gathered (optional).
                   11108: 
                   11109: If the third argument is undefined, sections are gathered for any role. 
                   11110: If the fourth argument is undefined, sections are gathered for any status.
                   11111: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  11112:  
1.374     raeburn  11113: Returns section hash (keys are section IDs, values are
                   11114: number of users in each section), subject to the
1.419     raeburn  11115: optional roles filter, optional status filter 
1.233     raeburn  11116: 
                   11117: =cut
                   11118: 
                   11119: ###############################################
                   11120: sub get_sections {
1.419     raeburn  11121:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 11122:     if (!defined($cdom) || !defined($cnum)) {
                   11123:         my $cid =  $env{'request.course.id'};
                   11124: 
                   11125: 	return if (!defined($cid));
                   11126: 
                   11127:         $cdom = $env{'course.'.$cid.'.domain'};
                   11128:         $cnum = $env{'course.'.$cid.'.num'};
                   11129:     }
                   11130: 
                   11131:     my %sectioncount;
1.419     raeburn  11132:     my $now = time;
1.240     albertel 11133: 
1.1118    raeburn  11134:     my $check_students = 1;
                   11135:     my $only_students = 0;
                   11136:     if (ref($possible_roles) eq 'ARRAY') {
                   11137:         if (grep(/^st$/,@{$possible_roles})) {
                   11138:             if (@{$possible_roles} == 1) {
                   11139:                 $only_students = 1;
                   11140:             }
                   11141:         } else {
                   11142:             $check_students = 0;
                   11143:         }
                   11144:     }
                   11145: 
                   11146:     if ($check_students) { 
1.276     albertel 11147: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 11148: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   11149: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  11150:         my $start_index = &Apache::loncoursedata::CL_START();
                   11151:         my $end_index = &Apache::loncoursedata::CL_END();
                   11152:         my $status;
1.366     albertel 11153: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  11154: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   11155: 				                     $data->[$status_index],
                   11156:                                                      $data->[$start_index],
                   11157:                                                      $data->[$end_index]);
                   11158:             if ($stu_status eq 'Active') {
                   11159:                 $status = 'active';
                   11160:             } elsif ($end < $now) {
                   11161:                 $status = 'previous';
                   11162:             } elsif ($start > $now) {
                   11163:                 $status = 'future';
                   11164:             } 
                   11165: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   11166:                 if ((!defined($possible_status)) || (($status ne '') && 
                   11167:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   11168: 		    $sectioncount{$section}++;
                   11169:                 }
1.240     albertel 11170: 	    }
                   11171: 	}
                   11172:     }
1.1118    raeburn  11173:     if ($only_students) {
                   11174:         return %sectioncount;
                   11175:     }
1.240     albertel 11176:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11177:     foreach my $user (sort(keys(%courseroles))) {
                   11178: 	if ($user !~ /^(\w{2})/) { next; }
                   11179: 	my ($role) = ($user =~ /^(\w{2})/);
                   11180: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  11181: 	my ($section,$status);
1.240     albertel 11182: 	if ($role eq 'cr' &&
                   11183: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   11184: 	    $section=$1;
                   11185: 	}
                   11186: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   11187: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  11188:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   11189:         if ($end == -1 && $start == -1) {
                   11190:             next; #deleted role
                   11191:         }
                   11192:         if (!defined($possible_status)) { 
                   11193:             $sectioncount{$section}++;
                   11194:         } else {
                   11195:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   11196:                 $status = 'active';
                   11197:             } elsif ($end < $now) {
                   11198:                 $status = 'future';
                   11199:             } elsif ($start > $now) {
                   11200:                 $status = 'previous';
                   11201:             }
                   11202:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   11203:                 $sectioncount{$section}++;
                   11204:             }
                   11205:         }
1.233     raeburn  11206:     }
1.366     albertel 11207:     return %sectioncount;
1.233     raeburn  11208: }
                   11209: 
1.274     raeburn  11210: ###############################################
1.294     raeburn  11211: 
                   11212: =pod
1.405     albertel 11213: 
                   11214: =item * &get_course_users()
                   11215: 
1.275     raeburn  11216: Retrieves usernames:domains for users in the specified course
                   11217: with specific role(s), and access status. 
                   11218: 
                   11219: Incoming parameters:
1.277     albertel 11220: 1. course domain
                   11221: 2. course number
                   11222: 3. access status: users must have - either active, 
1.275     raeburn  11223: previous, future, or all.
1.277     albertel 11224: 4. reference to array of permissible roles
1.288     raeburn  11225: 5. reference to array of section restrictions (optional)
                   11226: 6. reference to results object (hash of hashes).
                   11227: 7. reference to optional userdata hash
1.609     raeburn  11228: 8. reference to optional statushash
1.630     raeburn  11229: 9. flag if privileged users (except those set to unhide in
                   11230:    course settings) should be excluded    
1.609     raeburn  11231: Keys of top level results hash are roles.
1.275     raeburn  11232: Keys of inner hashes are username:domain, with 
                   11233: values set to access type.
1.288     raeburn  11234: Optional userdata hash returns an array with arguments in the 
                   11235: same order as loncoursedata::get_classlist() for student data.
                   11236: 
1.609     raeburn  11237: Optional statushash returns
                   11238: 
1.288     raeburn  11239: Entries for end, start, section and status are blank because
                   11240: of the possibility of multiple values for non-student roles.
                   11241: 
1.275     raeburn  11242: =cut
1.405     albertel 11243: 
1.275     raeburn  11244: ###############################################
1.405     albertel 11245: 
1.275     raeburn  11246: sub get_course_users {
1.630     raeburn  11247:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  11248:     my %idx = ();
1.419     raeburn  11249:     my %seclists;
1.288     raeburn  11250: 
                   11251:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   11252:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   11253:     $idx{end} = &Apache::loncoursedata::CL_END();
                   11254:     $idx{start} = &Apache::loncoursedata::CL_START();
                   11255:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   11256:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   11257:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   11258:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   11259: 
1.290     albertel 11260:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 11261:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  11262:         my $now = time;
1.277     albertel 11263:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  11264:             my $match = 0;
1.412     raeburn  11265:             my $secmatch = 0;
1.419     raeburn  11266:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  11267:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  11268:             if ($section eq '') {
                   11269:                 $section = 'none';
                   11270:             }
1.291     albertel 11271:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11272:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11273:                     $secmatch = 1;
                   11274:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 11275:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11276:                         $secmatch = 1;
                   11277:                     }
                   11278:                 } else {  
1.419     raeburn  11279: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  11280: 		        $secmatch = 1;
                   11281:                     }
1.290     albertel 11282: 		}
1.412     raeburn  11283:                 if (!$secmatch) {
                   11284:                     next;
                   11285:                 }
1.419     raeburn  11286:             }
1.275     raeburn  11287:             if (defined($$types{'active'})) {
1.288     raeburn  11288:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  11289:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  11290:                     $match = 1;
1.275     raeburn  11291:                 }
                   11292:             }
                   11293:             if (defined($$types{'previous'})) {
1.609     raeburn  11294:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  11295:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  11296:                     $match = 1;
1.275     raeburn  11297:                 }
                   11298:             }
                   11299:             if (defined($$types{'future'})) {
1.609     raeburn  11300:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  11301:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  11302:                     $match = 1;
1.275     raeburn  11303:                 }
                   11304:             }
1.609     raeburn  11305:             if ($match) {
                   11306:                 push(@{$seclists{$student}},$section);
                   11307:                 if (ref($userdata) eq 'HASH') {
                   11308:                     $$userdata{$student} = $$classlist{$student};
                   11309:                 }
                   11310:                 if (ref($statushash) eq 'HASH') {
                   11311:                     $statushash->{$student}{'st'}{$section} = $status;
                   11312:                 }
1.288     raeburn  11313:             }
1.275     raeburn  11314:         }
                   11315:     }
1.412     raeburn  11316:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  11317:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11318:         my $now = time;
1.609     raeburn  11319:         my %displaystatus = ( previous => 'Expired',
                   11320:                               active   => 'Active',
                   11321:                               future   => 'Future',
                   11322:                             );
1.1121    raeburn  11323:         my (%nothide,@possdoms);
1.630     raeburn  11324:         if ($hidepriv) {
                   11325:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   11326:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   11327:                 if ($user !~ /:/) {
                   11328:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   11329:                 } else {
                   11330:                     $nothide{$user} = 1;
                   11331:                 }
                   11332:             }
1.1121    raeburn  11333:             my @possdoms = ($cdom);
                   11334:             if ($coursehash{'checkforpriv'}) {
                   11335:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   11336:             }
1.630     raeburn  11337:         }
1.439     raeburn  11338:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  11339:             my $match = 0;
1.412     raeburn  11340:             my $secmatch = 0;
1.439     raeburn  11341:             my $status;
1.412     raeburn  11342:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  11343:             $user =~ s/:$//;
1.439     raeburn  11344:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   11345:             if ($end == -1 || $start == -1) {
                   11346:                 next;
                   11347:             }
                   11348:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   11349:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  11350:                 my ($uname,$udom) = split(/:/,$user);
                   11351:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11352:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11353:                         $secmatch = 1;
                   11354:                     } elsif ($usec eq '') {
1.420     albertel 11355:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11356:                             $secmatch = 1;
                   11357:                         }
                   11358:                     } else {
                   11359:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   11360:                             $secmatch = 1;
                   11361:                         }
                   11362:                     }
                   11363:                     if (!$secmatch) {
                   11364:                         next;
                   11365:                     }
1.288     raeburn  11366:                 }
1.419     raeburn  11367:                 if ($usec eq '') {
                   11368:                     $usec = 'none';
                   11369:                 }
1.275     raeburn  11370:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  11371:                     if ($hidepriv) {
1.1121    raeburn  11372:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  11373:                             (!$nothide{$uname.':'.$udom})) {
                   11374:                             next;
                   11375:                         }
                   11376:                     }
1.503     raeburn  11377:                     if ($end > 0 && $end < $now) {
1.439     raeburn  11378:                         $status = 'previous';
                   11379:                     } elsif ($start > $now) {
                   11380:                         $status = 'future';
                   11381:                     } else {
                   11382:                         $status = 'active';
                   11383:                     }
1.277     albertel 11384:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  11385:                         if ($status eq $type) {
1.420     albertel 11386:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  11387:                                 push(@{$$users{$role}{$user}},$type);
                   11388:                             }
1.288     raeburn  11389:                             $match = 1;
                   11390:                         }
                   11391:                     }
1.419     raeburn  11392:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   11393:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   11394: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   11395:                         }
1.420     albertel 11396:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  11397:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   11398:                         }
1.609     raeburn  11399:                         if (ref($statushash) eq 'HASH') {
                   11400:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   11401:                         }
1.275     raeburn  11402:                     }
                   11403:                 }
                   11404:             }
                   11405:         }
1.290     albertel 11406:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  11407:             if ((defined($cdom)) && (defined($cnum))) {
                   11408:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   11409:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   11410:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  11411:                     next if ($owner eq '');
                   11412:                     my ($ownername,$ownerdom);
                   11413:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   11414:                         $ownername = $1;
                   11415:                         $ownerdom = $2;
                   11416:                     } else {
                   11417:                         $ownername = $owner;
                   11418:                         $ownerdom = $cdom;
                   11419:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  11420:                     }
                   11421:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 11422:                     if (defined($userdata) && 
1.609     raeburn  11423: 			!exists($$userdata{$owner})) {
                   11424: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   11425:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   11426:                             push(@{$seclists{$owner}},'none');
                   11427:                         }
                   11428:                         if (ref($statushash) eq 'HASH') {
                   11429:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  11430:                         }
1.290     albertel 11431: 		    }
1.279     raeburn  11432:                 }
                   11433:             }
                   11434:         }
1.419     raeburn  11435:         foreach my $user (keys(%seclists)) {
                   11436:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   11437:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   11438:         }
1.275     raeburn  11439:     }
                   11440:     return;
                   11441: }
                   11442: 
1.288     raeburn  11443: sub get_user_info {
                   11444:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 11445:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   11446: 	&plainname($uname,$udom,'lastname');
1.291     albertel 11447:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  11448:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  11449:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   11450:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  11451:     return;
                   11452: }
1.275     raeburn  11453: 
1.472     raeburn  11454: ###############################################
                   11455: 
                   11456: =pod
                   11457: 
                   11458: =item * &get_user_quota()
                   11459: 
1.1134    raeburn  11460: Retrieves quota assigned for storage of user files.
                   11461: Default is to report quota for portfolio files.
1.472     raeburn  11462: 
                   11463: Incoming parameters:
                   11464: 1. user's username
                   11465: 2. user's domain
1.1134    raeburn  11466: 3. quota name - portfolio, author, or course
1.1136    raeburn  11467:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  11468: 4. crstype - official, unofficial, textbook, placement or community, 
                   11469:    if quota name is course
1.472     raeburn  11470: 
                   11471: Returns:
1.1163    raeburn  11472: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  11473: 2. (Optional) Type of setting: custom or default
                   11474:    (individually assigned or default for user's 
                   11475:    institutional status).
                   11476: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   11477:    or student - types as defined in localenroll::inst_usertypes 
                   11478:    for user's domain, which determines default quota for user.
                   11479: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  11480: 
                   11481: If a value has been stored in the user's environment, 
1.536     raeburn  11482: it will return that, otherwise it returns the maximal default
1.1134    raeburn  11483: defined for the user's institutional status(es) in the domain.
1.472     raeburn  11484: 
                   11485: =cut
                   11486: 
                   11487: ###############################################
                   11488: 
                   11489: 
                   11490: sub get_user_quota {
1.1136    raeburn  11491:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  11492:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  11493:     if (!defined($udom)) {
                   11494:         $udom = $env{'user.domain'};
                   11495:     }
                   11496:     if (!defined($uname)) {
                   11497:         $uname = $env{'user.name'};
                   11498:     }
                   11499:     if (($udom eq '' || $uname eq '') ||
                   11500:         ($udom eq 'public') && ($uname eq 'public')) {
                   11501:         $quota = 0;
1.536     raeburn  11502:         $quotatype = 'default';
                   11503:         $defquota = 0; 
1.472     raeburn  11504:     } else {
1.536     raeburn  11505:         my $inststatus;
1.1134    raeburn  11506:         if ($quotaname eq 'course') {
                   11507:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   11508:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   11509:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   11510:             } else {
                   11511:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   11512:                 $quota = $cenv{'internal.uploadquota'};
                   11513:             }
1.536     raeburn  11514:         } else {
1.1134    raeburn  11515:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   11516:                 if ($quotaname eq 'author') {
                   11517:                     $quota = $env{'environment.authorquota'};
                   11518:                 } else {
                   11519:                     $quota = $env{'environment.portfolioquota'};
                   11520:                 }
                   11521:                 $inststatus = $env{'environment.inststatus'};
                   11522:             } else {
                   11523:                 my %userenv = 
                   11524:                     &Apache::lonnet::get('environment',['portfolioquota',
                   11525:                                          'authorquota','inststatus'],$udom,$uname);
                   11526:                 my ($tmp) = keys(%userenv);
                   11527:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   11528:                     if ($quotaname eq 'author') {
                   11529:                         $quota = $userenv{'authorquota'};
                   11530:                     } else {
                   11531:                         $quota = $userenv{'portfolioquota'};
                   11532:                     }
                   11533:                     $inststatus = $userenv{'inststatus'};
                   11534:                 } else {
                   11535:                     undef(%userenv);
                   11536:                 }
                   11537:             }
                   11538:         }
                   11539:         if ($quota eq '' || wantarray) {
                   11540:             if ($quotaname eq 'course') {
                   11541:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  11542:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  11543:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   11544:                     ($crstype eq 'placement')) { 
1.1136    raeburn  11545:                     $defquota = $domdefs{$crstype.'quota'};
                   11546:                 }
                   11547:                 if ($defquota eq '') {
                   11548:                     $defquota = 500;
                   11549:                 }
1.1134    raeburn  11550:             } else {
                   11551:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   11552:             }
                   11553:             if ($quota eq '') {
                   11554:                 $quota = $defquota;
                   11555:                 $quotatype = 'default';
                   11556:             } else {
                   11557:                 $quotatype = 'custom';
                   11558:             }
1.472     raeburn  11559:         }
                   11560:     }
1.536     raeburn  11561:     if (wantarray) {
                   11562:         return ($quota,$quotatype,$settingstatus,$defquota);
                   11563:     } else {
                   11564:         return $quota;
                   11565:     }
1.472     raeburn  11566: }
                   11567: 
                   11568: ###############################################
                   11569: 
                   11570: =pod
                   11571: 
                   11572: =item * &default_quota()
                   11573: 
1.536     raeburn  11574: Retrieves default quota assigned for storage of user portfolio files,
                   11575: given an (optional) user's institutional status.
1.472     raeburn  11576: 
                   11577: Incoming parameters:
1.1142    raeburn  11578: 
1.472     raeburn  11579: 1. domain
1.536     raeburn  11580: 2. (Optional) institutional status(es).  This is a : separated list of 
                   11581:    status types (e.g., faculty, staff, student etc.)
                   11582:    which apply to the user for whom the default is being retrieved.
                   11583:    If the institutional status string in undefined, the domain
1.1134    raeburn  11584:    default quota will be returned.
                   11585: 3.  quota name - portfolio, author, or course
                   11586:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  11587: 
                   11588: Returns:
1.1142    raeburn  11589: 
1.1163    raeburn  11590: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  11591: 2. (Optional) institutional type which determined the value of the
                   11592:    default quota.
1.472     raeburn  11593: 
                   11594: If a value has been stored in the domain's configuration db,
                   11595: it will return that, otherwise it returns 20 (for backwards 
                   11596: compatibility with domains which have not set up a configuration
1.1163    raeburn  11597: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  11598: 
1.536     raeburn  11599: If the user's status includes multiple types (e.g., staff and student),
                   11600: the largest default quota which applies to the user determines the
                   11601: default quota returned.
                   11602: 
1.472     raeburn  11603: =cut
                   11604: 
                   11605: ###############################################
                   11606: 
                   11607: 
                   11608: sub default_quota {
1.1134    raeburn  11609:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  11610:     my ($defquota,$settingstatus);
                   11611:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  11612:                                             ['quotas'],$udom);
1.1134    raeburn  11613:     my $key = 'defaultquota';
                   11614:     if ($quotaname eq 'author') {
                   11615:         $key = 'authorquota';
                   11616:     }
1.622     raeburn  11617:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  11618:         if ($inststatus ne '') {
1.765     raeburn  11619:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  11620:             foreach my $item (@statuses) {
1.1134    raeburn  11621:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11622:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  11623:                         if ($defquota eq '') {
1.1134    raeburn  11624:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11625:                             $settingstatus = $item;
1.1134    raeburn  11626:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11627:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11628:                             $settingstatus = $item;
                   11629:                         }
                   11630:                     }
1.1134    raeburn  11631:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11632:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11633:                         if ($defquota eq '') {
                   11634:                             $defquota = $quotahash{'quotas'}{$item};
                   11635:                             $settingstatus = $item;
                   11636:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11637:                             $defquota = $quotahash{'quotas'}{$item};
                   11638:                             $settingstatus = $item;
                   11639:                         }
1.536     raeburn  11640:                     }
                   11641:                 }
                   11642:             }
                   11643:         }
                   11644:         if ($defquota eq '') {
1.1134    raeburn  11645:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11646:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11647:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11648:                 $defquota = $quotahash{'quotas'}{'default'};
                   11649:             }
1.536     raeburn  11650:             $settingstatus = 'default';
1.1139    raeburn  11651:             if ($defquota eq '') {
                   11652:                 if ($quotaname eq 'author') {
                   11653:                     $defquota = 500;
                   11654:                 }
                   11655:             }
1.536     raeburn  11656:         }
                   11657:     } else {
                   11658:         $settingstatus = 'default';
1.1134    raeburn  11659:         if ($quotaname eq 'author') {
                   11660:             $defquota = 500;
                   11661:         } else {
                   11662:             $defquota = 20;
                   11663:         }
1.536     raeburn  11664:     }
                   11665:     if (wantarray) {
                   11666:         return ($defquota,$settingstatus);
1.472     raeburn  11667:     } else {
1.536     raeburn  11668:         return $defquota;
1.472     raeburn  11669:     }
                   11670: }
                   11671: 
1.1135    raeburn  11672: ###############################################
                   11673: 
                   11674: =pod
                   11675: 
1.1136    raeburn  11676: =item * &excess_filesize_warning()
1.1135    raeburn  11677: 
                   11678: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  11679: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  11680: space to be exceeded.
1.1136    raeburn  11681: 
                   11682: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  11683: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  11684: 
1.1165    raeburn  11685: Inputs: 7 
1.1136    raeburn  11686: 1. username or coursenum
1.1135    raeburn  11687: 2. domain
1.1136    raeburn  11688: 3. context ('author' or 'course')
1.1135    raeburn  11689: 4. filename of file for which action is being requested
                   11690: 5. filesize (kB) of file
                   11691: 6. action being taken: copy or upload.
1.1237    raeburn  11692: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  11693: 
                   11694: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  11695:          otherwise return null.
                   11696: 
                   11697: =back
1.1135    raeburn  11698: 
                   11699: =cut
                   11700: 
1.1136    raeburn  11701: sub excess_filesize_warning {
1.1165    raeburn  11702:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  11703:     my $current_disk_usage = 0;
1.1165    raeburn  11704:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  11705:     if ($context eq 'author') {
                   11706:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11707:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11708:     } else {
                   11709:         foreach my $subdir ('docs','supplemental') {
                   11710:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11711:         }
                   11712:     }
1.1135    raeburn  11713:     $disk_quota = int($disk_quota * 1000);
                   11714:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11715:         return '<p class="LC_warning">'.
1.1135    raeburn  11716:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11717:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11718:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11719:                             $disk_quota,$current_disk_usage).
                   11720:                '</p>';
                   11721:     }
                   11722:     return;
                   11723: }
                   11724: 
                   11725: ###############################################
                   11726: 
                   11727: 
1.1136    raeburn  11728: 
                   11729: 
1.384     raeburn  11730: sub get_secgrprole_info {
                   11731:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11732:     my %sections_count = &get_sections($cdom,$cnum);
                   11733:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11734:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11735:     my @groups = sort(keys(%curr_groups));
                   11736:     my $allroles = [];
                   11737:     my $rolehash;
                   11738:     my $accesshash = {
                   11739:                      active => 'Currently has access',
                   11740:                      future => 'Will have future access',
                   11741:                      previous => 'Previously had access',
                   11742:                   };
                   11743:     if ($needroles) {
                   11744:         $rolehash = {'all' => 'all'};
1.385     albertel 11745:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11746: 	if (&Apache::lonnet::error(%user_roles)) {
                   11747: 	    undef(%user_roles);
                   11748: 	}
                   11749:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11750:             my ($role)=split(/\:/,$item,2);
                   11751:             if ($role eq 'cr') { next; }
                   11752:             if ($role =~ /^cr/) {
                   11753:                 $$rolehash{$role} = (split('/',$role))[3];
                   11754:             } else {
                   11755:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11756:             }
                   11757:         }
                   11758:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11759:             push(@{$allroles},$key);
                   11760:         }
                   11761:         push (@{$allroles},'st');
                   11762:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11763:     }
                   11764:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11765: }
                   11766: 
1.555     raeburn  11767: sub user_picker {
1.1279    raeburn  11768:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11769:     my $currdom = $dom;
1.1253    raeburn  11770:     my @alldoms = &Apache::lonnet::all_domains();
                   11771:     if (@alldoms == 1) {
                   11772:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11773:                                                ['directorysrch'],$alldoms[0]);
                   11774:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11775:         my $showdom = $domdesc;
                   11776:         if ($showdom eq '') {
                   11777:             $showdom = $dom;
                   11778:         }
                   11779:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11780:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11781:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11782:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11783:             }
                   11784:         }
                   11785:     }
1.555     raeburn  11786:     my %curr_selected = (
                   11787:                         srchin => 'dom',
1.580     raeburn  11788:                         srchby => 'lastname',
1.555     raeburn  11789:                       );
                   11790:     my $srchterm;
1.625     raeburn  11791:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11792:         if ($srch->{'srchby'} ne '') {
                   11793:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11794:         }
                   11795:         if ($srch->{'srchin'} ne '') {
                   11796:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11797:         }
                   11798:         if ($srch->{'srchtype'} ne '') {
                   11799:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11800:         }
                   11801:         if ($srch->{'srchdomain'} ne '') {
                   11802:             $currdom = $srch->{'srchdomain'};
                   11803:         }
                   11804:         $srchterm = $srch->{'srchterm'};
                   11805:     }
1.1222    damieng  11806:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11807:                     'usr'       => 'Search criteria',
1.563     raeburn  11808:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11809:                     'uname'     => 'username',
                   11810:                     'lastname'  => 'last name',
1.555     raeburn  11811:                     'lastfirst' => 'last name, first name',
1.558     albertel 11812:                     'crs'       => 'in this course',
1.576     raeburn  11813:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11814:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11815:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11816:                     'exact'     => 'is',
                   11817:                     'contains'  => 'contains',
1.569     raeburn  11818:                     'begins'    => 'begins with',
1.1222    damieng  11819:                                        );
                   11820:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11821:                     'youm'      => "You must include some text to search for.",
                   11822:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11823:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11824:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11825:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11826:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11827:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11828:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11829:                                        );
1.1222    damieng  11830:     &html_escape(\%html_lt);
                   11831:     &js_escape(\%js_lt);
1.1255    raeburn  11832:     my $domform;
1.1277    raeburn  11833:     my $allow_blank = 1;
1.1255    raeburn  11834:     if ($fixeddom) {
1.1277    raeburn  11835:         $allow_blank = 0;
                   11836:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11837:     } else {
1.1287    raeburn  11838:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11839:         my ($trusted,$untrusted);
1.1287    raeburn  11840:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11841:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11842:         } elsif ($context eq 'author') {
1.1288    raeburn  11843:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11844:         } elsif ($context eq 'domain') {
1.1288    raeburn  11845:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11846:         }
1.1288    raeburn  11847:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11848:     }
1.563     raeburn  11849:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11850: 
                   11851:     my @srchins = ('crs','dom','alc','instd');
                   11852: 
                   11853:     foreach my $option (@srchins) {
                   11854:         # FIXME 'alc' option unavailable until 
                   11855:         #       loncreateuser::print_user_query_page()
                   11856:         #       has been completed.
                   11857:         next if ($option eq 'alc');
1.880     raeburn  11858:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11859:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11860:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11861:         if ($curr_selected{'srchin'} eq $option) {
                   11862:             $srchinsel .= ' 
1.1222    damieng  11863:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11864:         } else {
                   11865:             $srchinsel .= '
1.1222    damieng  11866:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11867:         }
1.555     raeburn  11868:     }
1.563     raeburn  11869:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11870: 
                   11871:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11872:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11873:         if ($curr_selected{'srchby'} eq $option) {
                   11874:             $srchbysel .= '
1.1222    damieng  11875:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11876:         } else {
                   11877:             $srchbysel .= '
1.1222    damieng  11878:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11879:          }
                   11880:     }
                   11881:     $srchbysel .= "\n  </select>\n";
                   11882: 
                   11883:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11884:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11885:         if ($curr_selected{'srchtype'} eq $option) {
                   11886:             $srchtypesel .= '
1.1222    damieng  11887:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11888:         } else {
                   11889:             $srchtypesel .= '
1.1222    damieng  11890:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11891:         }
                   11892:     }
                   11893:     $srchtypesel .= "\n  </select>\n";
                   11894: 
1.558     albertel 11895:     my ($newuserscript,$new_user_create);
1.994     raeburn  11896:     my $context_dom = $env{'request.role.domain'};
                   11897:     if ($context eq 'requestcrs') {
                   11898:         if ($env{'form.coursedom'} ne '') { 
                   11899:             $context_dom = $env{'form.coursedom'};
                   11900:         }
                   11901:     }
1.556     raeburn  11902:     if ($forcenewuser) {
1.576     raeburn  11903:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11904:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11905:                 if ($cancreate) {
                   11906:                     $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>';
                   11907:                 } else {
1.799     bisitz   11908:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11909:                     my %usertypetext = (
                   11910:                         official   => 'institutional',
                   11911:                         unofficial => 'non-institutional',
                   11912:                     );
1.799     bisitz   11913:                     $new_user_create = '<p class="LC_warning">'
                   11914:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11915:                                       .' '
                   11916:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11917:                                           ,'<a href="'.$helplink.'">','</a>')
                   11918:                                       .'</p><br />';
1.627     raeburn  11919:                 }
1.576     raeburn  11920:             }
                   11921:         }
                   11922: 
1.556     raeburn  11923:         $newuserscript = <<"ENDSCRIPT";
                   11924: 
1.570     raeburn  11925: function setSearch(createnew,callingForm) {
1.556     raeburn  11926:     if (createnew == 1) {
1.570     raeburn  11927:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11928:             if (callingForm.srchby.options[i].value == 'uname') {
                   11929:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11930:             }
                   11931:         }
1.570     raeburn  11932:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11933:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11934: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11935:             }
                   11936:         }
1.570     raeburn  11937:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11938:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11939:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11940:             }
                   11941:         }
1.570     raeburn  11942:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11943:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11944:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11945:             }
                   11946:         }
                   11947:     }
                   11948: }
                   11949: ENDSCRIPT
1.558     albertel 11950: 
1.556     raeburn  11951:     }
                   11952: 
1.555     raeburn  11953:     my $output = <<"END_BLOCK";
1.556     raeburn  11954: <script type="text/javascript">
1.824     bisitz   11955: // <![CDATA[
1.570     raeburn  11956: function validateEntry(callingForm) {
1.558     albertel 11957: 
1.556     raeburn  11958:     var checkok = 1;
1.558     albertel 11959:     var srchin;
1.570     raeburn  11960:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11961: 	if ( callingForm.srchin[i].checked ) {
                   11962: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11963: 	}
                   11964:     }
                   11965: 
1.570     raeburn  11966:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11967:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11968:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11969:     var srchterm =  callingForm.srchterm.value;
                   11970:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11971:     var msg = "";
                   11972: 
                   11973:     if (srchterm == "") {
                   11974:         checkok = 0;
1.1222    damieng  11975:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11976:     }
                   11977: 
1.569     raeburn  11978:     if (srchtype== 'begins') {
                   11979:         if (srchterm.length < 2) {
                   11980:             checkok = 0;
1.1222    damieng  11981:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11982:         }
                   11983:     }
                   11984: 
1.556     raeburn  11985:     if (srchtype== 'contains') {
                   11986:         if (srchterm.length < 3) {
                   11987:             checkok = 0;
1.1222    damieng  11988:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11989:         }
                   11990:     }
                   11991:     if (srchin == 'instd') {
                   11992:         if (srchdomain == '') {
                   11993:             checkok = 0;
1.1222    damieng  11994:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11995:         }
                   11996:     }
                   11997:     if (srchin == 'dom') {
                   11998:         if (srchdomain == '') {
                   11999:             checkok = 0;
1.1222    damieng  12000:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  12001:         }
                   12002:     }
                   12003:     if (srchby == 'lastfirst') {
                   12004:         if (srchterm.indexOf(",") == -1) {
                   12005:             checkok = 0;
1.1222    damieng  12006:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  12007:         }
                   12008:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   12009:             checkok = 0;
1.1222    damieng  12010:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  12011:         }
                   12012:     }
                   12013:     if (checkok == 0) {
1.1222    damieng  12014:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  12015:         return;
                   12016:     }
                   12017:     if (checkok == 1) {
1.570     raeburn  12018:         callingForm.submit();
1.556     raeburn  12019:     }
                   12020: }
                   12021: 
                   12022: $newuserscript
                   12023: 
1.824     bisitz   12024: // ]]>
1.556     raeburn  12025: </script>
1.558     albertel 12026: 
                   12027: $new_user_create
                   12028: 
1.555     raeburn  12029: END_BLOCK
1.558     albertel 12030: 
1.876     raeburn  12031:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  12032:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  12033:                $domform.
                   12034:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  12035:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  12036:                $srchbysel.
                   12037:                $srchtypesel. 
                   12038:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   12039:                $srchinsel.
                   12040:                &Apache::lonhtmlcommon::row_closure(1). 
                   12041:                &Apache::lonhtmlcommon::end_pick_box().
                   12042:                '<br />';
1.1253    raeburn  12043:     return ($output,1);
1.555     raeburn  12044: }
                   12045: 
1.612     raeburn  12046: sub user_rule_check {
1.615     raeburn  12047:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  12048:     my ($response,%inst_response);
1.612     raeburn  12049:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  12050:         if (keys(%{$usershash}) > 1) {
                   12051:             my (%by_username,%by_id,%userdoms);
                   12052:             my $checkid; 
                   12053:             if (ref($checks) eq 'HASH') {
                   12054:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   12055:                     $checkid = 1;
                   12056:                 }
                   12057:             }
                   12058:             foreach my $user (keys(%{$usershash})) {
                   12059:                 my ($uname,$udom) = split(/:/,$user);
                   12060:                 if ($checkid) {
                   12061:                     if (ref($usershash->{$user}) eq 'HASH') {
                   12062:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  12063:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  12064:                             $userdoms{$udom} = 1;
1.1227    raeburn  12065:                             if (ref($inst_results) eq 'HASH') {
                   12066:                                 $inst_results->{$uname.':'.$udom} = {};
                   12067:                             }
1.1226    raeburn  12068:                         }
                   12069:                     }
                   12070:                 } else {
                   12071:                     $by_username{$udom}{$uname} = 1;
                   12072:                     $userdoms{$udom} = 1;
1.1227    raeburn  12073:                     if (ref($inst_results) eq 'HASH') {
                   12074:                         $inst_results->{$uname.':'.$udom} = {};
                   12075:                     }
1.1226    raeburn  12076:                 }
                   12077:             }
                   12078:             foreach my $udom (keys(%userdoms)) {
                   12079:                 if (!$got_rules->{$udom}) {
                   12080:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12081:                                                              ['usercreation'],$udom);
                   12082:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12083:                         foreach my $item ('username','id') {
                   12084:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  12085:                                 $$curr_rules{$udom}{$item} =
                   12086:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  12087:                             }
                   12088:                         }
                   12089:                     }
                   12090:                     $got_rules->{$udom} = 1;
                   12091:                 }
1.612     raeburn  12092:             }
1.1226    raeburn  12093:             if ($checkid) {
                   12094:                 foreach my $udom (keys(%by_id)) {
                   12095:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   12096:                     if ($outcome eq 'ok') {
1.1227    raeburn  12097:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   12098:                             my $uname = $by_id{$udom}{$id};
                   12099:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12100:                         }
1.1226    raeburn  12101:                         if (ref($results) eq 'HASH') {
                   12102:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  12103:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   12104:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   12105:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12106:                                 }
1.1226    raeburn  12107:                             }
                   12108:                         }
                   12109:                     }
1.612     raeburn  12110:                 }
1.615     raeburn  12111:             } else {
1.1226    raeburn  12112:                 foreach my $udom (keys(%by_username)) {
                   12113:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   12114:                     if ($outcome eq 'ok') {
1.1227    raeburn  12115:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   12116:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12117:                         }
1.1226    raeburn  12118:                         if (ref($results) eq 'HASH') {
                   12119:                             foreach my $uname (keys(%{$results})) {
                   12120:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12121:                             }
                   12122:                         }
                   12123:                     }
                   12124:                 }
1.612     raeburn  12125:             }
1.1226    raeburn  12126:         } elsif (keys(%{$usershash}) == 1) {
                   12127:             my $user = (keys(%{$usershash}))[0];
                   12128:             my ($uname,$udom) = split(/:/,$user);
                   12129:             if (($udom ne '') && ($uname ne '')) {
                   12130:                 if (ref($usershash->{$user}) eq 'HASH') {
                   12131:                     if (ref($checks) eq 'HASH') {
                   12132:                         if (defined($checks->{'username'})) {
                   12133:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   12134:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   12135:                         } elsif (defined($checks->{'id'})) {
                   12136:                             if ($usershash->{$user}->{'id'} ne '') {
                   12137:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12138:                                     &Apache::lonnet::get_instuser($udom,undef,
                   12139:                                                                   $usershash->{$user}->{'id'});
                   12140:                             } else {
                   12141:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12142:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   12143:                             }
1.585     raeburn  12144:                         }
1.1226    raeburn  12145:                     } else {
                   12146:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   12147:                             &Apache::lonnet::get_instuser($udom,$uname);
                   12148:                        return;
                   12149:                     }
                   12150:                     if (!$got_rules->{$udom}) {
                   12151:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12152:                                                                  ['usercreation'],$udom);
                   12153:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12154:                             foreach my $item ('username','id') {
                   12155:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   12156:                                    $$curr_rules{$udom}{$item} = 
                   12157:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   12158:                                 }
                   12159:                             }
                   12160:                         }
                   12161:                         $got_rules->{$udom} = 1;
1.585     raeburn  12162:                     }
                   12163:                 }
1.1226    raeburn  12164:             } else {
                   12165:                 return;
                   12166:             }
                   12167:         } else {
                   12168:             return;
                   12169:         }
                   12170:         foreach my $user (keys(%{$usershash})) {
                   12171:             my ($uname,$udom) = split(/:/,$user);
                   12172:             next if (($udom eq '') || ($uname eq ''));
                   12173:             my $id;
1.1227    raeburn  12174:             if (ref($inst_results) eq 'HASH') {
                   12175:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   12176:                     $id = $inst_results->{$user}->{'id'};
                   12177:                 }
                   12178:             }
                   12179:             if ($id eq '') { 
                   12180:                 if (ref($usershash->{$user})) {
                   12181:                     $id = $usershash->{$user}->{'id'};
                   12182:                 }
1.585     raeburn  12183:             }
1.612     raeburn  12184:             foreach my $item (keys(%{$checks})) {
                   12185:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   12186:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   12187:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  12188:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   12189:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  12190:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   12191:                                 if ($rule_check{$rule}) {
                   12192:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  12193:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  12194:                                         if (ref($inst_results) eq 'HASH') {
                   12195:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   12196:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   12197:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  12198:                                                 } elsif ($item eq 'id') {
                   12199:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   12200:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   12201:                                                     }
1.615     raeburn  12202:                                                 }
1.612     raeburn  12203:                                             }
                   12204:                                         }
1.615     raeburn  12205:                                     }
                   12206:                                     last;
1.585     raeburn  12207:                                 }
                   12208:                             }
                   12209:                         }
                   12210:                     }
                   12211:                 }
                   12212:             }
                   12213:         }
                   12214:     }
1.612     raeburn  12215:     return;
                   12216: }
                   12217: 
                   12218: sub user_rule_formats {
                   12219:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   12220:     my %text = ( 
                   12221:                  'username' => 'Usernames',
                   12222:                  'id'       => 'IDs',
                   12223:                );
                   12224:     my $output;
                   12225:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   12226:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   12227:         if (@{$ruleorder} > 0) {
1.1102    raeburn  12228:             $output = '<br />'.
                   12229:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   12230:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   12231:                       ' <ul>';
1.612     raeburn  12232:             foreach my $rule (@{$ruleorder}) {
                   12233:                 if (ref($curr_rules) eq 'ARRAY') {
                   12234:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   12235:                         if (ref($rules->{$rule}) eq 'HASH') {
                   12236:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   12237:                                         $rules->{$rule}{'desc'}.'</li>';
                   12238:                         }
                   12239:                     }
                   12240:                 }
                   12241:             }
                   12242:             $output .= '</ul>';
                   12243:         }
                   12244:     }
                   12245:     return $output;
                   12246: }
                   12247: 
                   12248: sub instrule_disallow_msg {
1.615     raeburn  12249:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  12250:     my $response;
                   12251:     my %text = (
                   12252:                   item   => 'username',
                   12253:                   items  => 'usernames',
                   12254:                   match  => 'matches',
                   12255:                   do     => 'does',
                   12256:                   action => 'a username',
                   12257:                   one    => 'one',
                   12258:                );
                   12259:     if ($count > 1) {
                   12260:         $text{'item'} = 'usernames';
                   12261:         $text{'match'} ='match';
                   12262:         $text{'do'} = 'do';
                   12263:         $text{'action'} = 'usernames',
                   12264:         $text{'one'} = 'ones';
                   12265:     }
                   12266:     if ($checkitem eq 'id') {
                   12267:         $text{'items'} = 'IDs';
                   12268:         $text{'item'} = 'ID';
                   12269:         $text{'action'} = 'an ID';
1.615     raeburn  12270:         if ($count > 1) {
                   12271:             $text{'item'} = 'IDs';
                   12272:             $text{'action'} = 'IDs';
                   12273:         }
1.612     raeburn  12274:     }
1.674     bisitz   12275:     $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  12276:     if ($mode eq 'upload') {
                   12277:         if ($checkitem eq 'username') {
                   12278:             $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'}.");
                   12279:         } elsif ($checkitem eq 'id') {
1.674     bisitz   12280:             $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  12281:         }
1.669     raeburn  12282:     } elsif ($mode eq 'selfcreate') {
                   12283:         if ($checkitem eq 'id') {
                   12284:             $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.");
                   12285:         }
1.615     raeburn  12286:     } else {
                   12287:         if ($checkitem eq 'username') {
                   12288:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   12289:         } elsif ($checkitem eq 'id') {
                   12290:             $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.");
                   12291:         }
1.612     raeburn  12292:     }
                   12293:     return $response;
1.585     raeburn  12294: }
                   12295: 
1.624     raeburn  12296: sub personal_data_fieldtitles {
                   12297:     my %fieldtitles = &Apache::lonlocal::texthash (
                   12298:                         id => 'Student/Employee ID',
                   12299:                         permanentemail => 'E-mail address',
                   12300:                         lastname => 'Last Name',
                   12301:                         firstname => 'First Name',
                   12302:                         middlename => 'Middle Name',
                   12303:                         generation => 'Generation',
                   12304:                         gen => 'Generation',
1.765     raeburn  12305:                         inststatus => 'Affiliation',
1.624     raeburn  12306:                    );
                   12307:     return %fieldtitles;
                   12308: }
                   12309: 
1.642     raeburn  12310: sub sorted_inst_types {
                   12311:     my ($dom) = @_;
1.1185    raeburn  12312:     my ($usertypes,$order);
                   12313:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   12314:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   12315:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   12316:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   12317:     } else {
                   12318:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   12319:     }
1.642     raeburn  12320:     my $othertitle = &mt('All users');
                   12321:     if ($env{'request.course.id'}) {
1.668     raeburn  12322:         $othertitle  = &mt('Any users');
1.642     raeburn  12323:     }
                   12324:     my @types;
                   12325:     if (ref($order) eq 'ARRAY') {
                   12326:         @types = @{$order};
                   12327:     }
                   12328:     if (@types == 0) {
                   12329:         if (ref($usertypes) eq 'HASH') {
                   12330:             @types = sort(keys(%{$usertypes}));
                   12331:         }
                   12332:     }
                   12333:     if (keys(%{$usertypes}) > 0) {
                   12334:         $othertitle = &mt('Other users');
                   12335:     }
                   12336:     return ($othertitle,$usertypes,\@types);
                   12337: }
                   12338: 
1.645     raeburn  12339: sub get_institutional_codes {
1.1361    raeburn  12340:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  12341: # Get complete list of course sections to update
                   12342:     my @currsections = ();
                   12343:     my @currxlists = ();
1.1361    raeburn  12344:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  12345:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  12346:     my $crskey = $crs.':'.$coursecode;
                   12347:     @{$unclutteredsec{$crskey}} = ();
                   12348:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  12349: 
                   12350:     if ($$settings{'internal.sectionnums'} ne '') {
                   12351:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   12352:     }
                   12353: 
                   12354:     if ($$settings{'internal.crosslistings'} ne '') {
                   12355:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   12356:     }
                   12357: 
                   12358:     if (@currxlists > 0) {
1.1361    raeburn  12359:         foreach my $xl (@currxlists) {
                   12360:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  12361:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  12362:                     push(@{$allcourses},$1);
1.645     raeburn  12363:                     $$LC_code{$1} = $2;
                   12364:                 }
                   12365:             }
                   12366:         }
                   12367:     }
1.1361    raeburn  12368: 
1.645     raeburn  12369:     if (@currsections > 0) {
1.1361    raeburn  12370:         foreach my $sec (@currsections) {
                   12371:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   12372:                 my $instsec = $1;
1.645     raeburn  12373:                 my $lc_sec = $2;
1.1361    raeburn  12374:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   12375:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   12376:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   12377:                 }
                   12378:             }
                   12379:         }
                   12380:     }
                   12381: 
                   12382:     if (@{$unclutteredsec{$crskey}} > 0) {
                   12383:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   12384:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   12385:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   12386:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   12387:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  12388:                     push(@{$allcourses},$sec);
1.1361    raeburn  12389:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  12390:                 }
                   12391:             }
                   12392:         }
                   12393:     }
                   12394:     return;
                   12395: }
                   12396: 
1.971     raeburn  12397: sub get_standard_codeitems {
                   12398:     return ('Year','Semester','Department','Number','Section');
                   12399: }
                   12400: 
1.112     bowersj2 12401: =pod
                   12402: 
1.780     raeburn  12403: =head1 Slot Helpers
                   12404: 
                   12405: =over 4
                   12406: 
                   12407: =item * sorted_slots()
                   12408: 
1.1040    raeburn  12409: Sorts an array of slot names in order of an optional sort key,
                   12410: default sort is by slot start time (earliest first). 
1.780     raeburn  12411: 
                   12412: Inputs:
                   12413: 
                   12414: =over 4
                   12415: 
                   12416: slotsarr  - Reference to array of unsorted slot names.
                   12417: 
                   12418: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   12419: 
1.1040    raeburn  12420: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   12421: 
1.549     albertel 12422: =back
                   12423: 
1.780     raeburn  12424: Returns:
                   12425: 
                   12426: =over 4
                   12427: 
1.1040    raeburn  12428: sorted   - An array of slot names sorted by a specified sort key 
                   12429:            (default sort key is start time of the slot).
1.780     raeburn  12430: 
                   12431: =back
                   12432: 
                   12433: =cut
                   12434: 
                   12435: 
                   12436: sub sorted_slots {
1.1040    raeburn  12437:     my ($slotsarr,$slots,$sortkey) = @_;
                   12438:     if ($sortkey eq '') {
                   12439:         $sortkey = 'starttime';
                   12440:     }
1.780     raeburn  12441:     my @sorted;
                   12442:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   12443:         @sorted =
                   12444:             sort {
                   12445:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  12446:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  12447:                      }
                   12448:                      if (ref($slots->{$a})) { return -1;}
                   12449:                      if (ref($slots->{$b})) { return 1;}
                   12450:                      return 0;
                   12451:                  } @{$slotsarr};
                   12452:     }
                   12453:     return @sorted;
                   12454: }
                   12455: 
1.1040    raeburn  12456: =pod
                   12457: 
                   12458: =item * get_future_slots()
                   12459: 
                   12460: Inputs:
                   12461: 
                   12462: =over 4
                   12463: 
                   12464: cnum - course number
                   12465: 
                   12466: cdom - course domain
                   12467: 
                   12468: now - current UNIX time
                   12469: 
                   12470: symb - optional symb
                   12471: 
                   12472: =back
                   12473: 
                   12474: Returns:
                   12475: 
                   12476: =over 4
                   12477: 
                   12478: sorted_reservable - ref to array of student_schedulable slots currently 
                   12479:                     reservable, ordered by end date of reservation period.
                   12480: 
                   12481: reservable_now - ref to hash of student_schedulable slots currently
                   12482:                  reservable.
                   12483: 
                   12484:     Keys in inner hash are:
                   12485:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12486:     (b) endreserve: end date of reservation period.
                   12487:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12488:         selected.
1.1040    raeburn  12489: 
                   12490: sorted_future - ref to array of student_schedulable slots reservable in
                   12491:                 the future, ordered by start date of reservation period.
                   12492: 
                   12493: future_reservable - ref to hash of student_schedulable slots reservable
                   12494:                     in the future.
                   12495: 
                   12496:     Keys in inner hash are:
                   12497:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12498:     (b) startreserve: start date of reservation period.
                   12499:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12500:         selected.
1.1040    raeburn  12501: 
                   12502: =back
                   12503: 
                   12504: =cut
                   12505: 
                   12506: sub get_future_slots {
                   12507:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  12508:     my $map;
                   12509:     if ($symb) {
                   12510:         ($map) = &Apache::lonnet::decode_symb($symb);
                   12511:     }
1.1040    raeburn  12512:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   12513:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   12514:     foreach my $slot (keys(%slots)) {
                   12515:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   12516:         if ($symb) {
1.1229    raeburn  12517:             if ($slots{$slot}->{'symb'} ne '') {
                   12518:                 my $canuse;
                   12519:                 my %oksymbs;
                   12520:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   12521:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   12522:                 if ($oksymbs{$symb}) {
                   12523:                     $canuse = 1;
                   12524:                 } else {
                   12525:                     foreach my $item (@slotsymbs) {
                   12526:                         if ($item =~ /\.(page|sequence)$/) {
                   12527:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   12528:                             if (($map ne '') && ($map eq $sloturl)) {
                   12529:                                 $canuse = 1;
                   12530:                                 last;
                   12531:                             }
                   12532:                         }
                   12533:                     }
                   12534:                 }
                   12535:                 next unless ($canuse);
                   12536:             }
1.1040    raeburn  12537:         }
                   12538:         if (($slots{$slot}->{'starttime'} > $now) &&
                   12539:             ($slots{$slot}->{'endtime'} > $now)) {
                   12540:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   12541:                 my $userallowed = 0;
                   12542:                 if ($slots{$slot}->{'allowedsections'}) {
                   12543:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   12544:                     if (!defined($env{'request.role.sec'})
                   12545:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   12546:                         $userallowed=1;
                   12547:                     } else {
                   12548:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   12549:                             $userallowed=1;
                   12550:                         }
                   12551:                     }
                   12552:                     unless ($userallowed) {
                   12553:                         if (defined($env{'request.course.groups'})) {
                   12554:                             my @groups = split(/:/,$env{'request.course.groups'});
                   12555:                             foreach my $group (@groups) {
                   12556:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   12557:                                     $userallowed=1;
                   12558:                                     last;
                   12559:                                 }
                   12560:                             }
                   12561:                         }
                   12562:                     }
                   12563:                 }
                   12564:                 if ($slots{$slot}->{'allowedusers'}) {
                   12565:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   12566:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   12567:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   12568:                         $userallowed = 1;
                   12569:                     }
                   12570:                 }
                   12571:                 next unless($userallowed);
                   12572:             }
                   12573:             my $startreserve = $slots{$slot}->{'startreserve'};
                   12574:             my $endreserve = $slots{$slot}->{'endreserve'};
                   12575:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  12576:             my $uniqueperiod;
                   12577:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   12578:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   12579:             }
1.1040    raeburn  12580:             if (($startreserve < $now) &&
                   12581:                 (!$endreserve || $endreserve > $now)) {
                   12582:                 my $lastres = $endreserve;
                   12583:                 if (!$lastres) {
                   12584:                     $lastres = $slots{$slot}->{'starttime'};
                   12585:                 }
                   12586:                 $reservable_now{$slot} = {
                   12587:                                            symb       => $symb,
1.1250    raeburn  12588:                                            endreserve => $lastres,
                   12589:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  12590:                                          };
                   12591:             } elsif (($startreserve > $now) &&
                   12592:                      (!$endreserve || $endreserve > $startreserve)) {
                   12593:                 $future_reservable{$slot} = {
                   12594:                                               symb         => $symb,
1.1250    raeburn  12595:                                               startreserve => $startreserve,
                   12596:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  12597:                                             };
                   12598:             }
                   12599:         }
                   12600:     }
                   12601:     my @unsorted_reservable = keys(%reservable_now);
                   12602:     if (@unsorted_reservable > 0) {
                   12603:         @sorted_reservable = 
                   12604:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   12605:     }
                   12606:     my @unsorted_future = keys(%future_reservable);
                   12607:     if (@unsorted_future > 0) {
                   12608:         @sorted_future =
                   12609:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   12610:     }
                   12611:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   12612: }
1.780     raeburn  12613: 
                   12614: =pod
                   12615: 
1.1057    foxr     12616: =back
                   12617: 
1.549     albertel 12618: =head1 HTTP Helpers
                   12619: 
                   12620: =over 4
                   12621: 
1.648     raeburn  12622: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 12623: 
1.258     albertel 12624: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 12625: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 12626: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 12627: 
                   12628: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   12629: $possible_names is an ref to an array of form element names.  As an example:
                   12630: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 12631: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 12632: 
                   12633: =cut
1.1       albertel 12634: 
1.6       albertel 12635: sub get_unprocessed_cgi {
1.25      albertel 12636:   my ($query,$possible_names)= @_;
1.26      matthew  12637:   # $Apache::lonxml::debug=1;
1.356     albertel 12638:   foreach my $pair (split(/&/,$query)) {
                   12639:     my ($name, $value) = split(/=/,$pair);
1.369     www      12640:     $name = &unescape($name);
1.25      albertel 12641:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   12642:       $value =~ tr/+/ /;
                   12643:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 12644:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 12645:     }
1.16      harris41 12646:   }
1.6       albertel 12647: }
                   12648: 
1.112     bowersj2 12649: =pod
                   12650: 
1.648     raeburn  12651: =item * &cacheheader() 
1.112     bowersj2 12652: 
                   12653: returns cache-controlling header code
                   12654: 
                   12655: =cut
                   12656: 
1.7       albertel 12657: sub cacheheader {
1.258     albertel 12658:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12659:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12660:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12661:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12662:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12663:     return $output;
1.7       albertel 12664: }
                   12665: 
1.112     bowersj2 12666: =pod
                   12667: 
1.648     raeburn  12668: =item * &no_cache($r) 
1.112     bowersj2 12669: 
                   12670: specifies header code to not have cache
                   12671: 
                   12672: =cut
                   12673: 
1.9       albertel 12674: sub no_cache {
1.216     albertel 12675:     my ($r) = @_;
                   12676:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12677: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12678:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12679:     $r->no_cache(1);
                   12680:     $r->header_out("Expires" => $date);
                   12681:     $r->header_out("Pragma" => "no-cache");
1.123     www      12682: }
                   12683: 
                   12684: sub content_type {
1.181     albertel 12685:     my ($r,$type,$charset) = @_;
1.299     foxr     12686:     if ($r) {
                   12687: 	#  Note that printout.pl calls this with undef for $r.
                   12688: 	&no_cache($r);
                   12689:     }
1.258     albertel 12690:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12691:     unless ($charset) {
                   12692: 	$charset=&Apache::lonlocal::current_encoding;
                   12693:     }
                   12694:     if ($charset) { $type.='; charset='.$charset; }
                   12695:     if ($r) {
                   12696: 	$r->content_type($type);
                   12697:     } else {
                   12698: 	print("Content-type: $type\n\n");
                   12699:     }
1.9       albertel 12700: }
1.25      albertel 12701: 
1.112     bowersj2 12702: =pod
                   12703: 
1.648     raeburn  12704: =item * &add_to_env($name,$value) 
1.112     bowersj2 12705: 
1.258     albertel 12706: adds $name to the %env hash with value
1.112     bowersj2 12707: $value, if $name already exists, the entry is converted to an array
                   12708: reference and $value is added to the array.
                   12709: 
                   12710: =cut
                   12711: 
1.25      albertel 12712: sub add_to_env {
                   12713:   my ($name,$value)=@_;
1.258     albertel 12714:   if (defined($env{$name})) {
                   12715:     if (ref($env{$name})) {
1.25      albertel 12716:       #already have multiple values
1.258     albertel 12717:       push(@{ $env{$name} },$value);
1.25      albertel 12718:     } else {
                   12719:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12720:       my $first=$env{$name};
                   12721:       undef($env{$name});
                   12722:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12723:     }
                   12724:   } else {
1.258     albertel 12725:     $env{$name}=$value;
1.25      albertel 12726:   }
1.31      albertel 12727: }
1.149     albertel 12728: 
                   12729: =pod
                   12730: 
1.648     raeburn  12731: =item * &get_env_multiple($name) 
1.149     albertel 12732: 
1.258     albertel 12733: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12734: values may be defined and end up as an array ref.
                   12735: 
                   12736: returns an array of values
                   12737: 
                   12738: =cut
                   12739: 
                   12740: sub get_env_multiple {
                   12741:     my ($name) = @_;
                   12742:     my @values;
1.258     albertel 12743:     if (defined($env{$name})) {
1.149     albertel 12744:         # exists is it an array
1.258     albertel 12745:         if (ref($env{$name})) {
                   12746:             @values=@{ $env{$name} };
1.149     albertel 12747:         } else {
1.258     albertel 12748:             $values[0]=$env{$name};
1.149     albertel 12749:         }
                   12750:     }
                   12751:     return(@values);
                   12752: }
                   12753: 
1.1249    damieng  12754: # Looks at given dependencies, and returns something depending on the context.
                   12755: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12756: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12757: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12758: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12759: # $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.
                   12760: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12761: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12762: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12763: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12764: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12765: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12766: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12767: # @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)
                   12768: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12769: sub ask_for_embedded_content {
1.1249    damieng  12770:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12771:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12772:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12773:         %currsubfile,%unused,$rem);
1.1071    raeburn  12774:     my $counter = 0;
                   12775:     my $numnew = 0;
1.987     raeburn  12776:     my $numremref = 0;
                   12777:     my $numinvalid = 0;
                   12778:     my $numpathchg = 0;
                   12779:     my $numexisting = 0;
1.1071    raeburn  12780:     my $numunused = 0;
                   12781:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12782:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12783:     my $heading = &mt('Upload embedded files');
                   12784:     my $buttontext = &mt('Upload');
                   12785: 
1.1249    damieng  12786:     # fills these variables based on the context:
                   12787:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12788:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12789:     if ($env{'request.course.id'}) {
1.1123    raeburn  12790:         if ($actionurl eq '/adm/dependencies') {
                   12791:             $navmap = Apache::lonnavmaps::navmap->new();
                   12792:         }
                   12793:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12794:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12795:     }
1.1123    raeburn  12796:     if (($actionurl eq '/adm/portfolio') || 
                   12797:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12798:         my $current_path='/';
                   12799:         if ($env{'form.currentpath'}) {
                   12800:             $current_path = $env{'form.currentpath'};
                   12801:         }
                   12802:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12803:             $udom = $cdom;
                   12804:             $uname = $cnum;
1.984     raeburn  12805:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12806:         } else {
                   12807:             $udom = $env{'user.domain'};
                   12808:             $uname = $env{'user.name'};
                   12809:             $url = '/userfiles/portfolio';
                   12810:         }
1.987     raeburn  12811:         $toplevel = $url.'/';
1.984     raeburn  12812:         $url .= $current_path;
                   12813:         $getpropath = 1;
1.987     raeburn  12814:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12815:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12816:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12817:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12818:         $toplevel = $url;
1.984     raeburn  12819:         if ($rest ne '') {
1.987     raeburn  12820:             $url .= $rest;
                   12821:         }
                   12822:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12823:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12824:             $url = $args->{'docs_url'};
                   12825:             $toplevel = $url;
1.1084    raeburn  12826:             if ($args->{'context'} eq 'paste') {
                   12827:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12828:                 ($path) = 
                   12829:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12830:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12831:                 $fileloc =~ s{^/}{};
                   12832:             }
1.1071    raeburn  12833:         }
1.1084    raeburn  12834:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12835:         if ($env{'request.course.id'} ne '') {
                   12836:             if (ref($args) eq 'HASH') {
                   12837:                 $url = $args->{'docs_url'};
                   12838:                 $title = $args->{'docs_title'};
1.1126    raeburn  12839:                 $toplevel = $url; 
                   12840:                 unless ($toplevel =~ m{^/}) {
                   12841:                     $toplevel = "/$url";
                   12842:                 }
1.1085    raeburn  12843:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12844:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12845:                     $path = $1;
                   12846:                 } else {
                   12847:                     ($path) =
                   12848:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12849:                 }
1.1195    raeburn  12850:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12851:                     $fileloc = $toplevel;
                   12852:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12853:                     my ($udom,$uname,$fname) =
                   12854:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12855:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12856:                 } else {
                   12857:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12858:                 }
1.1071    raeburn  12859:                 $fileloc =~ s{^/}{};
                   12860:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12861:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12862:             }
1.987     raeburn  12863:         }
1.1123    raeburn  12864:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12865:         $udom = $cdom;
                   12866:         $uname = $cnum;
                   12867:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12868:         $toplevel = $url;
                   12869:         $path = $url;
                   12870:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12871:         $fileloc =~ s{^/}{};
1.987     raeburn  12872:     }
1.1249    damieng  12873:     
                   12874:     # parses the dependency paths to get some info
                   12875:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12876:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12877:     # (will be completed later)
                   12878:     # $mapping:
                   12879:     #   for external URLs: external URL -> external URL
                   12880:     #   for relative paths: clean path -> original path
                   12881:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12882:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12883:     foreach my $file (keys(%{$allfiles})) {
                   12884:         my $embed_file;
                   12885:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12886:             $embed_file = $1;
                   12887:         } else {
                   12888:             $embed_file = $file;
                   12889:         }
1.1158    raeburn  12890:         my ($absolutepath,$cleaned_file);
                   12891:         if ($embed_file =~ m{^\w+://}) {
                   12892:             $cleaned_file = $embed_file;
1.1147    raeburn  12893:             $newfiles{$cleaned_file} = 1;
                   12894:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12895:         } else {
1.1158    raeburn  12896:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12897:             if ($embed_file =~ m{^/}) {
                   12898:                 $absolutepath = $embed_file;
                   12899:             }
1.1147    raeburn  12900:             if ($cleaned_file =~ m{/}) {
                   12901:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12902:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12903:                 my $item = $fname;
                   12904:                 if ($path ne '') {
                   12905:                     $item = $path.'/'.$fname;
                   12906:                     $subdependencies{$path}{$fname} = 1;
                   12907:                 } else {
                   12908:                     $dependencies{$item} = 1;
                   12909:                 }
                   12910:                 if ($absolutepath) {
                   12911:                     $mapping{$item} = $absolutepath;
                   12912:                 } else {
                   12913:                     $mapping{$item} = $embed_file;
                   12914:                 }
                   12915:             } else {
                   12916:                 $dependencies{$embed_file} = 1;
                   12917:                 if ($absolutepath) {
1.1147    raeburn  12918:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12919:                 } else {
1.1147    raeburn  12920:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12921:                 }
                   12922:             }
1.984     raeburn  12923:         }
                   12924:     }
1.1249    damieng  12925:     
                   12926:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12927:     # and lists
                   12928:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12929:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12930:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12931:     #                                    the path had to be cleaned up
                   12932:     # $existing: hash clean path -> 1 if the file exists
                   12933:     # $numexisting: number of keys in $existing
                   12934:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12935:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12936:     #                                      dependency subdirectories that are
                   12937:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12938:     my $dirptr = 16384;
1.984     raeburn  12939:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12940:         $currsubfile{$path} = {};
1.1123    raeburn  12941:         if (($actionurl eq '/adm/portfolio') || 
                   12942:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12943:             my ($sublistref,$listerror) =
                   12944:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12945:             if (ref($sublistref) eq 'ARRAY') {
                   12946:                 foreach my $line (@{$sublistref}) {
                   12947:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12948:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12949:                 }
1.984     raeburn  12950:             }
1.987     raeburn  12951:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12952:             if (opendir(my $dir,$url.'/'.$path)) {
                   12953:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12954:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12955:             }
1.1084    raeburn  12956:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12957:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12958:                   ($args->{'context'} eq 'paste')) ||
                   12959:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12960:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12961:                 my $dir;
                   12962:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12963:                     $dir = $fileloc;
                   12964:                 } else {
                   12965:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12966:                 }
1.1071    raeburn  12967:                 if ($dir ne '') {
                   12968:                     my ($sublistref,$listerror) =
                   12969:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12970:                     if (ref($sublistref) eq 'ARRAY') {
                   12971:                         foreach my $line (@{$sublistref}) {
                   12972:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12973:                                 undef,$mtime)=split(/\&/,$line,12);
                   12974:                             unless (($testdir&$dirptr) ||
                   12975:                                     ($file_name =~ /^\.\.?$/)) {
                   12976:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12977:                             }
                   12978:                         }
                   12979:                     }
                   12980:                 }
1.984     raeburn  12981:             }
                   12982:         }
                   12983:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12984:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12985:                 my $item = $path.'/'.$file;
                   12986:                 unless ($mapping{$item} eq $item) {
                   12987:                     $pathchanges{$item} = 1;
                   12988:                 }
                   12989:                 $existing{$item} = 1;
                   12990:                 $numexisting ++;
                   12991:             } else {
                   12992:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12993:             }
                   12994:         }
1.1071    raeburn  12995:         if ($actionurl eq '/adm/dependencies') {
                   12996:             foreach my $path (keys(%currsubfile)) {
                   12997:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12998:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12999:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  13000:                              next if (($rem ne '') &&
                   13001:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   13002:                                        (ref($navmap) &&
                   13003:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   13004:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   13005:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  13006:                              $unused{$path.'/'.$file} = 1; 
                   13007:                          }
                   13008:                     }
                   13009:                 }
                   13010:             }
                   13011:         }
1.984     raeburn  13012:     }
1.1249    damieng  13013:     
                   13014:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   13015:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  13016:     my %currfile;
1.1123    raeburn  13017:     if (($actionurl eq '/adm/portfolio') ||
                   13018:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  13019:         my ($dirlistref,$listerror) =
                   13020:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   13021:         if (ref($dirlistref) eq 'ARRAY') {
                   13022:             foreach my $line (@{$dirlistref}) {
                   13023:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   13024:                 $currfile{$file_name} = 1;
                   13025:             }
1.984     raeburn  13026:         }
1.987     raeburn  13027:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  13028:         if (opendir(my $dir,$url)) {
1.987     raeburn  13029:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  13030:             map {$currfile{$_} = 1;} @dir_list;
                   13031:         }
1.1084    raeburn  13032:     } elsif (($actionurl eq '/adm/dependencies') ||
                   13033:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  13034:               ($args->{'context'} eq 'paste')) ||
                   13035:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  13036:         if ($env{'request.course.id'} ne '') {
                   13037:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   13038:             if ($dir ne '') {
                   13039:                 my ($dirlistref,$listerror) =
                   13040:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   13041:                 if (ref($dirlistref) eq 'ARRAY') {
                   13042:                     foreach my $line (@{$dirlistref}) {
                   13043:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   13044:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   13045:                         unless (($testdir&$dirptr) ||
                   13046:                                 ($file_name =~ /^\.\.?$/)) {
                   13047:                             $currfile{$file_name} = [$size,$mtime];
                   13048:                         }
                   13049:                     }
                   13050:                 }
                   13051:             }
                   13052:         }
1.984     raeburn  13053:     }
1.1249    damieng  13054:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   13055:     # are not in subdirectories, using $currfile
1.984     raeburn  13056:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  13057:         if (exists($currfile{$file})) {
1.987     raeburn  13058:             unless ($mapping{$file} eq $file) {
                   13059:                 $pathchanges{$file} = 1;
                   13060:             }
                   13061:             $existing{$file} = 1;
                   13062:             $numexisting ++;
                   13063:         } else {
1.984     raeburn  13064:             $newfiles{$file} = 1;
                   13065:         }
                   13066:     }
1.1071    raeburn  13067:     foreach my $file (keys(%currfile)) {
                   13068:         unless (($file eq $filename) ||
                   13069:                 ($file eq $filename.'.bak') ||
                   13070:                 ($dependencies{$file})) {
1.1085    raeburn  13071:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  13072:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   13073:                     next if (($rem ne '') &&
                   13074:                              (($env{"httpref.$rem".$file} ne '') ||
                   13075:                               (ref($navmap) &&
                   13076:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   13077:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   13078:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   13079:                 }
1.1085    raeburn  13080:             }
1.1071    raeburn  13081:             $unused{$file} = 1;
                   13082:         }
                   13083:     }
1.1249    damieng  13084:     
                   13085:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  13086:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   13087:         ($args->{'context'} eq 'paste')) {
                   13088:         $counter = scalar(keys(%existing));
                   13089:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  13090:         return ($output,$counter,$numpathchg,\%existing);
                   13091:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   13092:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   13093:         $counter = scalar(keys(%existing));
                   13094:         $numpathchg = scalar(keys(%pathchanges));
                   13095:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  13096:     }
1.1249    damieng  13097:     
                   13098:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   13099:     
                   13100:     # $upload_output: missing dependencies (with upload form)
                   13101:     # $modify_output: uploaded dependencies (in use)
                   13102:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  13103:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  13104:         if ($actionurl eq '/adm/dependencies') {
                   13105:             next if ($embed_file =~ m{^\w+://});
                   13106:         }
1.660     raeburn  13107:         $upload_output .= &start_data_table_row().
1.1123    raeburn  13108:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  13109:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  13110:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  13111:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   13112:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  13113:         }
1.1123    raeburn  13114:         $upload_output .= '</td>';
1.1071    raeburn  13115:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  13116:             $upload_output.='<td align="right">'.
                   13117:                             '<span class="LC_info LC_fontsize_medium">'.
                   13118:                             &mt("URL points to web address").'</span>';
1.987     raeburn  13119:             $numremref++;
1.660     raeburn  13120:         } elsif ($args->{'error_on_invalid_names'}
                   13121:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  13122:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   13123:                             &mt('Invalid characters').'</span>';
1.987     raeburn  13124:             $numinvalid++;
1.660     raeburn  13125:         } else {
1.1123    raeburn  13126:             $upload_output .= '<td>'.
                   13127:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  13128:                                                      $embed_file,\%mapping,
1.1071    raeburn  13129:                                                      $allfiles,$codebase,'upload');
                   13130:             $counter ++;
                   13131:             $numnew ++;
1.987     raeburn  13132:         }
                   13133:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   13134:     }
                   13135:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  13136:         if ($actionurl eq '/adm/dependencies') {
                   13137:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   13138:             $modify_output .= &start_data_table_row().
                   13139:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   13140:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   13141:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   13142:                               '<td>'.$size.'</td>'.
                   13143:                               '<td>'.$mtime.'</td>'.
                   13144:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   13145:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   13146:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   13147:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   13148:                               &embedded_file_element('upload_embedded',$counter,
                   13149:                                                      $embed_file,\%mapping,
                   13150:                                                      $allfiles,$codebase,'modify').
                   13151:                               '</div></td>'.
                   13152:                               &end_data_table_row()."\n";
                   13153:             $counter ++;
                   13154:         } else {
                   13155:             $upload_output .= &start_data_table_row().
1.1123    raeburn  13156:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   13157:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   13158:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  13159:                               &Apache::loncommon::end_data_table_row()."\n";
                   13160:         }
                   13161:     }
                   13162:     my $delidx = $counter;
                   13163:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   13164:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   13165:         $delete_output .= &start_data_table_row().
                   13166:                           '<td><img src="'.&icon($oldfile).'" />'.
                   13167:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   13168:                           '<td>'.$size.'</td>'.
                   13169:                           '<td>'.$mtime.'</td>'.
                   13170:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   13171:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   13172:                           &embedded_file_element('upload_embedded',$delidx,
                   13173:                                                  $oldfile,\%mapping,$allfiles,
                   13174:                                                  $codebase,'delete').'</td>'.
                   13175:                           &end_data_table_row()."\n"; 
                   13176:         $numunused ++;
                   13177:         $delidx ++;
1.987     raeburn  13178:     }
                   13179:     if ($upload_output) {
                   13180:         $upload_output = &start_data_table().
                   13181:                          $upload_output.
                   13182:                          &end_data_table()."\n";
                   13183:     }
1.1071    raeburn  13184:     if ($modify_output) {
                   13185:         $modify_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('Upload replacement?').'</th>'.
                   13191:                          &end_data_table_header_row().
                   13192:                          $modify_output.
                   13193:                          &end_data_table()."\n";
                   13194:     }
                   13195:     if ($delete_output) {
                   13196:         $delete_output = &start_data_table().
                   13197:                          &start_data_table_header_row().
                   13198:                          '<th>'.&mt('File').'</th>'.
                   13199:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13200:                          '<th>'.&mt('Modified').'</th>'.
                   13201:                          '<th>'.&mt('Delete?').'</th>'.
                   13202:                          &end_data_table_header_row().
                   13203:                          $delete_output.
                   13204:                          &end_data_table()."\n";
                   13205:     }
1.987     raeburn  13206:     my $applies = 0;
                   13207:     if ($numremref) {
                   13208:         $applies ++;
                   13209:     }
                   13210:     if ($numinvalid) {
                   13211:         $applies ++;
                   13212:     }
                   13213:     if ($numexisting) {
                   13214:         $applies ++;
                   13215:     }
1.1071    raeburn  13216:     if ($counter || $numunused) {
1.987     raeburn  13217:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   13218:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  13219:                   $state.'<h3>'.$heading.'</h3>'; 
                   13220:         if ($actionurl eq '/adm/dependencies') {
                   13221:             if ($numnew) {
                   13222:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   13223:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   13224:                            $upload_output.'<br />'."\n";
                   13225:             }
                   13226:             if ($numexisting) {
                   13227:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   13228:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   13229:                            $modify_output.'<br />'."\n";
                   13230:                            $buttontext = &mt('Save changes');
                   13231:             }
                   13232:             if ($numunused) {
                   13233:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   13234:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   13235:                            $delete_output.'<br />'."\n";
                   13236:                            $buttontext = &mt('Save changes');
                   13237:             }
                   13238:         } else {
                   13239:             $output .= $upload_output.'<br />'."\n";
                   13240:         }
                   13241:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   13242:                    $counter.'" />'."\n";
                   13243:         if ($actionurl eq '/adm/dependencies') { 
                   13244:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   13245:                        $numnew.'" />'."\n";
                   13246:         } elsif ($actionurl eq '') {
1.987     raeburn  13247:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   13248:         }
                   13249:     } elsif ($applies) {
                   13250:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   13251:         if ($applies > 1) {
                   13252:             $output .=  
1.1123    raeburn  13253:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  13254:             if ($numremref) {
                   13255:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   13256:             }
                   13257:             if ($numinvalid) {
                   13258:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   13259:             }
                   13260:             if ($numexisting) {
                   13261:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   13262:             }
                   13263:             $output .= '</ul><br />';
                   13264:         } elsif ($numremref) {
                   13265:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   13266:         } elsif ($numinvalid) {
                   13267:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   13268:         } elsif ($numexisting) {
                   13269:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   13270:         }
                   13271:         $output .= $upload_output.'<br />';
                   13272:     }
                   13273:     my ($pathchange_output,$chgcount);
1.1071    raeburn  13274:     $chgcount = $counter;
1.987     raeburn  13275:     if (keys(%pathchanges) > 0) {
                   13276:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  13277:             if ($counter) {
1.987     raeburn  13278:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   13279:                                                   $embed_file,\%mapping,
1.1071    raeburn  13280:                                                   $allfiles,$codebase,'change');
1.987     raeburn  13281:             } else {
                   13282:                 $pathchange_output .= 
                   13283:                     &start_data_table_row().
                   13284:                     '<td><input type ="checkbox" name="namechange" value="'.
                   13285:                     $chgcount.'" checked="checked" /></td>'.
                   13286:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   13287:                     '<td>'.$embed_file.
                   13288:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  13289:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  13290:                     '</td>'.&end_data_table_row();
1.660     raeburn  13291:             }
1.987     raeburn  13292:             $numpathchg ++;
                   13293:             $chgcount ++;
1.660     raeburn  13294:         }
                   13295:     }
1.1127    raeburn  13296:     if (($counter) || ($numunused)) {
1.987     raeburn  13297:         if ($numpathchg) {
                   13298:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   13299:                        $numpathchg.'" />'."\n";
                   13300:         }
                   13301:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   13302:             ($actionurl eq '/adm/imsimport')) {
                   13303:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   13304:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   13305:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  13306:         } elsif ($actionurl eq '/adm/dependencies') {
                   13307:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  13308:         }
1.1123    raeburn  13309:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  13310:     } elsif ($numpathchg) {
                   13311:         my %pathchange = ();
                   13312:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   13313:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13314:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  13315:         }
1.987     raeburn  13316:     }
1.1071    raeburn  13317:     return ($output,$counter,$numpathchg);
1.987     raeburn  13318: }
                   13319: 
1.1147    raeburn  13320: =pod
                   13321: 
                   13322: =item * clean_path($name)
                   13323: 
                   13324: Performs clean-up of directories, subdirectories and filename in an
                   13325: embedded object, referenced in an HTML file which is being uploaded
                   13326: to a course or portfolio, where 
                   13327: "Upload embedded images/multimedia files if HTML file" checkbox was
                   13328: checked.
                   13329: 
                   13330: Clean-up is similar to replacements in lonnet::clean_filename()
                   13331: except each / between sub-directory and next level is preserved.
                   13332: 
                   13333: =cut
                   13334: 
                   13335: sub clean_path {
                   13336:     my ($embed_file) = @_;
                   13337:     $embed_file =~s{^/+}{};
                   13338:     my @contents;
                   13339:     if ($embed_file =~ m{/}) {
                   13340:         @contents = split(/\//,$embed_file);
                   13341:     } else {
                   13342:         @contents = ($embed_file);
                   13343:     }
                   13344:     my $lastidx = scalar(@contents)-1;
                   13345:     for (my $i=0; $i<=$lastidx; $i++) { 
                   13346:         $contents[$i]=~s{\\}{/}g;
                   13347:         $contents[$i]=~s/\s+/\_/g;
                   13348:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   13349:         if ($i == $lastidx) {
                   13350:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   13351:         }
                   13352:     }
                   13353:     if ($lastidx > 0) {
                   13354:         return join('/',@contents);
                   13355:     } else {
                   13356:         return $contents[0];
                   13357:     }
                   13358: }
                   13359: 
1.987     raeburn  13360: sub embedded_file_element {
1.1071    raeburn  13361:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  13362:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   13363:                    (ref($codebase) eq 'HASH'));
                   13364:     my $output;
1.1071    raeburn  13365:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  13366:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   13367:     }
                   13368:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   13369:                &escape($embed_file).'" />';
                   13370:     unless (($context eq 'upload_embedded') && 
                   13371:             ($mapping->{$embed_file} eq $embed_file)) {
                   13372:         $output .='
                   13373:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   13374:     }
                   13375:     my $attrib;
                   13376:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   13377:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   13378:     }
                   13379:     $output .=
                   13380:         "\n\t\t".
                   13381:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   13382:         $attrib.'" />';
                   13383:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   13384:         $output .=
                   13385:             "\n\t\t".
                   13386:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   13387:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  13388:     }
1.987     raeburn  13389:     return $output;
1.660     raeburn  13390: }
                   13391: 
1.1071    raeburn  13392: sub get_dependency_details {
                   13393:     my ($currfile,$currsubfile,$embed_file) = @_;
                   13394:     my ($size,$mtime,$showsize,$showmtime);
                   13395:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   13396:         if ($embed_file =~ m{/}) {
                   13397:             my ($path,$fname) = split(/\//,$embed_file);
                   13398:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   13399:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   13400:             }
                   13401:         } else {
                   13402:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   13403:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   13404:             }
                   13405:         }
                   13406:         $showsize = $size/1024.0;
                   13407:         $showsize = sprintf("%.1f",$showsize);
                   13408:         if ($mtime > 0) {
                   13409:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   13410:         }
                   13411:     }
                   13412:     return ($showsize,$showmtime);
                   13413: }
                   13414: 
                   13415: sub ask_embedded_js {
                   13416:     return <<"END";
                   13417: <script type="text/javascript"">
                   13418: // <![CDATA[
                   13419: function toggleBrowse(counter) {
                   13420:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   13421:     var fileid = document.getElementById('embedded_item_'+counter);
                   13422:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   13423:     if (chkboxid.checked == true) {
                   13424:         uploaddivid.style.display='block';
                   13425:     } else {
                   13426:         uploaddivid.style.display='none';
                   13427:         fileid.value = '';
                   13428:     }
                   13429: }
                   13430: // ]]>
                   13431: </script>
                   13432: 
                   13433: END
                   13434: }
                   13435: 
1.661     raeburn  13436: sub upload_embedded {
                   13437:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  13438:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   13439:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  13440:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   13441:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   13442:         my $orig_uploaded_filename =
                   13443:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  13444:         foreach my $type ('orig','ref','attrib','codebase') {
                   13445:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   13446:                 $env{'form.embedded_'.$type.'_'.$i} =
                   13447:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   13448:             }
                   13449:         }
1.661     raeburn  13450:         my ($path,$fname) =
                   13451:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   13452:         # no path, whole string is fname
                   13453:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   13454:         $fname = &Apache::lonnet::clean_filename($fname);
                   13455:         # See if there is anything left
                   13456:         next if ($fname eq '');
                   13457: 
                   13458:         # Check if file already exists as a file or directory.
                   13459:         my ($state,$msg);
                   13460:         if ($context eq 'portfolio') {
                   13461:             my $port_path = $dirpath;
                   13462:             if ($group ne '') {
                   13463:                 $port_path = "groups/$group/$port_path";
                   13464:             }
1.987     raeburn  13465:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   13466:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  13467:                                               $dir_root,$port_path,$disk_quota,
                   13468:                                               $current_disk_usage,$uname,$udom);
                   13469:             if ($state eq 'will_exceed_quota'
1.984     raeburn  13470:                 || $state eq 'file_locked') {
1.661     raeburn  13471:                 $output .= $msg;
                   13472:                 next;
                   13473:             }
                   13474:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   13475:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   13476:             if ($state eq 'exists') {
                   13477:                 $output .= $msg;
                   13478:                 next;
                   13479:             }
                   13480:         }
                   13481:         # Check if extension is valid
                   13482:         if (($fname =~ /\.(\w+)$/) &&
                   13483:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   13484:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   13485:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  13486:             next;
                   13487:         } elsif (($fname =~ /\.(\w+)$/) &&
                   13488:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  13489:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  13490:             next;
                   13491:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   13492:             $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  13493:             next;
                   13494:         }
                   13495:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  13496:         my $subdir = $path;
                   13497:         $subdir =~ s{/+$}{};
1.661     raeburn  13498:         if ($context eq 'portfolio') {
1.984     raeburn  13499:             my $result;
                   13500:             if ($state eq 'existingfile') {
                   13501:                 $result=
                   13502:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  13503:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  13504:             } else {
1.984     raeburn  13505:                 $result=
                   13506:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  13507:                                                     $dirpath.
1.1123    raeburn  13508:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  13509:                 if ($result !~ m|^/uploaded/|) {
                   13510:                     $output .= '<span class="LC_error">'
                   13511:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13512:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13513:                                .'</span><br />';
                   13514:                     next;
                   13515:                 } else {
1.987     raeburn  13516:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13517:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  13518:                 }
1.661     raeburn  13519:             }
1.1123    raeburn  13520:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  13521:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   13522:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  13523:             my $result =
1.1126    raeburn  13524:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  13525:             if ($result !~ m|^/uploaded/|) {
                   13526:                 $output .= '<span class="LC_error">'
                   13527:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13528:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13529:                            .'</span><br />';
                   13530:                     next;
                   13531:             } else {
                   13532:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13533:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  13534:                 if ($context eq 'syllabus') {
                   13535:                     &Apache::lonnet::make_public_indefinitely($result);
                   13536:                 }
1.987     raeburn  13537:             }
1.661     raeburn  13538:         } else {
                   13539: # Save the file
                   13540:             my $target = $env{'form.embedded_item_'.$i};
                   13541:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   13542:             my $dest = $fullpath.$fname;
                   13543:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  13544:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  13545:             my $count;
                   13546:             my $filepath = $dir_root;
1.1027    raeburn  13547:             foreach my $subdir (@parts) {
                   13548:                 $filepath .= "/$subdir";
                   13549:                 if (!-e $filepath) {
1.661     raeburn  13550:                     mkdir($filepath,0770);
                   13551:                 }
                   13552:             }
                   13553:             my $fh;
                   13554:             if (!open($fh,'>'.$dest)) {
                   13555:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   13556:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  13557:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   13558:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13559:                            '</span><br />';
                   13560:             } else {
                   13561:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   13562:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   13563:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  13564:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   13565:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13566:                               '</span><br />';
                   13567:                 } else {
1.987     raeburn  13568:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13569:                                $url.'</span>').'<br />';
                   13570:                     unless ($context eq 'testbank') {
                   13571:                         $footer .= &mt('View embedded file: [_1]',
                   13572:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   13573:                     }
                   13574:                 }
                   13575:                 close($fh);
                   13576:             }
                   13577:         }
                   13578:         if ($env{'form.embedded_ref_'.$i}) {
                   13579:             $pathchange{$i} = 1;
                   13580:         }
                   13581:     }
                   13582:     if ($output) {
                   13583:         $output = '<p>'.$output.'</p>';
                   13584:     }
                   13585:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   13586:     $returnflag = 'ok';
1.1071    raeburn  13587:     my $numpathchgs = scalar(keys(%pathchange));
                   13588:     if ($numpathchgs > 0) {
1.987     raeburn  13589:         if ($context eq 'portfolio') {
                   13590:             $output .= '<p>'.&mt('or').'</p>';
                   13591:         } elsif ($context eq 'testbank') {
1.1071    raeburn  13592:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   13593:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  13594:             $returnflag = 'modify_orightml';
                   13595:         }
                   13596:     }
1.1071    raeburn  13597:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  13598: }
                   13599: 
                   13600: sub modify_html_form {
                   13601:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   13602:     my $end = 0;
                   13603:     my $modifyform;
                   13604:     if ($context eq 'upload_embedded') {
                   13605:         return unless (ref($pathchange) eq 'HASH');
                   13606:         if ($env{'form.number_embedded_items'}) {
                   13607:             $end += $env{'form.number_embedded_items'};
                   13608:         }
                   13609:         if ($env{'form.number_pathchange_items'}) {
                   13610:             $end += $env{'form.number_pathchange_items'};
                   13611:         }
                   13612:         if ($end) {
                   13613:             for (my $i=0; $i<$end; $i++) {
                   13614:                 if ($i < $env{'form.number_embedded_items'}) {
                   13615:                     next unless($pathchange->{$i});
                   13616:                 }
                   13617:                 $modifyform .=
                   13618:                     &start_data_table_row().
                   13619:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   13620:                     'checked="checked" /></td>'.
                   13621:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   13622:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   13623:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   13624:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   13625:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   13626:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   13627:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   13628:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   13629:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   13630:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   13631:                     &end_data_table_row();
1.1071    raeburn  13632:             }
1.987     raeburn  13633:         }
                   13634:     } else {
                   13635:         $modifyform = $pathchgtable;
                   13636:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   13637:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   13638:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13639:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   13640:         }
                   13641:     }
                   13642:     if ($modifyform) {
1.1071    raeburn  13643:         if ($actionurl eq '/adm/dependencies') {
                   13644:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   13645:         }
1.987     raeburn  13646:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   13647:                '<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".
                   13648:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   13649:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   13650:                '</ol></p>'."\n".'<p>'.
                   13651:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   13652:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   13653:                &start_data_table()."\n".
                   13654:                &start_data_table_header_row().
                   13655:                '<th>'.&mt('Change?').'</th>'.
                   13656:                '<th>'.&mt('Current reference').'</th>'.
                   13657:                '<th>'.&mt('Required reference').'</th>'.
                   13658:                &end_data_table_header_row()."\n".
                   13659:                $modifyform.
                   13660:                &end_data_table().'<br />'."\n".$hiddenstate.
                   13661:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   13662:                '</form>'."\n";
                   13663:     }
                   13664:     return;
                   13665: }
                   13666: 
                   13667: sub modify_html_refs {
1.1123    raeburn  13668:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  13669:     my $container;
                   13670:     if ($context eq 'portfolio') {
                   13671:         $container = $env{'form.container'};
                   13672:     } elsif ($context eq 'coursedoc') {
                   13673:         $container = $env{'form.primaryurl'};
1.1071    raeburn  13674:     } elsif ($context eq 'manage_dependencies') {
                   13675:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   13676:         $container = "/$container";
1.1123    raeburn  13677:     } elsif ($context eq 'syllabus') {
                   13678:         $container = $url;
1.987     raeburn  13679:     } else {
1.1027    raeburn  13680:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  13681:     }
                   13682:     my (%allfiles,%codebase,$output,$content);
                   13683:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  13684:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  13685:         if (wantarray) {
                   13686:             return ('',0,0); 
                   13687:         } else {
                   13688:             return;
                   13689:         }
                   13690:     }
                   13691:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13692:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  13693:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   13694:             if (wantarray) {
                   13695:                 return ('',0,0);
                   13696:             } else {
                   13697:                 return;
                   13698:             }
                   13699:         } 
1.987     raeburn  13700:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  13701:         if ($content eq '-1') {
                   13702:             if (wantarray) {
                   13703:                 return ('',0,0);
                   13704:             } else {
                   13705:                 return;
                   13706:             }
                   13707:         }
1.987     raeburn  13708:     } else {
1.1071    raeburn  13709:         unless ($container =~ /^\Q$dir_root\E/) {
                   13710:             if (wantarray) {
                   13711:                 return ('',0,0);
                   13712:             } else {
                   13713:                 return;
                   13714:             }
                   13715:         } 
1.1317    raeburn  13716:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13717:             $content = join('', <$fh>);
                   13718:             close($fh);
                   13719:         } else {
1.1071    raeburn  13720:             if (wantarray) {
                   13721:                 return ('',0,0);
                   13722:             } else {
                   13723:                 return;
                   13724:             }
1.987     raeburn  13725:         }
                   13726:     }
                   13727:     my ($count,$codebasecount) = (0,0);
                   13728:     my $mm = new File::MMagic;
                   13729:     my $mime_type = $mm->checktype_contents($content);
                   13730:     if ($mime_type eq 'text/html') {
                   13731:         my $parse_result = 
                   13732:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13733:                                                     \%codebase,\$content);
                   13734:         if ($parse_result eq 'ok') {
                   13735:             foreach my $i (@changes) {
                   13736:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13737:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13738:                 if ($allfiles{$ref}) {
                   13739:                     my $newname =  $orig;
                   13740:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13741:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13742:                     if ($attrib_regexp =~ /:/) {
                   13743:                         $attrib_regexp =~ s/\:/|/g;
                   13744:                     }
                   13745:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13746:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13747:                         $count += $numchg;
1.1123    raeburn  13748:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13749:                         delete($allfiles{$ref});
1.987     raeburn  13750:                     }
                   13751:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13752:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13753:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13754:                         $codebasecount ++;
                   13755:                     }
                   13756:                 }
                   13757:             }
1.1123    raeburn  13758:             my $skiprewrites;
1.987     raeburn  13759:             if ($count || $codebasecount) {
                   13760:                 my $saveresult;
1.1071    raeburn  13761:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13762:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13763:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13764:                     if ($url eq $container) {
                   13765:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13766:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13767:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13768:                                             $fname.'</span>').'</p>';
1.987     raeburn  13769:                     } else {
                   13770:                          $output = '<p class="LC_error">'.
                   13771:                                    &mt('Error: update failed for: [_1].',
                   13772:                                    '<span class="LC_filename">'.
                   13773:                                    $container.'</span>').'</p>';
                   13774:                     }
1.1123    raeburn  13775:                     if ($context eq 'syllabus') {
                   13776:                         unless ($saveresult eq 'ok') {
                   13777:                             $skiprewrites = 1;
                   13778:                         }
                   13779:                     }
1.987     raeburn  13780:                 } else {
1.1317    raeburn  13781:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13782:                         print $fh $content;
                   13783:                         close($fh);
                   13784:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13785:                                   $count,'<span class="LC_filename">'.
                   13786:                                   $container.'</span>').'</p>';
1.661     raeburn  13787:                     } else {
1.987     raeburn  13788:                          $output = '<p class="LC_error">'.
                   13789:                                    &mt('Error: could not update [_1].',
                   13790:                                    '<span class="LC_filename">'.
                   13791:                                    $container.'</span>').'</p>';
1.661     raeburn  13792:                     }
                   13793:                 }
                   13794:             }
1.1123    raeburn  13795:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13796:                 my ($actionurl,$state);
                   13797:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13798:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13799:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13800:                                               \%codebase,
                   13801:                                               {'context' => 'rewrites',
                   13802:                                                'ignore_remote_references' => 1,});
                   13803:                 if (ref($mapping) eq 'HASH') {
                   13804:                     my $rewrites = 0;
                   13805:                     foreach my $key (keys(%{$mapping})) {
                   13806:                         next if ($key =~ m{^https?://});
                   13807:                         my $ref = $mapping->{$key};
                   13808:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13809:                         my $attrib;
                   13810:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13811:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13812:                         }
                   13813:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13814:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13815:                             $rewrites += $numchg;
                   13816:                         }
                   13817:                     }
                   13818:                     if ($rewrites) {
                   13819:                         my $saveresult; 
                   13820:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13821:                         if ($url eq $container) {
                   13822:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13823:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13824:                                             $count,'<span class="LC_filename">'.
                   13825:                                             $fname.'</span>').'</p>';
                   13826:                         } else {
                   13827:                             $output .= '<p class="LC_error">'.
                   13828:                                        &mt('Error: could not update links in [_1].',
                   13829:                                        '<span class="LC_filename">'.
                   13830:                                        $container.'</span>').'</p>';
                   13831: 
                   13832:                         }
                   13833:                     }
                   13834:                 }
                   13835:             }
1.987     raeburn  13836:         } else {
                   13837:             &logthis('Failed to parse '.$container.
                   13838:                      ' to modify references: '.$parse_result);
1.661     raeburn  13839:         }
                   13840:     }
1.1071    raeburn  13841:     if (wantarray) {
                   13842:         return ($output,$count,$codebasecount);
                   13843:     } else {
                   13844:         return $output;
                   13845:     }
1.661     raeburn  13846: }
                   13847: 
                   13848: sub check_for_existing {
                   13849:     my ($path,$fname,$element) = @_;
                   13850:     my ($state,$msg);
                   13851:     if (-d $path.'/'.$fname) {
                   13852:         $state = 'exists';
                   13853:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13854:     } elsif (-e $path.'/'.$fname) {
                   13855:         $state = 'exists';
                   13856:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13857:     }
                   13858:     if ($state eq 'exists') {
                   13859:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13860:     }
                   13861:     return ($state,$msg);
                   13862: }
                   13863: 
                   13864: sub check_for_upload {
                   13865:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13866:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13867:     my $filesize = length($env{'form.'.$element});
                   13868:     if (!$filesize) {
                   13869:         my $msg = '<span class="LC_error">'.
                   13870:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13871:                       '<span class="LC_filename">'.$fname.'</span>',
                   13872:                       $filesize).'<br />'.
1.1007    raeburn  13873:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13874:                   '</span>';
                   13875:         return ('zero_bytes',$msg);
                   13876:     }
                   13877:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13878:     my $getpropath = 1;
1.1021    raeburn  13879:     my ($dirlistref,$listerror) =
                   13880:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13881:     my $found_file = 0;
                   13882:     my $locked_file = 0;
1.991     raeburn  13883:     my @lockers;
                   13884:     my $navmap;
                   13885:     if ($env{'request.course.id'}) {
                   13886:         $navmap = Apache::lonnavmaps::navmap->new();
                   13887:     }
1.1021    raeburn  13888:     if (ref($dirlistref) eq 'ARRAY') {
                   13889:         foreach my $line (@{$dirlistref}) {
                   13890:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13891:             if ($file_name eq $fname){
                   13892:                 $file_name = $path.$file_name;
                   13893:                 if ($group ne '') {
                   13894:                     $file_name = $group.$file_name;
                   13895:                 }
                   13896:                 $found_file = 1;
                   13897:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13898:                     foreach my $lock (@lockers) {
                   13899:                         if (ref($lock) eq 'ARRAY') {
                   13900:                             my ($symb,$crsid) = @{$lock};
                   13901:                             if ($crsid eq $env{'request.course.id'}) {
                   13902:                                 if (ref($navmap)) {
                   13903:                                     my $res = $navmap->getBySymb($symb);
                   13904:                                     foreach my $part (@{$res->parts()}) { 
                   13905:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13906:                                         unless (($slot_status == $res->RESERVED) ||
                   13907:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13908:                                             $locked_file = 1;
                   13909:                                         }
1.991     raeburn  13910:                                     }
1.1021    raeburn  13911:                                 } else {
                   13912:                                     $locked_file = 1;
1.991     raeburn  13913:                                 }
                   13914:                             } else {
                   13915:                                 $locked_file = 1;
                   13916:                             }
                   13917:                         }
1.1021    raeburn  13918:                    }
                   13919:                 } else {
                   13920:                     my @info = split(/\&/,$rest);
                   13921:                     my $currsize = $info[6]/1000;
                   13922:                     if ($currsize < $filesize) {
                   13923:                         my $extra = $filesize - $currsize;
                   13924:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13925:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13926:                                       &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   13927:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13928:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13929:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13930:                             return ('will_exceed_quota',$msg);
                   13931:                         }
1.984     raeburn  13932:                     }
                   13933:                 }
1.661     raeburn  13934:             }
                   13935:         }
                   13936:     }
                   13937:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13938:         my $msg = '<p class="LC_warning">'.
                   13939:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13940:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13941:         return ('will_exceed_quota',$msg);
                   13942:     } elsif ($found_file) {
                   13943:         if ($locked_file) {
1.1179    bisitz   13944:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13945:             $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   13946:             $msg .= '</p>';
1.661     raeburn  13947:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13948:             return ('file_locked',$msg);
                   13949:         } else {
1.1179    bisitz   13950:             my $msg = '<p class="LC_error">';
1.984     raeburn  13951:             $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   13952:             $msg .= '</p>';
1.984     raeburn  13953:             return ('existingfile',$msg);
1.661     raeburn  13954:         }
                   13955:     }
                   13956: }
                   13957: 
1.987     raeburn  13958: sub check_for_traversal {
                   13959:     my ($path,$url,$toplevel) = @_;
                   13960:     my @parts=split(/\//,$path);
                   13961:     my $cleanpath;
                   13962:     my $fullpath = $url;
                   13963:     for (my $i=0;$i<@parts;$i++) {
                   13964:         next if ($parts[$i] eq '.');
                   13965:         if ($parts[$i] eq '..') {
                   13966:             $fullpath =~ s{([^/]+/)$}{};
                   13967:         } else {
                   13968:             $fullpath .= $parts[$i].'/';
                   13969:         }
                   13970:     }
                   13971:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13972:         $cleanpath = $1;
                   13973:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13974:         my $curr_toprel = $1;
                   13975:         my @parts = split(/\//,$curr_toprel);
                   13976:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13977:         my @urlparts = split(/\//,$url_toprel);
                   13978:         my $doubledots;
                   13979:         my $startdiff = -1;
                   13980:         for (my $i=0; $i<@urlparts; $i++) {
                   13981:             if ($startdiff == -1) {
                   13982:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13983:                     $startdiff = $i;
                   13984:                     $doubledots .= '../';
                   13985:                 }
                   13986:             } else {
                   13987:                 $doubledots .= '../';
                   13988:             }
                   13989:         }
                   13990:         if ($startdiff > -1) {
                   13991:             $cleanpath = $doubledots;
                   13992:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13993:                 $cleanpath .= $parts[$i].'/';
                   13994:             }
                   13995:         }
                   13996:     }
                   13997:     $cleanpath =~ s{(/)$}{};
                   13998:     return $cleanpath;
                   13999: }
1.31      albertel 14000: 
1.1053    raeburn  14001: sub is_archive_file {
                   14002:     my ($mimetype) = @_;
                   14003:     if (($mimetype eq 'application/octet-stream') ||
                   14004:         ($mimetype eq 'application/x-stuffit') ||
                   14005:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   14006:         return 1;
                   14007:     }
                   14008:     return;
                   14009: }
                   14010: 
                   14011: sub decompress_form {
1.1065    raeburn  14012:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  14013:     my %lt = &Apache::lonlocal::texthash (
                   14014:         this => 'This file is an archive file.',
1.1067    raeburn  14015:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  14016:         itsc => 'Its contents are as follows:',
1.1053    raeburn  14017:         youm => 'You may wish to extract its contents.',
                   14018:         extr => 'Extract contents',
1.1067    raeburn  14019:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   14020:         proa => 'Process automatically?',
1.1053    raeburn  14021:         yes  => 'Yes',
                   14022:         no   => 'No',
1.1067    raeburn  14023:         fold => 'Title for folder containing movie',
                   14024:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  14025:     );
1.1065    raeburn  14026:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  14027:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  14028:     my $info = &list_archive_contents($fileloc,\@paths);
                   14029:     if (@paths) {
                   14030:         foreach my $path (@paths) {
                   14031:             $path =~ s{^/}{};
1.1067    raeburn  14032:             if ($path =~ m{^([^/]+)/$}) {
                   14033:                 $topdir = $1;
                   14034:             }
1.1065    raeburn  14035:             if ($path =~ m{^([^/]+)/}) {
                   14036:                 $toplevel{$1} = $path;
                   14037:             } else {
                   14038:                 $toplevel{$path} = $path;
                   14039:             }
                   14040:         }
                   14041:     }
1.1067    raeburn  14042:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  14043:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  14044:                         "$topdir/media/",
                   14045:                         "$topdir/media/$topdir.mp4",
                   14046:                         "$topdir/media/FirstFrame.png",
                   14047:                         "$topdir/media/player.swf",
                   14048:                         "$topdir/media/swfobject.js",
                   14049:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  14050:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  14051:                          "$topdir/$topdir.mp4",
                   14052:                          "$topdir/$topdir\_config.xml",
                   14053:                          "$topdir/$topdir\_controller.swf",
                   14054:                          "$topdir/$topdir\_embed.css",
                   14055:                          "$topdir/$topdir\_First_Frame.png",
                   14056:                          "$topdir/$topdir\_player.html",
                   14057:                          "$topdir/$topdir\_Thumbnails.png",
                   14058:                          "$topdir/playerProductInstall.swf",
                   14059:                          "$topdir/scripts/",
                   14060:                          "$topdir/scripts/config_xml.js",
                   14061:                          "$topdir/scripts/handlebars.js",
                   14062:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   14063:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   14064:                          "$topdir/scripts/modernizr.js",
                   14065:                          "$topdir/scripts/player-min.js",
                   14066:                          "$topdir/scripts/swfobject.js",
                   14067:                          "$topdir/skins/",
                   14068:                          "$topdir/skins/configuration_express.xml",
                   14069:                          "$topdir/skins/express_show/",
                   14070:                          "$topdir/skins/express_show/player-min.css",
                   14071:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  14072:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   14073:                          "$topdir/$topdir.mp4",
                   14074:                          "$topdir/$topdir\_config.xml",
                   14075:                          "$topdir/$topdir\_controller.swf",
                   14076:                          "$topdir/$topdir\_embed.css",
                   14077:                          "$topdir/$topdir\_First_Frame.png",
                   14078:                          "$topdir/$topdir\_player.html",
                   14079:                          "$topdir/$topdir\_Thumbnails.png",
                   14080:                          "$topdir/playerProductInstall.swf",
                   14081:                          "$topdir/scripts/",
                   14082:                          "$topdir/scripts/config_xml.js",
                   14083:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   14084:                          "$topdir/skins/",
                   14085:                          "$topdir/skins/configuration_express.xml",
                   14086:                          "$topdir/skins/express_show/",
                   14087:                          "$topdir/skins/express_show/spritesheet.min.css",
                   14088:                          "$topdir/skins/express_show/spritesheet.png",
                   14089:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  14090:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  14091:         if (@diffs == 0) {
1.1164    raeburn  14092:             $is_camtasia = 6;
                   14093:         } else {
1.1197    raeburn  14094:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  14095:             if (@diffs == 0) {
                   14096:                 $is_camtasia = 8;
1.1197    raeburn  14097:             } else {
                   14098:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   14099:                 if (@diffs == 0) {
                   14100:                     $is_camtasia = 8;
                   14101:                 }
1.1164    raeburn  14102:             }
1.1067    raeburn  14103:         }
                   14104:     }
                   14105:     my $output;
                   14106:     if ($is_camtasia) {
                   14107:         $output = <<"ENDCAM";
                   14108: <script type="text/javascript" language="Javascript">
                   14109: // <![CDATA[
                   14110: 
                   14111: function camtasiaToggle() {
                   14112:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   14113:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  14114:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  14115:                 document.getElementById('camtasia_titles').style.display='block';
                   14116:             } else {
                   14117:                 document.getElementById('camtasia_titles').style.display='none';
                   14118:             }
                   14119:         }
                   14120:     }
                   14121:     return;
                   14122: }
                   14123: 
                   14124: // ]]>
                   14125: </script>
                   14126: <p>$lt{'camt'}</p>
                   14127: ENDCAM
1.1065    raeburn  14128:     } else {
1.1067    raeburn  14129:         $output = '<p>'.$lt{'this'};
                   14130:         if ($info eq '') {
                   14131:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   14132:         } else {
                   14133:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   14134:                        '<div><pre>'.$info.'</pre></div>';
                   14135:         }
1.1065    raeburn  14136:     }
1.1067    raeburn  14137:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  14138:     my $duplicates;
                   14139:     my $num = 0;
                   14140:     if (ref($dirlist) eq 'ARRAY') {
                   14141:         foreach my $item (@{$dirlist}) {
                   14142:             if (ref($item) eq 'ARRAY') {
                   14143:                 if (exists($toplevel{$item->[0]})) {
                   14144:                     $duplicates .= 
                   14145:                         &start_data_table_row().
                   14146:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14147:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   14148:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14149:                         'value="1" />'.&mt('Yes').'</label>'.
                   14150:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   14151:                         '<td>'.$item->[0].'</td>';
                   14152:                     if ($item->[2]) {
                   14153:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   14154:                     } else {
                   14155:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   14156:                     }
                   14157:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   14158:                                    '<td>'.
                   14159:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   14160:                                    '</td>'.
                   14161:                                    &end_data_table_row();
                   14162:                     $num ++;
                   14163:                 }
                   14164:             }
                   14165:         }
                   14166:     }
                   14167:     my $itemcount;
                   14168:     if (@paths > 0) {
                   14169:         $itemcount = scalar(@paths);
                   14170:     } else {
                   14171:         $itemcount = 1;
                   14172:     }
1.1067    raeburn  14173:     if ($is_camtasia) {
                   14174:         $output .= $lt{'auto'}.'<br />'.
                   14175:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  14176:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  14177:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   14178:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   14179:                    $lt{'no'}.'</label></span><br />'.
                   14180:                    '<div id="camtasia_titles" style="display:block">'.
                   14181:                    &Apache::lonhtmlcommon::start_pick_box().
                   14182:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   14183:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   14184:                    &Apache::lonhtmlcommon::row_closure().
                   14185:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   14186:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   14187:                    &Apache::lonhtmlcommon::row_closure(1).
                   14188:                    &Apache::lonhtmlcommon::end_pick_box().
                   14189:                    '</div>';
                   14190:     }
1.1065    raeburn  14191:     $output .= 
                   14192:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  14193:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   14194:         "\n";
1.1065    raeburn  14195:     if ($duplicates ne '') {
                   14196:         $output .= '<p><span class="LC_warning">'.
                   14197:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   14198:                    &start_data_table().
                   14199:                    &start_data_table_header_row().
                   14200:                    '<th>'.&mt('Overwrite?').'</th>'.
                   14201:                    '<th>'.&mt('Name').'</th>'.
                   14202:                    '<th>'.&mt('Type').'</th>'.
                   14203:                    '<th>'.&mt('Size').'</th>'.
                   14204:                    '<th>'.&mt('Last modified').'</th>'.
                   14205:                    &end_data_table_header_row().
                   14206:                    $duplicates.
                   14207:                    &end_data_table().
                   14208:                    '</p>';
                   14209:     }
1.1067    raeburn  14210:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  14211:     if (ref($hiddenelements) eq 'HASH') {
                   14212:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   14213:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   14214:         }
                   14215:     }
                   14216:     $output .= <<"END";
1.1067    raeburn  14217: <br />
1.1053    raeburn  14218: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   14219: </form>
                   14220: $noextract
                   14221: END
                   14222:     return $output;
                   14223: }
                   14224: 
1.1065    raeburn  14225: sub decompression_utility {
                   14226:     my ($program) = @_;
                   14227:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   14228:     my $location;
                   14229:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   14230:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   14231:                          '/usr/sbin/') {
                   14232:             if (-x $dir.$program) {
                   14233:                 $location = $dir.$program;
                   14234:                 last;
                   14235:             }
                   14236:         }
                   14237:     }
                   14238:     return $location;
                   14239: }
                   14240: 
                   14241: sub list_archive_contents {
                   14242:     my ($file,$pathsref) = @_;
                   14243:     my (@cmd,$output);
                   14244:     my $needsregexp;
                   14245:     if ($file =~ /\.zip$/) {
                   14246:         @cmd = (&decompression_utility('unzip'),"-l");
                   14247:         $needsregexp = 1;
                   14248:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   14249:              ($file =~ /\.tgz$/)) {
                   14250:         @cmd = (&decompression_utility('tar'),"-ztf");
                   14251:     } elsif ($file =~ /\.tar\.bz2$/) {
                   14252:         @cmd = (&decompression_utility('tar'),"-jtf");
                   14253:     } elsif ($file =~ m|\.tar$|) {
                   14254:         @cmd = (&decompression_utility('tar'),"-tf");
                   14255:     }
                   14256:     if (@cmd) {
                   14257:         undef($!);
                   14258:         undef($@);
                   14259:         if (open(my $fh,"-|", @cmd, $file)) {
                   14260:             while (my $line = <$fh>) {
                   14261:                 $output .= $line;
                   14262:                 chomp($line);
                   14263:                 my $item;
                   14264:                 if ($needsregexp) {
                   14265:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   14266:                 } else {
                   14267:                     $item = $line;
                   14268:                 }
                   14269:                 if ($item ne '') {
                   14270:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   14271:                         push(@{$pathsref},$item);
                   14272:                     } 
                   14273:                 }
                   14274:             }
                   14275:             close($fh);
                   14276:         }
                   14277:     }
                   14278:     return $output;
                   14279: }
                   14280: 
1.1053    raeburn  14281: sub decompress_uploaded_file {
                   14282:     my ($file,$dir) = @_;
                   14283:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   14284:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   14285:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   14286:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   14287:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   14288:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   14289:     my $decompressed = $env{'cgi.decompressed'};
                   14290:     &Apache::lonnet::delenv('cgi.file');
                   14291:     &Apache::lonnet::delenv('cgi.dir');
                   14292:     &Apache::lonnet::delenv('cgi.decompressed');
                   14293:     return ($decompressed,$result);
                   14294: }
                   14295: 
1.1055    raeburn  14296: sub process_decompression {
                   14297:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  14298:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   14299:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14300:                &mt('Unexpected file path.').'</p>'."\n";
                   14301:     }
                   14302:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   14303:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14304:                &mt('Unexpected course context.').'</p>'."\n";
                   14305:     }
1.1293    raeburn  14306:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  14307:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14308:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   14309:     }
1.1055    raeburn  14310:     my ($dir,$error,$warning,$output);
1.1180    raeburn  14311:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   14312:         $error = &mt('Filename not a supported archive file type.').
                   14313:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  14314:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   14315:     } else {
                   14316:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14317:         if ($docuhome eq 'no_host') {
                   14318:             $error = &mt('Could not determine home server for course.');
                   14319:         } else {
                   14320:             my @ids=&Apache::lonnet::current_machine_ids();
                   14321:             my $currdir = "$dir_root/$destination";
                   14322:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14323:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   14324:                        "$dir_root/$destination";
                   14325:             } else {
                   14326:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   14327:                        "$dir_root/$docudom/$docuname/$destination";
                   14328:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   14329:                     $error = &mt('Archive file not found.');
                   14330:                 }
                   14331:             }
1.1065    raeburn  14332:             my (@to_overwrite,@to_skip);
                   14333:             if ($env{'form.archive_overwrite_total'} > 0) {
                   14334:                 my $total = $env{'form.archive_overwrite_total'};
                   14335:                 for (my $i=0; $i<$total; $i++) {
                   14336:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   14337:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   14338:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   14339:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   14340:                     }
                   14341:                 }
                   14342:             }
                   14343:             my $numskip = scalar(@to_skip);
1.1292    raeburn  14344:             my $numoverwrite = scalar(@to_overwrite);
                   14345:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  14346:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   14347:             } elsif ($dir eq '') {
1.1055    raeburn  14348:                 $error = &mt('Directory containing archive file unavailable.');
                   14349:             } elsif (!$error) {
1.1065    raeburn  14350:                 my ($decompressed,$display);
1.1292    raeburn  14351:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  14352:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   14353:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  14354:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   14355:                         ($decompressed,$display) = 
                   14356:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   14357:                         foreach my $item (@to_skip) {
                   14358:                             if (($item ne '') && ($item !~ /\.\./)) {
                   14359:                                 if (-f "$dir/$tempdir/$item") { 
                   14360:                                     unlink("$dir/$tempdir/$item");
                   14361:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  14362:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  14363:                                 }
                   14364:                             }
                   14365:                         }
                   14366:                         foreach my $item (@to_overwrite) {
                   14367:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   14368:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   14369:                                     if (-f "$dir/$item") {
                   14370:                                         unlink("$dir/$item");
                   14371:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  14372:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  14373:                                     }
                   14374:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   14375:                                 }
1.1065    raeburn  14376:                             }
                   14377:                         }
1.1292    raeburn  14378:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  14379:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  14380:                         }
1.1065    raeburn  14381:                     }
                   14382:                 } else {
                   14383:                     ($decompressed,$display) = 
                   14384:                         &decompress_uploaded_file($file,$dir);
                   14385:                 }
1.1055    raeburn  14386:                 if ($decompressed eq 'ok') {
1.1065    raeburn  14387:                     $output = '<p class="LC_info">'.
                   14388:                               &mt('Files extracted successfully from archive.').
                   14389:                               '</p>'."\n";
1.1055    raeburn  14390:                     my ($warning,$result,@contents);
                   14391:                     my ($newdirlistref,$newlisterror) =
                   14392:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   14393:                                                  $docuname,1);
                   14394:                     my (%is_dir,%changes,@newitems);
                   14395:                     my $dirptr = 16384;
1.1065    raeburn  14396:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  14397:                         foreach my $dir_line (@{$newdirlistref}) {
                   14398:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  14399:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  14400:                                 push(@newitems,$item);
                   14401:                                 if ($dirptr&$testdir) {
                   14402:                                     $is_dir{$item} = 1;
                   14403:                                 }
                   14404:                                 $changes{$item} = 1;
                   14405:                             }
                   14406:                         }
                   14407:                     }
                   14408:                     if (keys(%changes) > 0) {
                   14409:                         foreach my $item (sort(@newitems)) {
                   14410:                             if ($changes{$item}) {
                   14411:                                 push(@contents,$item);
                   14412:                             }
                   14413:                         }
                   14414:                     }
                   14415:                     if (@contents > 0) {
1.1067    raeburn  14416:                         my $wantform;
                   14417:                         unless ($env{'form.autoextract_camtasia'}) {
                   14418:                             $wantform = 1;
                   14419:                         }
1.1056    raeburn  14420:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  14421:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   14422:                                                                 $currdir,\%is_dir,
                   14423:                                                                 \%children,\%parent,
1.1056    raeburn  14424:                                                                 \@contents,\%dirorder,
                   14425:                                                                 \%titles,$wantform);
1.1055    raeburn  14426:                         if ($datatable ne '') {
                   14427:                             $output .= &archive_options_form('decompressed',$datatable,
                   14428:                                                              $count,$hiddenelem);
1.1065    raeburn  14429:                             my $startcount = 6;
1.1055    raeburn  14430:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  14431:                                                            \%titles,\%children);
1.1055    raeburn  14432:                         }
1.1067    raeburn  14433:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  14434:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  14435:                             my %displayed;
                   14436:                             my $total = 1;
                   14437:                             $env{'form.archive_directory'} = [];
                   14438:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   14439:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   14440:                                 $path =~ s{/$}{};
                   14441:                                 my $item;
                   14442:                                 if ($path ne '') {
                   14443:                                     $item = "$path/$titles{$i}";
                   14444:                                 } else {
                   14445:                                     $item = $titles{$i};
                   14446:                                 }
                   14447:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   14448:                                 if ($item eq $contents[0]) {
                   14449:                                     push(@{$env{'form.archive_directory'}},$i);
                   14450:                                     $env{'form.archive_'.$i} = 'display';
                   14451:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   14452:                                     $displayed{'folder'} = $i;
1.1164    raeburn  14453:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   14454:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  14455:                                     $env{'form.archive_'.$i} = 'display';
                   14456:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   14457:                                     $displayed{'web'} = $i;
                   14458:                                 } else {
1.1164    raeburn  14459:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   14460:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   14461:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  14462:                                         push(@{$env{'form.archive_directory'}},$i);
                   14463:                                     }
                   14464:                                     $env{'form.archive_'.$i} = 'dependency';
                   14465:                                 }
                   14466:                                 $total ++;
                   14467:                             }
                   14468:                             for (my $i=1; $i<$total; $i++) {
                   14469:                                 next if ($i == $displayed{'web'});
                   14470:                                 next if ($i == $displayed{'folder'});
                   14471:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   14472:                             }
                   14473:                             $env{'form.phase'} = 'decompress_cleanup';
                   14474:                             $env{'form.archivedelete'} = 1;
                   14475:                             $env{'form.archive_count'} = $total-1;
                   14476:                             $output .=
                   14477:                                 &process_extracted_files('coursedocs',$docudom,
                   14478:                                                          $docuname,$destination,
                   14479:                                                          $dir_root,$hiddenelem);
                   14480:                         }
1.1055    raeburn  14481:                     } else {
                   14482:                         $warning = &mt('No new items extracted from archive file.');
                   14483:                     }
                   14484:                 } else {
                   14485:                     $output = $display;
                   14486:                     $error = &mt('An error occurred during extraction from the archive file.');
                   14487:                 }
                   14488:             }
                   14489:         }
                   14490:     }
                   14491:     if ($error) {
                   14492:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14493:                    $error.'</p>'."\n";
                   14494:     }
                   14495:     if ($warning) {
                   14496:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14497:     }
                   14498:     return $output;
                   14499: }
                   14500: 
                   14501: sub get_extracted {
1.1056    raeburn  14502:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   14503:         $titles,$wantform) = @_;
1.1055    raeburn  14504:     my $count = 0;
                   14505:     my $depth = 0;
                   14506:     my $datatable;
1.1056    raeburn  14507:     my @hierarchy;
1.1055    raeburn  14508:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  14509:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   14510:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  14511:     foreach my $item (@{$contents}) {
                   14512:         $count ++;
1.1056    raeburn  14513:         @{$dirorder->{$count}} = @hierarchy;
                   14514:         $titles->{$count} = $item;
1.1055    raeburn  14515:         &archive_hierarchy($depth,$count,$parent,$children);
                   14516:         if ($wantform) {
                   14517:             $datatable .= &archive_row($is_dir->{$item},$item,
                   14518:                                        $currdir,$depth,$count);
                   14519:         }
                   14520:         if ($is_dir->{$item}) {
                   14521:             $depth ++;
1.1056    raeburn  14522:             push(@hierarchy,$count);
                   14523:             $parent->{$depth} = $count;
1.1055    raeburn  14524:             $datatable .=
                   14525:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  14526:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   14527:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  14528:             $depth --;
1.1056    raeburn  14529:             pop(@hierarchy);
1.1055    raeburn  14530:         }
                   14531:     }
                   14532:     return ($count,$datatable);
                   14533: }
                   14534: 
                   14535: sub recurse_extracted_archive {
1.1056    raeburn  14536:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   14537:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  14538:     my $result='';
1.1056    raeburn  14539:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   14540:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   14541:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  14542:         return $result;
                   14543:     }
                   14544:     my $dirptr = 16384;
                   14545:     my ($newdirlistref,$newlisterror) =
                   14546:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   14547:     if (ref($newdirlistref) eq 'ARRAY') {
                   14548:         foreach my $dir_line (@{$newdirlistref}) {
                   14549:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   14550:             unless ($item =~ /^\.+$/) {
                   14551:                 $$count ++;
1.1056    raeburn  14552:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   14553:                 $titles->{$$count} = $item;
1.1055    raeburn  14554:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  14555: 
1.1055    raeburn  14556:                 my $is_dir;
                   14557:                 if ($dirptr&$testdir) {
                   14558:                     $is_dir = 1;
                   14559:                 }
                   14560:                 if ($wantform) {
                   14561:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   14562:                 }
                   14563:                 if ($is_dir) {
                   14564:                     $$depth ++;
1.1056    raeburn  14565:                     push(@{$hierarchy},$$count);
                   14566:                     $parent->{$$depth} = $$count;
1.1055    raeburn  14567:                     $result .=
                   14568:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   14569:                                                    $docuname,$depth,$count,
1.1056    raeburn  14570:                                                    $hierarchy,$dirorder,$children,
                   14571:                                                    $parent,$titles,$wantform);
1.1055    raeburn  14572:                     $$depth --;
1.1056    raeburn  14573:                     pop(@{$hierarchy});
1.1055    raeburn  14574:                 }
                   14575:             }
                   14576:         }
                   14577:     }
                   14578:     return $result;
                   14579: }
                   14580: 
                   14581: sub archive_hierarchy {
                   14582:     my ($depth,$count,$parent,$children) =@_;
                   14583:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   14584:         if (exists($parent->{$depth})) {
                   14585:              $children->{$parent->{$depth}} .= $count.':';
                   14586:         }
                   14587:     }
                   14588:     return;
                   14589: }
                   14590: 
                   14591: sub archive_row {
                   14592:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   14593:     my ($name) = ($item =~ m{([^/]+)$});
                   14594:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  14595:                                        'display'    => 'Add as file',
1.1055    raeburn  14596:                                        'dependency' => 'Include as dependency',
                   14597:                                        'discard'    => 'Discard',
                   14598:                                       );
                   14599:     if ($is_dir) {
1.1059    raeburn  14600:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  14601:     }
1.1056    raeburn  14602:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   14603:     my $offset = 0;
1.1055    raeburn  14604:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  14605:         $offset ++;
1.1065    raeburn  14606:         if ($action ne 'display') {
                   14607:             $offset ++;
                   14608:         }  
1.1055    raeburn  14609:         $output .= '<td><span class="LC_nobreak">'.
                   14610:                    '<label><input type="radio" name="archive_'.$count.
                   14611:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   14612:         my $text = $choices{$action};
                   14613:         if ($is_dir) {
                   14614:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   14615:             if ($action eq 'display') {
1.1059    raeburn  14616:                 $text = &mt('Add as folder');
1.1055    raeburn  14617:             }
1.1056    raeburn  14618:         } else {
                   14619:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   14620: 
                   14621:         }
                   14622:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   14623:         if ($action eq 'dependency') {
                   14624:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   14625:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   14626:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   14627:                        '<option value=""></option>'."\n".
                   14628:                        '</select>'."\n".
                   14629:                        '</div>';
1.1059    raeburn  14630:         } elsif ($action eq 'display') {
                   14631:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   14632:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   14633:                        '</div>';
1.1055    raeburn  14634:         }
1.1056    raeburn  14635:         $output .= '</td>';
1.1055    raeburn  14636:     }
                   14637:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   14638:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   14639:     for (my $i=0; $i<$depth; $i++) {
                   14640:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   14641:     }
                   14642:     if ($is_dir) {
                   14643:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   14644:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   14645:     } else {
                   14646:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   14647:     }
                   14648:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   14649:                &end_data_table_row();
                   14650:     return $output;
                   14651: }
                   14652: 
                   14653: sub archive_options_form {
1.1065    raeburn  14654:     my ($form,$display,$count,$hiddenelem) = @_;
                   14655:     my %lt = &Apache::lonlocal::texthash(
                   14656:                perm => 'Permanently remove archive file?',
                   14657:                hows => 'How should each extracted item be incorporated in the course?',
                   14658:                cont => 'Content actions for all',
                   14659:                addf => 'Add as folder/file',
                   14660:                incd => 'Include as dependency for a displayed file',
                   14661:                disc => 'Discard',
                   14662:                no   => 'No',
                   14663:                yes  => 'Yes',
                   14664:                save => 'Save',
                   14665:     );
                   14666:     my $output = <<"END";
                   14667: <form name="$form" method="post" action="">
                   14668: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   14669: <label>
                   14670:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   14671: </label>
                   14672: &nbsp;
                   14673: <label>
                   14674:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   14675: </span>
                   14676: </p>
                   14677: <input type="hidden" name="phase" value="decompress_cleanup" />
                   14678: <br />$lt{'hows'}
                   14679: <div class="LC_columnSection">
                   14680:   <fieldset>
                   14681:     <legend>$lt{'cont'}</legend>
                   14682:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   14683:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   14684:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   14685:   </fieldset>
                   14686: </div>
                   14687: END
                   14688:     return $output.
1.1055    raeburn  14689:            &start_data_table()."\n".
1.1065    raeburn  14690:            $display."\n".
1.1055    raeburn  14691:            &end_data_table()."\n".
                   14692:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   14693:            $hiddenelem.
1.1065    raeburn  14694:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  14695:            '</form>';
                   14696: }
                   14697: 
                   14698: sub archive_javascript {
1.1056    raeburn  14699:     my ($startcount,$numitems,$titles,$children) = @_;
                   14700:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  14701:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  14702:     my $scripttag = <<START;
                   14703: <script type="text/javascript">
                   14704: // <![CDATA[
                   14705: 
                   14706: function checkAll(form,prefix) {
                   14707:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14708:     for (var i=0; i < form.elements.length; i++) {
                   14709:         var id = form.elements[i].id;
                   14710:         if ((id != '') && (id != undefined)) {
                   14711:             if (idstr.test(id)) {
                   14712:                 if (form.elements[i].type == 'radio') {
                   14713:                     form.elements[i].checked = true;
1.1056    raeburn  14714:                     var nostart = i-$startcount;
1.1059    raeburn  14715:                     var offset = nostart%7;
                   14716:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14717:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14718:                 }
                   14719:             }
                   14720:         }
                   14721:     }
                   14722: }
                   14723: 
                   14724: function propagateCheck(form,count) {
                   14725:     if (count > 0) {
1.1059    raeburn  14726:         var startelement = $startcount + ((count-1) * 7);
                   14727:         for (var j=1; j<6; j++) {
                   14728:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14729:                 var item = startelement + j; 
                   14730:                 if (form.elements[item].type == 'radio') {
                   14731:                     if (form.elements[item].checked) {
                   14732:                         containerCheck(form,count,j);
                   14733:                         break;
                   14734:                     }
1.1055    raeburn  14735:                 }
                   14736:             }
                   14737:         }
                   14738:     }
                   14739: }
                   14740: 
                   14741: numitems = $numitems
1.1056    raeburn  14742: var titles = new Array(numitems);
                   14743: var parents = new Array(numitems);
1.1055    raeburn  14744: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14745:     parents[i] = new Array;
1.1055    raeburn  14746: }
1.1059    raeburn  14747: var maintitle = '$maintitle';
1.1055    raeburn  14748: 
                   14749: START
                   14750: 
1.1056    raeburn  14751:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14752:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14753:         for (my $i=0; $i<@contents; $i ++) {
                   14754:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14755:         }
                   14756:     }
                   14757: 
1.1056    raeburn  14758:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14759:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14760:     }
                   14761: 
1.1055    raeburn  14762:     $scripttag .= <<END;
                   14763: 
                   14764: function containerCheck(form,count,offset) {
                   14765:     if (count > 0) {
1.1056    raeburn  14766:         dependencyCheck(form,count,offset);
1.1059    raeburn  14767:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14768:         form.elements[item].checked = true;
                   14769:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14770:             if (parents[count].length > 0) {
                   14771:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14772:                     containerCheck(form,parents[count][j],offset);
                   14773:                 }
                   14774:             }
                   14775:         }
                   14776:     }
                   14777: }
                   14778: 
                   14779: function dependencyCheck(form,count,offset) {
                   14780:     if (count > 0) {
1.1059    raeburn  14781:         var chosen = (offset+$startcount)+7*(count-1);
                   14782:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14783:         var currtype = form.elements[depitem].type;
                   14784:         if (form.elements[chosen].value == 'dependency') {
                   14785:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14786:             form.elements[depitem].options.length = 0;
                   14787:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14788:             for (var i=1; i<=numitems; i++) {
                   14789:                 if (i == count) {
                   14790:                     continue;
                   14791:                 }
1.1059    raeburn  14792:                 var startelement = $startcount + (i-1) * 7;
                   14793:                 for (var j=1; j<6; j++) {
                   14794:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14795:                         var item = startelement + j;
                   14796:                         if (form.elements[item].type == 'radio') {
                   14797:                             if (form.elements[item].checked) {
                   14798:                                 if (form.elements[item].value == 'display') {
                   14799:                                     var n = form.elements[depitem].options.length;
                   14800:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14801:                                 }
                   14802:                             }
                   14803:                         }
                   14804:                     }
                   14805:                 }
                   14806:             }
                   14807:         } else {
                   14808:             document.getElementById('arc_depon_'+count).style.display='none';
                   14809:             form.elements[depitem].options.length = 0;
                   14810:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14811:         }
1.1059    raeburn  14812:         titleCheck(form,count,offset);
1.1056    raeburn  14813:     }
                   14814: }
                   14815: 
                   14816: function propagateSelect(form,count,offset) {
                   14817:     if (count > 0) {
1.1065    raeburn  14818:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14819:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14820:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14821:             if (parents[count].length > 0) {
                   14822:                 for (var j=0; j<parents[count].length; j++) {
                   14823:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14824:                 }
                   14825:             }
                   14826:         }
                   14827:     }
                   14828: }
1.1056    raeburn  14829: 
                   14830: function containerSelect(form,count,offset,picked) {
                   14831:     if (count > 0) {
1.1065    raeburn  14832:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14833:         if (form.elements[item].type == 'radio') {
                   14834:             if (form.elements[item].value == 'dependency') {
                   14835:                 if (form.elements[item+1].type == 'select-one') {
                   14836:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14837:                         if (form.elements[item+1].options[i].value == picked) {
                   14838:                             form.elements[item+1].selectedIndex = i;
                   14839:                             break;
                   14840:                         }
                   14841:                     }
                   14842:                 }
                   14843:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14844:                     if (parents[count].length > 0) {
                   14845:                         for (var j=0; j<parents[count].length; j++) {
                   14846:                             containerSelect(form,parents[count][j],offset,picked);
                   14847:                         }
                   14848:                     }
                   14849:                 }
                   14850:             }
                   14851:         }
                   14852:     }
                   14853: }
                   14854: 
1.1059    raeburn  14855: function titleCheck(form,count,offset) {
                   14856:     if (count > 0) {
                   14857:         var chosen = (offset+$startcount)+7*(count-1);
                   14858:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14859:         var currtype = form.elements[depitem].type;
                   14860:         if (form.elements[chosen].value == 'display') {
                   14861:             document.getElementById('arc_title_'+count).style.display='block';
                   14862:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14863:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14864:             }
                   14865:         } else {
                   14866:             document.getElementById('arc_title_'+count).style.display='none';
                   14867:             if (currtype == 'text') { 
                   14868:                 document.getElementById('archive_title_'+count).value='';
                   14869:             }
                   14870:         }
                   14871:     }
                   14872:     return;
                   14873: }
                   14874: 
1.1055    raeburn  14875: // ]]>
                   14876: </script>
                   14877: END
                   14878:     return $scripttag;
                   14879: }
                   14880: 
                   14881: sub process_extracted_files {
1.1067    raeburn  14882:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14883:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14884:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14885:     my @ids=&Apache::lonnet::current_machine_ids();
                   14886:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14887:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14888:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14889:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14890:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14891:         $pathtocheck = "$dir_root/$destination";
                   14892:         $dir = $dir_root;
                   14893:         $ishome = 1;
                   14894:     } else {
                   14895:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14896:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14897:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14898:     }
                   14899:     my $currdir = "$dir_root/$destination";
                   14900:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14901:     if ($env{'form.folderpath'}) {
                   14902:         my @items = split('&',$env{'form.folderpath'});
                   14903:         $folders{'0'} = $items[-2];
1.1099    raeburn  14904:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14905:             $containers{'0'}='page';
                   14906:         } else {  
                   14907:             $containers{'0'}='sequence';
                   14908:         }
1.1055    raeburn  14909:     }
                   14910:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14911:     if ($numitems) {
                   14912:         for (my $i=1; $i<=$numitems; $i++) {
                   14913:             my $path = $env{'form.archive_content_'.$i};
                   14914:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14915:                 my $item = $1;
                   14916:                 $toplevelitems{$item} = $i;
                   14917:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14918:                     $is_dir{$item} = 1;
                   14919:                 }
                   14920:             }
                   14921:         }
                   14922:     }
1.1067    raeburn  14923:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14924:     if (keys(%toplevelitems) > 0) {
                   14925:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14926:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14927:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14928:     }
1.1066    raeburn  14929:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14930:     if ($numitems) {
                   14931:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14932:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14933:             my $path = $env{'form.archive_content_'.$i};
                   14934:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14935:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14936:                     if ($prefix ne '' && $path ne '') {
                   14937:                         if (-e $prefix.$path) {
1.1066    raeburn  14938:                             if ((@archdirs > 0) && 
                   14939:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14940:                                 $todeletedir{$prefix.$path} = 1;
                   14941:                             } else {
                   14942:                                 $todelete{$prefix.$path} = 1;
                   14943:                             }
1.1055    raeburn  14944:                         }
                   14945:                     }
                   14946:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14947:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14948:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14949:                     $docstitle = $env{'form.archive_title_'.$i};
                   14950:                     if ($docstitle eq '') {
                   14951:                         $docstitle = $title;
                   14952:                     }
1.1055    raeburn  14953:                     $outer = 0;
1.1056    raeburn  14954:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14955:                         if (@{$dirorder{$i}} > 0) {
                   14956:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14957:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14958:                                     $outer = $item;
                   14959:                                     last;
                   14960:                                 }
                   14961:                             }
                   14962:                         }
                   14963:                     }
                   14964:                     my ($errtext,$fatal) = 
                   14965:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14966:                                                '/'.$folders{$outer}.'.'.
                   14967:                                                $containers{$outer});
                   14968:                     next if ($fatal);
                   14969:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14970:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14971:                             $mapinner{$i} = time;
1.1055    raeburn  14972:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14973:                             $containers{$i} = 'sequence';
                   14974:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14975:                                       $folders{$i}.'.'.$containers{$i};
                   14976:                             my $newidx = &LONCAPA::map::getresidx();
                   14977:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14978:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14979:                             push(@LONCAPA::map::order,$newidx);
                   14980:                             my ($outtext,$errtext) =
                   14981:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14982:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14983:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14984:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14985:                             unless ($errtext) {
1.1294    raeburn  14986:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14987:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14988:                                             '</li>'."\n";
1.1067    raeburn  14989:                             }
1.1055    raeburn  14990:                         }
                   14991:                     } else {
                   14992:                         if ($context eq 'coursedocs') {
                   14993:                             my $newidx=&LONCAPA::map::getresidx();
                   14994:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14995:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14996:                                       $title;
1.1392    raeburn  14997:                             if (($outer !~ /\D/) &&
                   14998:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14999:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  15000:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   15001:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   15002:                                 }
                   15003:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   15004:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   15005:                                 }
                   15006:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   15007:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   15008:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   15009:                                         unless ($ishome) {
                   15010:                                             my $fetch = "$newdest{$i}/$title";
                   15011:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   15012:                                             $prompttofetch{$fetch} = 1;
                   15013:                                         }
1.1292    raeburn  15014:                                     }
1.1067    raeburn  15015:                                 }
1.1294    raeburn  15016:                                 $LONCAPA::map::resources[$newidx]=
                   15017:                                     $docstitle.':'.$url.':false:normal:res';
                   15018:                                 push(@LONCAPA::map::order, $newidx);
                   15019:                                 my ($outtext,$errtext)=
                   15020:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   15021:                                                             $docuname.'/'.$folders{$outer}.
                   15022:                                                             '.'.$containers{$outer},1,1);
                   15023:                                 unless ($errtext) {
                   15024:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   15025:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   15026:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   15027:                                                    '</li>'."\n";
                   15028:                                     }
1.1067    raeburn  15029:                                 }
1.1294    raeburn  15030:                             } else {
                   15031:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   15032:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  15033:                             }
1.1055    raeburn  15034:                         }
                   15035:                     }
1.1086    raeburn  15036:                 }
                   15037:             } else {
1.1294    raeburn  15038:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   15039:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  15040:             }
                   15041:         }
                   15042:         for (my $i=1; $i<=$numitems; $i++) {
                   15043:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   15044:             my $path = $env{'form.archive_content_'.$i};
                   15045:             if ($path =~ /^\Q$pathtocheck\E/) {
                   15046:                 my ($title) = ($path =~ m{/([^/]+)$});
                   15047:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   15048:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   15049:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   15050:                         my ($itemidx,$fullpath,$relpath);
                   15051:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   15052:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  15053:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  15054:                                 if ($dirorder{$i}->[$j] eq $container) {
                   15055:                                     $itemidx = $j;
1.1056    raeburn  15056:                                 }
                   15057:                             }
1.1086    raeburn  15058:                         }
                   15059:                         if ($itemidx eq '') {
                   15060:                             $itemidx =  0;
                   15061:                         } 
                   15062:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   15063:                             if ($mapinner{$referrer{$i}}) {
                   15064:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   15065:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15066:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15067:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15068:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15069:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15070:                                             if (!-e $fullpath) {
                   15071:                                                 mkdir($fullpath,0755);
1.1056    raeburn  15072:                                             }
                   15073:                                         }
1.1086    raeburn  15074:                                     } else {
                   15075:                                         last;
1.1056    raeburn  15076:                                     }
1.1086    raeburn  15077:                                 }
                   15078:                             }
                   15079:                         } elsif ($newdest{$referrer{$i}}) {
                   15080:                             $fullpath = $newdest{$referrer{$i}};
                   15081:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15082:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   15083:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   15084:                                     last;
                   15085:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15086:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15087:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15088:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15089:                                         if (!-e $fullpath) {
                   15090:                                             mkdir($fullpath,0755);
1.1056    raeburn  15091:                                         }
                   15092:                                     }
1.1086    raeburn  15093:                                 } else {
                   15094:                                     last;
1.1056    raeburn  15095:                                 }
1.1055    raeburn  15096:                             }
                   15097:                         }
1.1086    raeburn  15098:                         if ($fullpath ne '') {
                   15099:                             if (-e "$prefix$path") {
1.1292    raeburn  15100:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   15101:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   15102:                                 }
1.1086    raeburn  15103:                             }
                   15104:                             if (-e "$fullpath/$title") {
                   15105:                                 my $showpath;
                   15106:                                 if ($relpath ne '') {
                   15107:                                     $showpath = "$relpath/$title";
                   15108:                                 } else {
                   15109:                                     $showpath = "/$title";
                   15110:                                 } 
1.1294    raeburn  15111:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   15112:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   15113:                                            '</li>'."\n";
1.1292    raeburn  15114:                                 unless ($ishome) {
                   15115:                                     my $fetch = "$fullpath/$title";
                   15116:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   15117:                                     $prompttofetch{$fetch} = 1;
                   15118:                                 }
1.1086    raeburn  15119:                             }
                   15120:                         }
1.1055    raeburn  15121:                     }
1.1086    raeburn  15122:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   15123:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  15124:                                     &HTML::Entities::encode($path,'<>&"'),
                   15125:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   15126:                                 '<br />';
1.1055    raeburn  15127:                 }
                   15128:             } else {
1.1294    raeburn  15129:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  15130:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  15131:             }
                   15132:         }
                   15133:         if (keys(%todelete)) {
                   15134:             foreach my $key (keys(%todelete)) {
                   15135:                 unlink($key);
1.1066    raeburn  15136:             }
                   15137:         }
                   15138:         if (keys(%todeletedir)) {
                   15139:             foreach my $key (keys(%todeletedir)) {
                   15140:                 rmdir($key);
                   15141:             }
                   15142:         }
                   15143:         foreach my $dir (sort(keys(%is_dir))) {
                   15144:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   15145:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  15146:             }
                   15147:         }
1.1067    raeburn  15148:         if ($result ne '') {
                   15149:             $output .= '<ul>'."\n".
                   15150:                        $result."\n".
                   15151:                        '</ul>';
                   15152:         }
                   15153:         unless ($ishome) {
                   15154:             my $replicationfail;
                   15155:             foreach my $item (keys(%prompttofetch)) {
                   15156:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   15157:                 unless ($fetchresult eq 'ok') {
                   15158:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   15159:                 }
                   15160:             }
                   15161:             if ($replicationfail) {
                   15162:                 $output .= '<p class="LC_error">'.
                   15163:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   15164:                            $replicationfail.
                   15165:                            '</ul></p>';
                   15166:             }
                   15167:         }
1.1055    raeburn  15168:     } else {
                   15169:         $warning = &mt('No items found in archive.');
                   15170:     }
                   15171:     if ($error) {
                   15172:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   15173:                    $error.'</p>'."\n";
                   15174:     }
                   15175:     if ($warning) {
                   15176:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   15177:     }
                   15178:     return $output;
                   15179: }
                   15180: 
1.1066    raeburn  15181: sub cleanup_empty_dirs {
                   15182:     my ($path) = @_;
                   15183:     if (($path ne '') && (-d $path)) {
                   15184:         if (opendir(my $dirh,$path)) {
                   15185:             my @dircontents = grep(!/^\./,readdir($dirh));
                   15186:             my $numitems = 0;
                   15187:             foreach my $item (@dircontents) {
                   15188:                 if (-d "$path/$item") {
1.1111    raeburn  15189:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  15190:                     if (-e "$path/$item") {
                   15191:                         $numitems ++;
                   15192:                     }
                   15193:                 } else {
                   15194:                     $numitems ++;
                   15195:                 }
                   15196:             }
                   15197:             if ($numitems == 0) {
                   15198:                 rmdir($path);
                   15199:             }
                   15200:             closedir($dirh);
                   15201:         }
                   15202:     }
                   15203:     return;
                   15204: }
                   15205: 
1.41      ng       15206: =pod
1.45      matthew  15207: 
1.1162    raeburn  15208: =item * &get_folder_hierarchy()
1.1068    raeburn  15209: 
                   15210: Provides hierarchy of names of folders/sub-folders containing the current
                   15211: item,
                   15212: 
                   15213: Inputs: 3
                   15214:      - $navmap - navmaps object
                   15215: 
                   15216:      - $map - url for map (either the trigger itself, or map containing
                   15217:                            the resource, which is the trigger).
                   15218: 
                   15219:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   15220: 
                   15221: Outputs: 1 @pathitems - array of folder/subfolder names.
                   15222: 
                   15223: =cut
                   15224: 
                   15225: sub get_folder_hierarchy {
                   15226:     my ($navmap,$map,$showitem) = @_;
                   15227:     my @pathitems;
                   15228:     if (ref($navmap)) {
                   15229:         my $mapres = $navmap->getResourceByUrl($map);
                   15230:         if (ref($mapres)) {
                   15231:             my $pcslist = $mapres->map_hierarchy();
                   15232:             if ($pcslist ne '') {
                   15233:                 my @pcs = split(/,/,$pcslist);
                   15234:                 foreach my $pc (@pcs) {
                   15235:                     if ($pc == 1) {
1.1129    raeburn  15236:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  15237:                     } else {
                   15238:                         my $res = $navmap->getByMapPc($pc);
                   15239:                         if (ref($res)) {
                   15240:                             my $title = $res->compTitle();
                   15241:                             $title =~ s/\W+/_/g;
                   15242:                             if ($title ne '') {
                   15243:                                 push(@pathitems,$title);
                   15244:                             }
                   15245:                         }
                   15246:                     }
                   15247:                 }
                   15248:             }
1.1071    raeburn  15249:             if ($showitem) {
                   15250:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  15251:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  15252:                 } else {
                   15253:                     my $maptitle = $mapres->compTitle();
                   15254:                     $maptitle =~ s/\W+/_/g;
                   15255:                     if ($maptitle ne '') {
                   15256:                         push(@pathitems,$maptitle);
                   15257:                     }
1.1068    raeburn  15258:                 }
                   15259:             }
                   15260:         }
                   15261:     }
                   15262:     return @pathitems;
                   15263: }
                   15264: 
                   15265: =pod
                   15266: 
1.1015    raeburn  15267: =item * &get_turnedin_filepath()
                   15268: 
                   15269: Determines path in a user's portfolio file for storage of files uploaded
                   15270: to a specific essayresponse or dropbox item.
                   15271: 
                   15272: Inputs: 3 required + 1 optional.
                   15273: $symb is symb for resource, $uname and $udom are for current user (required).
                   15274: $caller is optional (can be "submission", if routine is called when storing
                   15275: an upoaded file when "Submit Answer" button was pressed).
                   15276: 
                   15277: Returns array containing $path and $multiresp. 
                   15278: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   15279: than one file upload item.  Callers of routine should append partid as a 
                   15280: subdirectory to $path in cases where $multiresp is 1.
                   15281: 
                   15282: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   15283: 
                   15284: =cut
                   15285: 
                   15286: sub get_turnedin_filepath {
                   15287:     my ($symb,$uname,$udom,$caller) = @_;
                   15288:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   15289:     my $turnindir;
                   15290:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   15291:     $turnindir = $userhash{'turnindir'};
                   15292:     my ($path,$multiresp);
                   15293:     if ($turnindir eq '') {
                   15294:         if ($caller eq 'submission') {
                   15295:             $turnindir = &mt('turned in');
                   15296:             $turnindir =~ s/\W+/_/g;
                   15297:             my %newhash = (
                   15298:                             'turnindir' => $turnindir,
                   15299:                           );
                   15300:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   15301:         }
                   15302:     }
                   15303:     if ($turnindir ne '') {
                   15304:         $path = '/'.$turnindir.'/';
                   15305:         my ($multipart,$turnin,@pathitems);
                   15306:         my $navmap = Apache::lonnavmaps::navmap->new();
                   15307:         if (defined($navmap)) {
                   15308:             my $mapres = $navmap->getResourceByUrl($map);
                   15309:             if (ref($mapres)) {
                   15310:                 my $pcslist = $mapres->map_hierarchy();
                   15311:                 if ($pcslist ne '') {
                   15312:                     foreach my $pc (split(/,/,$pcslist)) {
                   15313:                         my $res = $navmap->getByMapPc($pc);
                   15314:                         if (ref($res)) {
                   15315:                             my $title = $res->compTitle();
                   15316:                             $title =~ s/\W+/_/g;
                   15317:                             if ($title ne '') {
1.1149    raeburn  15318:                                 if (($pc > 1) && (length($title) > 12)) {
                   15319:                                     $title = substr($title,0,12);
                   15320:                                 }
1.1015    raeburn  15321:                                 push(@pathitems,$title);
                   15322:                             }
                   15323:                         }
                   15324:                     }
                   15325:                 }
                   15326:                 my $maptitle = $mapres->compTitle();
                   15327:                 $maptitle =~ s/\W+/_/g;
                   15328:                 if ($maptitle ne '') {
1.1149    raeburn  15329:                     if (length($maptitle) > 12) {
                   15330:                         $maptitle = substr($maptitle,0,12);
                   15331:                     }
1.1015    raeburn  15332:                     push(@pathitems,$maptitle);
                   15333:                 }
                   15334:                 unless ($env{'request.state'} eq 'construct') {
                   15335:                     my $res = $navmap->getBySymb($symb);
                   15336:                     if (ref($res)) {
                   15337:                         my $partlist = $res->parts();
                   15338:                         my $totaluploads = 0;
                   15339:                         if (ref($partlist) eq 'ARRAY') {
                   15340:                             foreach my $part (@{$partlist}) {
                   15341:                                 my @types = $res->responseType($part);
                   15342:                                 my @ids = $res->responseIds($part);
                   15343:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   15344:                                     if ($types[$i] eq 'essay') {
                   15345:                                         my $partid = $part.'_'.$ids[$i];
                   15346:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   15347:                                             $totaluploads ++;
                   15348:                                         }
                   15349:                                     }
                   15350:                                 }
                   15351:                             }
                   15352:                             if ($totaluploads > 1) {
                   15353:                                 $multiresp = 1;
                   15354:                             }
                   15355:                         }
                   15356:                     }
                   15357:                 }
                   15358:             } else {
                   15359:                 return;
                   15360:             }
                   15361:         } else {
                   15362:             return;
                   15363:         }
                   15364:         my $restitle=&Apache::lonnet::gettitle($symb);
                   15365:         $restitle =~ s/\W+/_/g;
                   15366:         if ($restitle eq '') {
                   15367:             $restitle = ($resurl =~ m{/[^/]+$});
                   15368:             if ($restitle eq '') {
                   15369:                 $restitle = time;
                   15370:             }
                   15371:         }
1.1149    raeburn  15372:         if (length($restitle) > 12) {
                   15373:             $restitle = substr($restitle,0,12);
                   15374:         }
1.1015    raeburn  15375:         push(@pathitems,$restitle);
                   15376:         $path .= join('/',@pathitems);
                   15377:     }
                   15378:     return ($path,$multiresp);
                   15379: }
                   15380: 
                   15381: =pod
                   15382: 
1.464     albertel 15383: =back
1.41      ng       15384: 
1.112     bowersj2 15385: =head1 CSV Upload/Handling functions
1.38      albertel 15386: 
1.41      ng       15387: =over 4
                   15388: 
1.648     raeburn  15389: =item * &upfile_store($r)
1.41      ng       15390: 
                   15391: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 15392: needs $env{'form.upfile'}
1.41      ng       15393: returns $datatoken to be put into hidden field
                   15394: 
                   15395: =cut
1.31      albertel 15396: 
                   15397: sub upfile_store {
                   15398:     my $r=shift;
1.258     albertel 15399:     $env{'form.upfile'}=~s/\r/\n/gs;
                   15400:     $env{'form.upfile'}=~s/\f/\n/gs;
                   15401:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   15402:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 15403: 
1.1299    raeburn  15404:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   15405:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   15406:                                      time.'_'.$$);
                   15407:     return if ($datatoken eq '');
                   15408: 
1.31      albertel 15409:     {
1.158     raeburn  15410:         my $datafile = $r->dir_config('lonDaemons').
                   15411:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15412:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 15413:             print $fh $env{'form.upfile'};
1.158     raeburn  15414:             close($fh);
                   15415:         }
1.31      albertel 15416:     }
                   15417:     return $datatoken;
                   15418: }
                   15419: 
1.56      matthew  15420: =pod
                   15421: 
1.1290    raeburn  15422: =item * &load_tmp_file($r,$datatoken)
1.41      ng       15423: 
                   15424: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  15425: $datatoken is the name to assign to the temporary file.
1.258     albertel 15426: sets $env{'form.upfile'} to the contents of the file
1.41      ng       15427: 
                   15428: =cut
1.31      albertel 15429: 
                   15430: sub load_tmp_file {
1.1290    raeburn  15431:     my ($r,$datatoken) = @_;
                   15432:     return if ($datatoken eq '');
1.31      albertel 15433:     my @studentdata=();
                   15434:     {
1.158     raeburn  15435:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  15436:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15437:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  15438:             @studentdata=<$fh>;
                   15439:             close($fh);
                   15440:         }
1.31      albertel 15441:     }
1.258     albertel 15442:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 15443: }
                   15444: 
1.1290    raeburn  15445: sub valid_datatoken {
                   15446:     my ($datatoken) = @_;
1.1325    raeburn  15447:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  15448:         return $datatoken;
                   15449:     }
                   15450:     return;
                   15451: }
                   15452: 
1.56      matthew  15453: =pod
                   15454: 
1.648     raeburn  15455: =item * &upfile_record_sep()
1.41      ng       15456: 
                   15457: Separate uploaded file into records
                   15458: returns array of records,
1.258     albertel 15459: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       15460: 
                   15461: =cut
1.31      albertel 15462: 
                   15463: sub upfile_record_sep {
1.258     albertel 15464:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 15465:     } else {
1.248     albertel 15466: 	my @records;
1.258     albertel 15467: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 15468: 	    if ($line=~/^\s*$/) { next; }
                   15469: 	    push(@records,$line);
                   15470: 	}
                   15471: 	return @records;
1.31      albertel 15472:     }
                   15473: }
                   15474: 
1.56      matthew  15475: =pod
                   15476: 
1.648     raeburn  15477: =item * &record_sep($record)
1.41      ng       15478: 
1.258     albertel 15479: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       15480: 
                   15481: =cut
                   15482: 
1.263     www      15483: sub takeleft {
                   15484:     my $index=shift;
                   15485:     return substr('0000'.$index,-4,4);
                   15486: }
                   15487: 
1.31      albertel 15488: sub record_sep {
                   15489:     my $record=shift;
                   15490:     my %components=();
1.258     albertel 15491:     if ($env{'form.upfiletype'} eq 'xml') {
                   15492:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 15493:         my $i=0;
1.356     albertel 15494:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 15495:             $field=~s/^(\"|\')//;
                   15496:             $field=~s/(\"|\')$//;
1.263     www      15497:             $components{&takeleft($i)}=$field;
1.31      albertel 15498:             $i++;
                   15499:         }
1.258     albertel 15500:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 15501:         my $i=0;
1.356     albertel 15502:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 15503:             $field=~s/^(\"|\')//;
                   15504:             $field=~s/(\"|\')$//;
1.263     www      15505:             $components{&takeleft($i)}=$field;
1.31      albertel 15506:             $i++;
                   15507:         }
                   15508:     } else {
1.561     www      15509:         my $separator=',';
1.480     banghart 15510:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      15511:             $separator=';';
1.480     banghart 15512:         }
1.31      albertel 15513:         my $i=0;
1.561     www      15514: # the character we are looking for to indicate the end of a quote or a record 
                   15515:         my $looking_for=$separator;
                   15516: # do not add the characters to the fields
                   15517:         my $ignore=0;
                   15518: # we just encountered a separator (or the beginning of the record)
                   15519:         my $just_found_separator=1;
                   15520: # store the field we are working on here
                   15521:         my $field='';
                   15522: # work our way through all characters in record
                   15523:         foreach my $character ($record=~/(.)/g) {
                   15524:             if ($character eq $looking_for) {
                   15525:                if ($character ne $separator) {
                   15526: # Found the end of a quote, again looking for separator
                   15527:                   $looking_for=$separator;
                   15528:                   $ignore=1;
                   15529:                } else {
                   15530: # Found a separator, store away what we got
                   15531:                   $components{&takeleft($i)}=$field;
                   15532: 	          $i++;
                   15533:                   $just_found_separator=1;
                   15534:                   $ignore=0;
                   15535:                   $field='';
                   15536:                }
                   15537:                next;
                   15538:             }
                   15539: # single or double quotation marks after a separator indicate beginning of a quote
                   15540: # we are now looking for the end of the quote and need to ignore separators
                   15541:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   15542:                $looking_for=$character;
                   15543:                next;
                   15544:             }
                   15545: # ignore would be true after we reached the end of a quote
                   15546:             if ($ignore) { next; }
                   15547:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   15548:             $field.=$character;
                   15549:             $just_found_separator=0; 
1.31      albertel 15550:         }
1.561     www      15551: # catch the very last entry, since we never encountered the separator
                   15552:         $components{&takeleft($i)}=$field;
1.31      albertel 15553:     }
                   15554:     return %components;
                   15555: }
                   15556: 
1.144     matthew  15557: ######################################################
                   15558: ######################################################
                   15559: 
1.56      matthew  15560: =pod
                   15561: 
1.648     raeburn  15562: =item * &upfile_select_html()
1.41      ng       15563: 
1.144     matthew  15564: Return HTML code to select a file from the users machine and specify 
                   15565: the file type.
1.41      ng       15566: 
                   15567: =cut
                   15568: 
1.144     matthew  15569: ######################################################
                   15570: ######################################################
1.31      albertel 15571: sub upfile_select_html {
1.144     matthew  15572:     my %Types = (
                   15573:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 15574:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  15575:                  space => &mt('Space separated'),
                   15576:                  tab   => &mt('Tabulator separated'),
                   15577: #                 xml   => &mt('HTML/XML'),
                   15578:                  );
                   15579:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  15580:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  15581:     foreach my $type (sort(keys(%Types))) {
                   15582:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   15583:     }
                   15584:     $Str .= "</select>\n";
                   15585:     return $Str;
1.31      albertel 15586: }
                   15587: 
1.301     albertel 15588: sub get_samples {
                   15589:     my ($records,$toget) = @_;
                   15590:     my @samples=({});
                   15591:     my $got=0;
                   15592:     foreach my $rec (@$records) {
                   15593: 	my %temp = &record_sep($rec);
                   15594: 	if (! grep(/\S/, values(%temp))) { next; }
                   15595: 	if (%temp) {
                   15596: 	    $samples[$got]=\%temp;
                   15597: 	    $got++;
                   15598: 	    if ($got == $toget) { last; }
                   15599: 	}
                   15600:     }
                   15601:     return \@samples;
                   15602: }
                   15603: 
1.144     matthew  15604: ######################################################
                   15605: ######################################################
                   15606: 
1.56      matthew  15607: =pod
                   15608: 
1.648     raeburn  15609: =item * &csv_print_samples($r,$records)
1.41      ng       15610: 
                   15611: Prints a table of sample values from each column uploaded $r is an
                   15612: Apache Request ref, $records is an arrayref from
                   15613: &Apache::loncommon::upfile_record_sep
                   15614: 
                   15615: =cut
                   15616: 
1.144     matthew  15617: ######################################################
                   15618: ######################################################
1.31      albertel 15619: sub csv_print_samples {
                   15620:     my ($r,$records) = @_;
1.662     bisitz   15621:     my $samples = &get_samples($records,5);
1.301     albertel 15622: 
1.594     raeburn  15623:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   15624:               &start_data_table_header_row());
1.356     albertel 15625:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   15626:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  15627:     $r->print(&end_data_table_header_row());
1.301     albertel 15628:     foreach my $hash (@$samples) {
1.594     raeburn  15629: 	$r->print(&start_data_table_row());
1.356     albertel 15630: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 15631: 	    $r->print('<td>');
1.356     albertel 15632: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 15633: 	    $r->print('</td>');
                   15634: 	}
1.594     raeburn  15635: 	$r->print(&end_data_table_row());
1.31      albertel 15636:     }
1.594     raeburn  15637:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 15638: }
                   15639: 
1.144     matthew  15640: ######################################################
                   15641: ######################################################
                   15642: 
1.56      matthew  15643: =pod
                   15644: 
1.648     raeburn  15645: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       15646: 
                   15647: Prints a table to create associations between values and table columns.
1.144     matthew  15648: 
1.41      ng       15649: $r is an Apache Request ref,
                   15650: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  15651: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       15652: 
                   15653: =cut
                   15654: 
1.144     matthew  15655: ######################################################
                   15656: ######################################################
1.31      albertel 15657: sub csv_print_select_table {
                   15658:     my ($r,$records,$d) = @_;
1.301     albertel 15659:     my $i=0;
                   15660:     my $samples = &get_samples($records,1);
1.144     matthew  15661:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  15662: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  15663:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  15664:               '<th>'.&mt('Column').'</th>'.
                   15665:               &end_data_table_header_row()."\n");
1.356     albertel 15666:     foreach my $array_ref (@$d) {
                   15667: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  15668: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 15669: 
1.875     bisitz   15670: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  15671: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 15672: 	$r->print('<option value="none"></option>');
1.356     albertel 15673: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   15674: 	    $r->print('<option value="'.$sample.'"'.
                   15675:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   15676:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 15677: 	}
1.594     raeburn  15678: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 15679: 	$i++;
                   15680:     }
1.594     raeburn  15681:     $r->print(&end_data_table());
1.31      albertel 15682:     $i--;
                   15683:     return $i;
                   15684: }
1.56      matthew  15685: 
1.144     matthew  15686: ######################################################
                   15687: ######################################################
                   15688: 
1.56      matthew  15689: =pod
1.31      albertel 15690: 
1.648     raeburn  15691: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       15692: 
                   15693: Prints a table of sample values from the upload and can make associate samples to internal names.
                   15694: 
                   15695: $r is an Apache Request ref,
                   15696: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   15697: $d is an array of 2 element arrays (internal name, displayed name)
                   15698: 
                   15699: =cut
                   15700: 
1.144     matthew  15701: ######################################################
                   15702: ######################################################
1.31      albertel 15703: sub csv_samples_select_table {
                   15704:     my ($r,$records,$d) = @_;
                   15705:     my $i=0;
1.144     matthew  15706:     #
1.662     bisitz   15707:     my $max_samples = 5;
                   15708:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15709:     $r->print(&start_data_table().
                   15710:               &start_data_table_header_row().'<th>'.
                   15711:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15712:               &end_data_table_header_row());
1.301     albertel 15713: 
                   15714:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15715: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15716: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15717: 	foreach my $option (@$d) {
                   15718: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15719: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15720:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15721:                       $display.'</option>');
1.31      albertel 15722: 	}
                   15723: 	$r->print('</select></td><td>');
1.662     bisitz   15724: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15725: 	    if (defined($samples->[$line]{$key})) { 
                   15726: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15727: 	    }
                   15728: 	}
1.594     raeburn  15729: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15730: 	$i++;
                   15731:     }
1.594     raeburn  15732:     $r->print(&end_data_table());
1.31      albertel 15733:     $i--;
                   15734:     return($i);
1.115     matthew  15735: }
                   15736: 
1.144     matthew  15737: ######################################################
                   15738: ######################################################
                   15739: 
1.115     matthew  15740: =pod
                   15741: 
1.648     raeburn  15742: =item * &clean_excel_name($name)
1.115     matthew  15743: 
                   15744: Returns a replacement for $name which does not contain any illegal characters.
                   15745: 
                   15746: =cut
                   15747: 
1.144     matthew  15748: ######################################################
                   15749: ######################################################
1.115     matthew  15750: sub clean_excel_name {
                   15751:     my ($name) = @_;
                   15752:     $name =~ s/[:\*\?\/\\]//g;
                   15753:     if (length($name) > 31) {
                   15754:         $name = substr($name,0,31);
                   15755:     }
                   15756:     return $name;
1.25      albertel 15757: }
1.84      albertel 15758: 
1.85      albertel 15759: =pod
                   15760: 
1.648     raeburn  15761: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15762: 
                   15763: Returns either 1 or undef
                   15764: 
                   15765: 1 if the part is to be hidden, undef if it is to be shown
                   15766: 
                   15767: Arguments are:
                   15768: 
                   15769: $id the id of the part to be checked
                   15770: $symb, optional the symb of the resource to check
                   15771: $udom, optional the domain of the user to check for
                   15772: $uname, optional the username of the user to check for
                   15773: 
                   15774: =cut
1.84      albertel 15775: 
                   15776: sub check_if_partid_hidden {
                   15777:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15778:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15779: 					 $symb,$udom,$uname);
1.141     albertel 15780:     my $truth=1;
                   15781:     #if the string starts with !, then the list is the list to show not hide
                   15782:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15783:     my @hiddenlist=split(/,/,$hiddenparts);
                   15784:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15785: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15786:     }
1.141     albertel 15787:     return !$truth;
1.84      albertel 15788: }
1.127     matthew  15789: 
1.138     matthew  15790: 
                   15791: ############################################################
                   15792: ############################################################
                   15793: 
                   15794: =pod
                   15795: 
1.157     matthew  15796: =back 
                   15797: 
1.138     matthew  15798: =head1 cgi-bin script and graphing routines
                   15799: 
1.157     matthew  15800: =over 4
                   15801: 
1.648     raeburn  15802: =item * &get_cgi_id()
1.138     matthew  15803: 
                   15804: Inputs: none
                   15805: 
                   15806: Returns an id which can be used to pass environment variables
                   15807: to various cgi-bin scripts.  These environment variables will
                   15808: be removed from the users environment after a given time by
                   15809: the routine &Apache::lonnet::transfer_profile_to_env.
                   15810: 
                   15811: =cut
                   15812: 
                   15813: ############################################################
                   15814: ############################################################
1.152     albertel 15815: my $uniq=0;
1.136     matthew  15816: sub get_cgi_id {
1.154     albertel 15817:     $uniq=($uniq+1)%100000;
1.280     albertel 15818:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15819: }
                   15820: 
1.127     matthew  15821: ############################################################
                   15822: ############################################################
                   15823: 
                   15824: =pod
                   15825: 
1.648     raeburn  15826: =item * &DrawBarGraph()
1.127     matthew  15827: 
1.138     matthew  15828: Facilitates the plotting of data in a (stacked) bar graph.
                   15829: Puts plot definition data into the users environment in order for 
                   15830: graph.png to plot it.  Returns an <img> tag for the plot.
                   15831: The bars on the plot are labeled '1','2',...,'n'.
                   15832: 
                   15833: Inputs:
                   15834: 
                   15835: =over 4
                   15836: 
                   15837: =item $Title: string, the title of the plot
                   15838: 
                   15839: =item $xlabel: string, text describing the X-axis of the plot
                   15840: 
                   15841: =item $ylabel: string, text describing the Y-axis of the plot
                   15842: 
                   15843: =item $Max: scalar, the maximum Y value to use in the plot
                   15844: If $Max is < any data point, the graph will not be rendered.
                   15845: 
1.140     matthew  15846: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15847: they are plotted.  If undefined, default values will be used.
                   15848: 
1.178     matthew  15849: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15850: 
1.138     matthew  15851: =item @Values: An array of array references.  Each array reference holds data
                   15852: to be plotted in a stacked bar chart.
                   15853: 
1.239     matthew  15854: =item If the final element of @Values is a hash reference the key/value
                   15855: pairs will be added to the graph definition.
                   15856: 
1.138     matthew  15857: =back
                   15858: 
                   15859: Returns:
                   15860: 
                   15861: An <img> tag which references graph.png and the appropriate identifying
                   15862: information for the plot.
                   15863: 
1.127     matthew  15864: =cut
                   15865: 
                   15866: ############################################################
                   15867: ############################################################
1.134     matthew  15868: sub DrawBarGraph {
1.178     matthew  15869:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15870:     #
                   15871:     if (! defined($colors)) {
                   15872:         $colors = ['#33ff00', 
                   15873:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15874:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15875:                   ]; 
                   15876:     }
1.228     matthew  15877:     my $extra_settings = {};
                   15878:     if (ref($Values[-1]) eq 'HASH') {
                   15879:         $extra_settings = pop(@Values);
                   15880:     }
1.127     matthew  15881:     #
1.136     matthew  15882:     my $identifier = &get_cgi_id();
                   15883:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15884:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15885:         return '';
                   15886:     }
1.225     matthew  15887:     #
                   15888:     my @Labels;
                   15889:     if (defined($labels)) {
                   15890:         @Labels = @$labels;
                   15891:     } else {
                   15892:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15893:             push(@Labels,$i+1);
1.225     matthew  15894:         }
                   15895:     }
                   15896:     #
1.129     matthew  15897:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15898:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15899:     my %ValuesHash;
                   15900:     my $NumSets=1;
                   15901:     foreach my $array (@Values) {
                   15902:         next if (! ref($array));
1.136     matthew  15903:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15904:             join(',',@$array);
1.129     matthew  15905:     }
1.127     matthew  15906:     #
1.136     matthew  15907:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15908:     if ($NumBars < 3) {
                   15909:         $width = 120+$NumBars*32;
1.220     matthew  15910:         $xskip = 1;
1.225     matthew  15911:         $bar_width = 30;
                   15912:     } elsif ($NumBars < 5) {
                   15913:         $width = 120+$NumBars*20;
                   15914:         $xskip = 1;
                   15915:         $bar_width = 20;
1.220     matthew  15916:     } elsif ($NumBars < 10) {
1.136     matthew  15917:         $width = 120+$NumBars*15;
                   15918:         $xskip = 1;
                   15919:         $bar_width = 15;
                   15920:     } elsif ($NumBars <= 25) {
                   15921:         $width = 120+$NumBars*11;
                   15922:         $xskip = 5;
                   15923:         $bar_width = 8;
                   15924:     } elsif ($NumBars <= 50) {
                   15925:         $width = 120+$NumBars*8;
                   15926:         $xskip = 5;
                   15927:         $bar_width = 4;
                   15928:     } else {
                   15929:         $width = 120+$NumBars*8;
                   15930:         $xskip = 5;
                   15931:         $bar_width = 4;
                   15932:     }
                   15933:     #
1.137     matthew  15934:     $Max = 1 if ($Max < 1);
                   15935:     if ( int($Max) < $Max ) {
                   15936:         $Max++;
                   15937:         $Max = int($Max);
                   15938:     }
1.127     matthew  15939:     $Title  = '' if (! defined($Title));
                   15940:     $xlabel = '' if (! defined($xlabel));
                   15941:     $ylabel = '' if (! defined($ylabel));
1.369     www      15942:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15943:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15944:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15945:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15946:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15947:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15948:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15949:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15950:     $ValuesHash{$id.'.height'}   = $height;
                   15951:     $ValuesHash{$id.'.width'}    = $width;
                   15952:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15953:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15954:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15955:     #
1.228     matthew  15956:     # Deal with other parameters
                   15957:     while (my ($key,$value) = each(%$extra_settings)) {
                   15958:         $ValuesHash{$id.'.'.$key} = $value;
                   15959:     }
                   15960:     #
1.646     raeburn  15961:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15962:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15963: }
                   15964: 
                   15965: ############################################################
                   15966: ############################################################
                   15967: 
                   15968: =pod
                   15969: 
1.648     raeburn  15970: =item * &DrawXYGraph()
1.137     matthew  15971: 
1.138     matthew  15972: Facilitates the plotting of data in an XY graph.
                   15973: Puts plot definition data into the users environment in order for 
                   15974: graph.png to plot it.  Returns an <img> tag for the plot.
                   15975: 
                   15976: Inputs:
                   15977: 
                   15978: =over 4
                   15979: 
                   15980: =item $Title: string, the title of the plot
                   15981: 
                   15982: =item $xlabel: string, text describing the X-axis of the plot
                   15983: 
                   15984: =item $ylabel: string, text describing the Y-axis of the plot
                   15985: 
                   15986: =item $Max: scalar, the maximum Y value to use in the plot
                   15987: If $Max is < any data point, the graph will not be rendered.
                   15988: 
                   15989: =item $colors: Array ref containing the hex color codes for the data to be 
                   15990: plotted in.  If undefined, default values will be used.
                   15991: 
                   15992: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15993: 
                   15994: =item $Ydata: Array ref containing Array refs.  
1.185     www      15995: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15996: 
                   15997: =item %Values: hash indicating or overriding any default values which are 
                   15998: passed to graph.png.  
                   15999: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   16000: 
                   16001: =back
                   16002: 
                   16003: Returns:
                   16004: 
                   16005: An <img> tag which references graph.png and the appropriate identifying
                   16006: information for the plot.
                   16007: 
1.137     matthew  16008: =cut
                   16009: 
                   16010: ############################################################
                   16011: ############################################################
                   16012: sub DrawXYGraph {
                   16013:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   16014:     #
                   16015:     # Create the identifier for the graph
                   16016:     my $identifier = &get_cgi_id();
                   16017:     my $id = 'cgi.'.$identifier;
                   16018:     #
                   16019:     $Title  = '' if (! defined($Title));
                   16020:     $xlabel = '' if (! defined($xlabel));
                   16021:     $ylabel = '' if (! defined($ylabel));
                   16022:     my %ValuesHash = 
                   16023:         (
1.369     www      16024:          $id.'.title'  => &escape($Title),
                   16025:          $id.'.xlabel' => &escape($xlabel),
                   16026:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  16027:          $id.'.y_max_value'=> $Max,
                   16028:          $id.'.labels'     => join(',',@$Xlabels),
                   16029:          $id.'.PlotType'   => 'XY',
                   16030:          );
                   16031:     #
                   16032:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16033:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16034:     }
                   16035:     #
                   16036:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   16037:         return '';
                   16038:     }
                   16039:     my $NumSets=1;
1.138     matthew  16040:     foreach my $array (@{$Ydata}){
1.137     matthew  16041:         next if (! ref($array));
                   16042:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   16043:     }
1.138     matthew  16044:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  16045:     #
                   16046:     # Deal with other parameters
                   16047:     while (my ($key,$value) = each(%Values)) {
                   16048:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  16049:     }
                   16050:     #
1.646     raeburn  16051:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  16052:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   16053: }
                   16054: 
                   16055: ############################################################
                   16056: ############################################################
                   16057: 
                   16058: =pod
                   16059: 
1.648     raeburn  16060: =item * &DrawXYYGraph()
1.138     matthew  16061: 
                   16062: Facilitates the plotting of data in an XY graph with two Y axes.
                   16063: Puts plot definition data into the users environment in order for 
                   16064: graph.png to plot it.  Returns an <img> tag for the plot.
                   16065: 
                   16066: Inputs:
                   16067: 
                   16068: =over 4
                   16069: 
                   16070: =item $Title: string, the title of the plot
                   16071: 
                   16072: =item $xlabel: string, text describing the X-axis of the plot
                   16073: 
                   16074: =item $ylabel: string, text describing the Y-axis of the plot
                   16075: 
                   16076: =item $colors: Array ref containing the hex color codes for the data to be 
                   16077: plotted in.  If undefined, default values will be used.
                   16078: 
                   16079: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   16080: 
                   16081: =item $Ydata1: The first data set
                   16082: 
                   16083: =item $Min1: The minimum value of the left Y-axis
                   16084: 
                   16085: =item $Max1: The maximum value of the left Y-axis
                   16086: 
                   16087: =item $Ydata2: The second data set
                   16088: 
                   16089: =item $Min2: The minimum value of the right Y-axis
                   16090: 
                   16091: =item $Max2: The maximum value of the left Y-axis
                   16092: 
                   16093: =item %Values: hash indicating or overriding any default values which are 
                   16094: passed to graph.png.  
                   16095: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   16096: 
                   16097: =back
                   16098: 
                   16099: Returns:
                   16100: 
                   16101: An <img> tag which references graph.png and the appropriate identifying
                   16102: information for the plot.
1.136     matthew  16103: 
                   16104: =cut
                   16105: 
                   16106: ############################################################
                   16107: ############################################################
1.137     matthew  16108: sub DrawXYYGraph {
                   16109:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   16110:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  16111:     #
                   16112:     # Create the identifier for the graph
                   16113:     my $identifier = &get_cgi_id();
                   16114:     my $id = 'cgi.'.$identifier;
                   16115:     #
                   16116:     $Title  = '' if (! defined($Title));
                   16117:     $xlabel = '' if (! defined($xlabel));
                   16118:     $ylabel = '' if (! defined($ylabel));
                   16119:     my %ValuesHash = 
                   16120:         (
1.369     www      16121:          $id.'.title'  => &escape($Title),
                   16122:          $id.'.xlabel' => &escape($xlabel),
                   16123:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  16124:          $id.'.labels' => join(',',@$Xlabels),
                   16125:          $id.'.PlotType' => 'XY',
                   16126:          $id.'.NumSets' => 2,
1.137     matthew  16127:          $id.'.two_axes' => 1,
                   16128:          $id.'.y1_max_value' => $Max1,
                   16129:          $id.'.y1_min_value' => $Min1,
                   16130:          $id.'.y2_max_value' => $Max2,
                   16131:          $id.'.y2_min_value' => $Min2,
1.136     matthew  16132:          );
                   16133:     #
1.137     matthew  16134:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16135:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16136:     }
                   16137:     #
                   16138:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   16139:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  16140:         return '';
                   16141:     }
                   16142:     my $NumSets=1;
1.137     matthew  16143:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  16144:         next if (! ref($array));
                   16145:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  16146:     }
                   16147:     #
                   16148:     # Deal with other parameters
                   16149:     while (my ($key,$value) = each(%Values)) {
                   16150:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  16151:     }
                   16152:     #
1.646     raeburn  16153:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 16154:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  16155: }
                   16156: 
                   16157: ############################################################
                   16158: ############################################################
                   16159: 
                   16160: =pod
                   16161: 
1.157     matthew  16162: =back 
                   16163: 
1.139     matthew  16164: =head1 Statistics helper routines?  
                   16165: 
                   16166: Bad place for them but what the hell.
                   16167: 
1.157     matthew  16168: =over 4
                   16169: 
1.648     raeburn  16170: =item * &chartlink()
1.139     matthew  16171: 
                   16172: Returns a link to the chart for a specific student.  
                   16173: 
                   16174: Inputs:
                   16175: 
                   16176: =over 4
                   16177: 
                   16178: =item $linktext: The text of the link
                   16179: 
                   16180: =item $sname: The students username
                   16181: 
                   16182: =item $sdomain: The students domain
                   16183: 
                   16184: =back
                   16185: 
1.157     matthew  16186: =back
                   16187: 
1.139     matthew  16188: =cut
                   16189: 
                   16190: ############################################################
                   16191: ############################################################
                   16192: sub chartlink {
                   16193:     my ($linktext, $sname, $sdomain) = @_;
                   16194:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      16195:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 16196:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  16197:        '">'.$linktext.'</a>';
1.153     matthew  16198: }
                   16199: 
                   16200: #######################################################
                   16201: #######################################################
                   16202: 
                   16203: =pod
                   16204: 
                   16205: =head1 Course Environment Routines
1.157     matthew  16206: 
                   16207: =over 4
1.153     matthew  16208: 
1.648     raeburn  16209: =item * &restore_course_settings()
1.153     matthew  16210: 
1.648     raeburn  16211: =item * &store_course_settings()
1.153     matthew  16212: 
                   16213: Restores/Store indicated form parameters from the course environment.
                   16214: Will not overwrite existing values of the form parameters.
                   16215: 
                   16216: Inputs: 
                   16217: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   16218: 
                   16219: a hash ref describing the data to be stored.  For example:
                   16220:    
                   16221: %Save_Parameters = ('Status' => 'scalar',
                   16222:     'chartoutputmode' => 'scalar',
                   16223:     'chartoutputdata' => 'scalar',
                   16224:     'Section' => 'array',
1.373     raeburn  16225:     'Group' => 'array',
1.153     matthew  16226:     'StudentData' => 'array',
                   16227:     'Maps' => 'array');
                   16228: 
                   16229: Returns: both routines return nothing
                   16230: 
1.631     raeburn  16231: =back
                   16232: 
1.153     matthew  16233: =cut
                   16234: 
                   16235: #######################################################
                   16236: #######################################################
                   16237: sub store_course_settings {
1.496     albertel 16238:     return &store_settings($env{'request.course.id'},@_);
                   16239: }
                   16240: 
                   16241: sub store_settings {
1.153     matthew  16242:     # save to the environment
                   16243:     # appenv the same items, just to be safe
1.300     albertel 16244:     my $udom  = $env{'user.domain'};
                   16245:     my $uname = $env{'user.name'};
1.496     albertel 16246:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16247:     my %SaveHash;
                   16248:     my %AppHash;
                   16249:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 16250:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 16251:         my $envname = 'environment.'.$basename;
1.258     albertel 16252:         if (exists($env{'form.'.$setting})) {
1.153     matthew  16253:             # Save this value away
                   16254:             if ($type eq 'scalar' &&
1.258     albertel 16255:                 (! exists($env{$envname}) || 
                   16256:                  $env{$envname} ne $env{'form.'.$setting})) {
                   16257:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   16258:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  16259:             } elsif ($type eq 'array') {
                   16260:                 my $stored_form;
1.258     albertel 16261:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  16262:                     $stored_form = join(',',
                   16263:                                         map {
1.369     www      16264:                                             &escape($_);
1.258     albertel 16265:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  16266:                 } else {
                   16267:                     $stored_form = 
1.369     www      16268:                         &escape($env{'form.'.$setting});
1.153     matthew  16269:                 }
                   16270:                 # Determine if the array contents are the same.
1.258     albertel 16271:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  16272:                     $SaveHash{$basename} = $stored_form;
                   16273:                     $AppHash{$envname}   = $stored_form;
                   16274:                 }
                   16275:             }
                   16276:         }
                   16277:     }
                   16278:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 16279:                                           $udom,$uname);
1.153     matthew  16280:     if ($put_result !~ /^(ok|delayed)/) {
                   16281:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   16282:                                  'got error:'.$put_result);
                   16283:     }
                   16284:     # Make sure these settings stick around in this session, too
1.646     raeburn  16285:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  16286:     return;
                   16287: }
                   16288: 
                   16289: sub restore_course_settings {
1.499     albertel 16290:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 16291: }
                   16292: 
                   16293: sub restore_settings {
                   16294:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16295:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 16296:         next if (exists($env{'form.'.$setting}));
1.496     albertel 16297:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  16298:             '.'.$setting;
1.258     albertel 16299:         if (exists($env{$envname})) {
1.153     matthew  16300:             if ($type eq 'scalar') {
1.258     albertel 16301:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  16302:             } elsif ($type eq 'array') {
1.258     albertel 16303:                 $env{'form.'.$setting} = [ 
1.153     matthew  16304:                                            map { 
1.369     www      16305:                                                &unescape($_); 
1.258     albertel 16306:                                            } split(',',$env{$envname})
1.153     matthew  16307:                                            ];
                   16308:             }
                   16309:         }
                   16310:     }
1.127     matthew  16311: }
                   16312: 
1.618     raeburn  16313: #######################################################
                   16314: #######################################################
                   16315: 
                   16316: =pod
                   16317: 
                   16318: =head1 Domain E-mail Routines  
                   16319: 
                   16320: =over 4
                   16321: 
1.648     raeburn  16322: =item * &build_recipient_list()
1.618     raeburn  16323: 
1.1144    raeburn  16324: Build recipient lists for following types of e-mail:
1.766     raeburn  16325: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  16326: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   16327: module change checking, student/employee ID conflict checks, as
                   16328: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   16329: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  16330: 
                   16331: Inputs:
1.619     raeburn  16332: defmail (scalar - email address of default recipient), 
1.1144    raeburn  16333: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   16334: requestsmail, updatesmail, or idconflictsmail).
                   16335: 
1.619     raeburn  16336: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  16337: 
1.619     raeburn  16338: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  16339: i.e., predates configuration by DC via domainprefs.pm
                   16340: 
                   16341: $requname username of requester (if mailing type is helpdeskmail)
                   16342: 
                   16343: $requdom domain of requester (if mailing type is helpdeskmail)
                   16344: 
                   16345: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   16346: 
1.618     raeburn  16347: 
1.655     raeburn  16348: Returns: comma separated list of addresses to which to send e-mail.
                   16349: 
                   16350: =back
1.618     raeburn  16351: 
                   16352: =cut
                   16353: 
                   16354: ############################################################
                   16355: ############################################################
                   16356: sub build_recipient_list {
1.1297    raeburn  16357:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  16358:     my @recipients;
1.1270    raeburn  16359:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  16360:     my %domconfig =
1.1270    raeburn  16361:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  16362:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  16363:         if (exists($domconfig{'contacts'}{$mailing})) {
                   16364:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   16365:                 my @contacts = ('adminemail','supportemail');
                   16366:                 foreach my $item (@contacts) {
                   16367:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   16368:                         my $addr = $domconfig{'contacts'}{$item}; 
                   16369:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16370:                             push(@recipients,$addr);
                   16371:                         }
1.619     raeburn  16372:                     }
1.1270    raeburn  16373:                 }
                   16374:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   16375:                 if ($mailing eq 'helpdeskmail') {
                   16376:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   16377:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   16378:                         my @ok_bccs;
                   16379:                         foreach my $bcc (@bccs) {
                   16380:                             $bcc =~ s/^\s+//g;
                   16381:                             $bcc =~ s/\s+$//g;
                   16382:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16383:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16384:                                     push(@ok_bccs,$bcc);
                   16385:                                 }
                   16386:                             }
                   16387:                         }
                   16388:                         if (@ok_bccs > 0) {
                   16389:                             $allbcc = join(', ',@ok_bccs);
                   16390:                         }
                   16391:                     }
                   16392:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  16393:                 }
                   16394:             }
1.766     raeburn  16395:         } elsif ($origmail ne '') {
1.1270    raeburn  16396:             $lastresort = $origmail;
1.618     raeburn  16397:         }
1.1297    raeburn  16398:         if ($mailing eq 'helpdeskmail') {
                   16399:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   16400:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   16401:                 my ($inststatus,$inststatus_checked);
                   16402:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   16403:                     ($env{'user.domain'} ne 'public')) {
                   16404:                     $inststatus_checked = 1;
                   16405:                     $inststatus = $env{'environment.inststatus'};
                   16406:                 }
                   16407:                 unless ($inststatus_checked) {
                   16408:                     if (($requname ne '') && ($requdom ne '')) {
                   16409:                         if (($requname =~ /^$match_username$/) &&
                   16410:                             ($requdom =~ /^$match_domain$/) &&
                   16411:                             (&Apache::lonnet::domain($requdom))) {
                   16412:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   16413:                                                                       $requdom);
                   16414:                             unless ($requhome eq 'no_host') {
                   16415:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   16416:                                 $inststatus = $userenv{'inststatus'};
                   16417:                                 $inststatus_checked = 1;
                   16418:                             }
                   16419:                         }
                   16420:                     }
                   16421:                 }
                   16422:                 unless ($inststatus_checked) {
                   16423:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   16424:                         my %srch = (srchby     => 'email',
                   16425:                                     srchdomain => $defdom,
                   16426:                                     srchterm   => $reqemail,
                   16427:                                     srchtype   => 'exact');
                   16428:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   16429:                         foreach my $uname (keys(%srch_results)) {
                   16430:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16431:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16432:                                 $inststatus_checked = 1;
                   16433:                                 last;
                   16434:                             }
                   16435:                         }
                   16436:                         unless ($inststatus_checked) {
                   16437:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   16438:                             if ($dirsrchres eq 'ok') {
                   16439:                                 foreach my $uname (keys(%srch_results)) {
                   16440:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16441:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16442:                                         $inststatus_checked = 1;
                   16443:                                         last;
                   16444:                                     }
                   16445:                                 }
                   16446:                             }
                   16447:                         }
                   16448:                     }
                   16449:                 }
                   16450:                 if ($inststatus ne '') {
                   16451:                     foreach my $status (split(/\:/,$inststatus)) {
                   16452:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   16453:                             my @contacts = ('adminemail','supportemail');
                   16454:                             foreach my $item (@contacts) {
                   16455:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   16456:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   16457:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16458:                                         push(@recipients,$addr);
                   16459:                                     }
                   16460:                                 }
                   16461:                             }
                   16462:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   16463:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   16464:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   16465:                                 my @ok_bccs;
                   16466:                                 foreach my $bcc (@bccs) {
                   16467:                                     $bcc =~ s/^\s+//g;
                   16468:                                     $bcc =~ s/\s+$//g;
                   16469:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16470:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16471:                                             push(@ok_bccs,$bcc);
                   16472:                                         }
                   16473:                                     }
                   16474:                                 }
                   16475:                                 if (@ok_bccs > 0) {
                   16476:                                     $allbcc = join(', ',@ok_bccs);
                   16477:                                 }
                   16478:                             }
                   16479:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   16480:                             last;
                   16481:                         }
                   16482:                     }
                   16483:                 }
                   16484:             }
                   16485:         }
1.619     raeburn  16486:     } elsif ($origmail ne '') {
1.1270    raeburn  16487:         $lastresort = $origmail;
                   16488:     }
1.1297    raeburn  16489:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  16490:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   16491:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   16492:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   16493:             my %what = (
                   16494:                           perlvar => 1,
                   16495:                        );
                   16496:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   16497:             if ($primary) {
                   16498:                 my $gotaddr;
                   16499:                 my ($result,$returnhash) =
                   16500:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   16501:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   16502:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   16503:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   16504:                         $gotaddr = 1;
                   16505:                     }
                   16506:                 }
                   16507:                 unless ($gotaddr) {
                   16508:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   16509:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   16510:                     unless ($uintdom eq $intdom) {
                   16511:                         my %domconfig =
                   16512:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   16513:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   16514:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   16515:                                 my @contacts = ('adminemail','supportemail');
                   16516:                                 foreach my $item (@contacts) {
                   16517:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   16518:                                         my $addr = $domconfig{'contacts'}{$item};
                   16519:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16520:                                             push(@recipients,$addr);
                   16521:                                         }
                   16522:                                     }
                   16523:                                 }
                   16524:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   16525:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   16526:                                 }
                   16527:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   16528:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   16529:                                     my @ok_bccs;
                   16530:                                     foreach my $bcc (@bccs) {
                   16531:                                         $bcc =~ s/^\s+//g;
                   16532:                                         $bcc =~ s/\s+$//g;
                   16533:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16534:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16535:                                                 push(@ok_bccs,$bcc);
                   16536:                                             }
                   16537:                                         }
                   16538:                                     }
                   16539:                                     if (@ok_bccs > 0) {
                   16540:                                         $allbcc = join(', ',@ok_bccs);
                   16541:                                     }
                   16542:                                 }
                   16543:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   16544:                             }
                   16545:                         }
                   16546:                     }
                   16547:                 }
                   16548:             }
                   16549:         }
1.618     raeburn  16550:     }
1.688     raeburn  16551:     if (defined($defmail)) {
                   16552:         if ($defmail ne '') {
                   16553:             push(@recipients,$defmail);
                   16554:         }
1.618     raeburn  16555:     }
                   16556:     if ($otheremails) {
1.619     raeburn  16557:         my @others;
                   16558:         if ($otheremails =~ /,/) {
                   16559:             @others = split(/,/,$otheremails);
1.618     raeburn  16560:         } else {
1.619     raeburn  16561:             push(@others,$otheremails);
                   16562:         }
                   16563:         foreach my $addr (@others) {
                   16564:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16565:                 push(@recipients,$addr);
                   16566:             }
1.618     raeburn  16567:         }
                   16568:     }
1.1298    raeburn  16569:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  16570:         if ((!@recipients) && ($lastresort ne '')) {
                   16571:             push(@recipients,$lastresort);
                   16572:         }
                   16573:     } elsif ($lastresort ne '') {
                   16574:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   16575:             push(@recipients,$lastresort);
                   16576:         }
                   16577:     }
1.1271    raeburn  16578:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  16579:     if (wantarray) {
                   16580:         return ($recipientlist,$allbcc,$addtext);
                   16581:     } else {
                   16582:         return $recipientlist;
                   16583:     }
1.618     raeburn  16584: }
                   16585: 
1.127     matthew  16586: ############################################################
                   16587: ############################################################
1.154     albertel 16588: 
1.655     raeburn  16589: =pod
                   16590: 
1.1224    musolffc 16591: =over 4
                   16592: 
1.1223    musolffc 16593: =item * &mime_email()
                   16594: 
                   16595: Sends an email with a possible attachment
                   16596: 
                   16597: Inputs:
                   16598: 
                   16599: =over 4
                   16600: 
                   16601: from -              Sender's email address
                   16602: 
1.1343    raeburn  16603: replyto -           Reply-To email address
                   16604: 
1.1223    musolffc 16605: to -                Email address of recipient
                   16606: 
                   16607: subject -           Subject of email
                   16608: 
                   16609: body -              Body of email
                   16610: 
                   16611: cc_string -         Carbon copy email address
                   16612: 
                   16613: bcc -               Blind carbon copy email address
                   16614: 
                   16615: attachment_path -   Path of file to be attached
                   16616: 
                   16617: file_name -         Name of file to be attached
                   16618: 
                   16619: attachment_text -   The body of an attachment of type "TEXT"
                   16620: 
                   16621: =back
                   16622: 
                   16623: =back
                   16624: 
                   16625: =cut
                   16626: 
                   16627: ############################################################
                   16628: ############################################################
                   16629: 
                   16630: sub mime_email {
1.1343    raeburn  16631:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   16632:         $file_name,$attachment_text) = @_;
                   16633:  
1.1223    musolffc 16634:     my $msg = MIME::Lite->new(
                   16635:              From    => $from,
                   16636:              To      => $to,
                   16637:              Subject => $subject,
                   16638:              Type    =>'TEXT',
                   16639:              Data    => $body,
                   16640:              );
1.1343    raeburn  16641:     if ($replyto ne '') {
                   16642:         $msg->add("Reply-To" => $replyto);
                   16643:     }
1.1223    musolffc 16644:     if ($cc_string ne '') {
                   16645:         $msg->add("Cc" => $cc_string);
                   16646:     }
                   16647:     if ($bcc ne '') {
                   16648:         $msg->add("Bcc" => $bcc);
                   16649:     }
                   16650:     $msg->attr("content-type"         => "text/plain");
                   16651:     $msg->attr("content-type.charset" => "UTF-8");
                   16652:     # Attach file if given
                   16653:     if ($attachment_path) {
                   16654:         unless ($file_name) {
                   16655:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   16656:         }
                   16657:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   16658:         $msg->attach(Type     => $type,
                   16659:                      Path     => $attachment_path,
                   16660:                      Filename => $file_name
                   16661:                      );
                   16662:     # Otherwise attach text if given
                   16663:     } elsif ($attachment_text) {
                   16664:         $msg->attach(Type => 'TEXT',
                   16665:                      Data => $attachment_text);
                   16666:     }
                   16667:     # Send it
                   16668:     $msg->send('sendmail');
                   16669: }
                   16670: 
                   16671: ############################################################
                   16672: ############################################################
                   16673: 
                   16674: =pod
                   16675: 
1.655     raeburn  16676: =head1 Course Catalog Routines
                   16677: 
                   16678: =over 4
                   16679: 
                   16680: =item * &gather_categories()
                   16681: 
                   16682: Converts category definitions - keys of categories hash stored in  
                   16683: coursecategories in configuration.db on the primary library server in a 
                   16684: domain - to an array.  Also generates javascript and idx hash used to 
                   16685: generate Domain Coordinator interface for editing Course Categories.
                   16686: 
                   16687: Inputs:
1.663     raeburn  16688: 
1.655     raeburn  16689: categories (reference to hash of category definitions).
1.663     raeburn  16690: 
1.655     raeburn  16691: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16692:       categories and subcategories).
1.663     raeburn  16693: 
1.655     raeburn  16694: idx (reference to hash of counters used in Domain Coordinator interface for 
                   16695:       editing Course Categories).
1.663     raeburn  16696: 
1.655     raeburn  16697: jsarray (reference to array of categories used to create Javascript arrays for
                   16698:          Domain Coordinator interface for editing Course Categories).
                   16699: 
                   16700: Returns: nothing
                   16701: 
                   16702: Side effects: populates cats, idx and jsarray. 
                   16703: 
                   16704: =cut
                   16705: 
                   16706: sub gather_categories {
                   16707:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16708:     my %counters;
                   16709:     my $num = 0;
                   16710:     foreach my $item (keys(%{$categories})) {
                   16711:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16712:         if ($container eq '' && $depth == 0) {
                   16713:             $cats->[$depth][$categories->{$item}] = $cat;
                   16714:         } else {
                   16715:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16716:         }
                   16717:         my ($escitem,$tail) = split(/:/,$item,2);
                   16718:         if ($counters{$tail} eq '') {
                   16719:             $counters{$tail} = $num;
                   16720:             $num ++;
                   16721:         }
                   16722:         if (ref($idx) eq 'HASH') {
                   16723:             $idx->{$item} = $counters{$tail};
                   16724:         }
                   16725:         if (ref($jsarray) eq 'ARRAY') {
                   16726:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16727:         }
                   16728:     }
                   16729:     return;
                   16730: }
                   16731: 
                   16732: =pod
                   16733: 
                   16734: =item * &extract_categories()
                   16735: 
                   16736: Used to generate breadcrumb trails for course categories.
                   16737: 
                   16738: Inputs:
1.663     raeburn  16739: 
1.655     raeburn  16740: categories (reference to hash of category definitions).
1.663     raeburn  16741: 
1.655     raeburn  16742: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16743:       categories and subcategories).
1.663     raeburn  16744: 
1.655     raeburn  16745: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16746: 
1.655     raeburn  16747: allitems (reference to hash - key is category key 
                   16748:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16749: 
1.655     raeburn  16750: idx (reference to hash of counters used in Domain Coordinator interface for
                   16751:       editing Course Categories).
1.663     raeburn  16752: 
1.655     raeburn  16753: jsarray (reference to array of categories used to create Javascript arrays for
                   16754:          Domain Coordinator interface for editing Course Categories).
                   16755: 
1.665     raeburn  16756: subcats (reference to hash of arrays containing all subcategories within each 
                   16757:          category, -recursive)
                   16758: 
1.1321    raeburn  16759: maxd (reference to hash used to hold max depth for all top-level categories).
                   16760: 
1.655     raeburn  16761: Returns: nothing
                   16762: 
                   16763: Side effects: populates trails and allitems hash references.
                   16764: 
                   16765: =cut
                   16766: 
                   16767: sub extract_categories {
1.1321    raeburn  16768:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16769:     if (ref($categories) eq 'HASH') {
                   16770:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16771:         if (ref($cats->[0]) eq 'ARRAY') {
                   16772:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16773:                 my $name = $cats->[0][$i];
                   16774:                 my $item = &escape($name).'::0';
                   16775:                 my $trailstr;
                   16776:                 if ($name eq 'instcode') {
                   16777:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16778:                 } elsif ($name eq 'communities') {
                   16779:                     $trailstr = &mt('Communities');
1.1239    raeburn  16780:                 } elsif ($name eq 'placement') {
                   16781:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16782:                 } else {
                   16783:                     $trailstr = $name;
                   16784:                 }
                   16785:                 if ($allitems->{$item} eq '') {
                   16786:                     push(@{$trails},$trailstr);
                   16787:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16788:                 }
                   16789:                 my @parents = ($name);
                   16790:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16791:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16792:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16793:                         if (ref($subcats) eq 'HASH') {
                   16794:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16795:                         }
1.1321    raeburn  16796:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16797:                     }
                   16798:                 } else {
                   16799:                     if (ref($subcats) eq 'HASH') {
                   16800:                         $subcats->{$item} = [];
1.655     raeburn  16801:                     }
1.1321    raeburn  16802:                     if (ref($maxd) eq 'HASH') {
                   16803:                         $maxd->{$name} = 1;
                   16804:                     }
1.655     raeburn  16805:                 }
                   16806:             }
                   16807:         }
                   16808:     }
                   16809:     return;
                   16810: }
                   16811: 
                   16812: =pod
                   16813: 
1.1162    raeburn  16814: =item * &recurse_categories()
1.655     raeburn  16815: 
                   16816: Recursively used to generate breadcrumb trails for course categories.
                   16817: 
                   16818: Inputs:
1.663     raeburn  16819: 
1.655     raeburn  16820: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16821:       categories and subcategories).
1.663     raeburn  16822: 
1.655     raeburn  16823: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16824: 
                   16825: category (current course category, for which breadcrumb trail is being generated).
                   16826: 
                   16827: trails (reference to array of breadcrumb trails for each category).
                   16828: 
1.655     raeburn  16829: allitems (reference to hash - key is category key
                   16830:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16831: 
1.655     raeburn  16832: parents (array containing containers directories for current category, 
                   16833:          back to top level). 
                   16834: 
                   16835: Returns: nothing
                   16836: 
                   16837: Side effects: populates trails and allitems hash references
                   16838: 
                   16839: =cut
                   16840: 
                   16841: sub recurse_categories {
1.1321    raeburn  16842:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16843:     my $shallower = $depth - 1;
                   16844:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16845:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16846:             my $name = $cats->[$depth]{$category}[$k];
                   16847:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16848:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16849:             if ($allitems->{$item} eq '') {
                   16850:                 push(@{$trails},$trailstr);
                   16851:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16852:             }
                   16853:             my $deeper = $depth+1;
                   16854:             push(@{$parents},$category);
1.665     raeburn  16855:             if (ref($subcats) eq 'HASH') {
                   16856:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16857:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16858:                     my $higher;
                   16859:                     if ($j > 0) {
                   16860:                         $higher = &escape($parents->[$j]).':'.
                   16861:                                   &escape($parents->[$j-1]).':'.$j;
                   16862:                     } else {
                   16863:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16864:                     }
                   16865:                     push(@{$subcats->{$higher}},$subcat);
                   16866:                 }
                   16867:             }
                   16868:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16869:                                 $subcats,$maxd);
1.655     raeburn  16870:             pop(@{$parents});
                   16871:         }
                   16872:     } else {
                   16873:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16874:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16875:         if ($allitems->{$item} eq '') {
                   16876:             push(@{$trails},$trailstr);
                   16877:             $allitems->{$item} = scalar(@{$trails})-1;
                   16878:         }
1.1321    raeburn  16879:         if (ref($maxd) eq 'HASH') {
                   16880:             if ($depth > $maxd->{$parents->[0]}) {
                   16881:                 $maxd->{$parents->[0]} = $depth;
                   16882:             }
                   16883:         }
1.655     raeburn  16884:     }
                   16885:     return;
                   16886: }
                   16887: 
1.663     raeburn  16888: =pod
                   16889: 
1.1162    raeburn  16890: =item * &assign_categories_table()
1.663     raeburn  16891: 
                   16892: Create a datatable for display of hierarchical categories in a domain,
                   16893: with checkboxes to allow a course to be categorized. 
                   16894: 
                   16895: Inputs:
                   16896: 
                   16897: cathash - reference to hash of categories defined for the domain (from
                   16898:           configuration.db)
                   16899: 
                   16900: currcat - scalar with an & separated list of categories assigned to a course. 
                   16901: 
1.919     raeburn  16902: type    - scalar contains course type (Course or Community).
                   16903: 
1.1260    raeburn  16904: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16905:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16906: 
1.663     raeburn  16907: Returns: $output (markup to be displayed) 
                   16908: 
                   16909: =cut
                   16910: 
                   16911: sub assign_categories_table {
1.1259    raeburn  16912:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16913:     my $output;
                   16914:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16915:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16916:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16917:         $maxdepth = scalar(@cats);
                   16918:         if (@cats > 0) {
                   16919:             my $itemcount = 0;
                   16920:             if (ref($cats[0]) eq 'ARRAY') {
                   16921:                 my @currcategories;
                   16922:                 if ($currcat ne '') {
                   16923:                     @currcategories = split('&',$currcat);
                   16924:                 }
1.919     raeburn  16925:                 my $table;
1.663     raeburn  16926:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16927:                     my $parent = $cats[0][$i];
1.919     raeburn  16928:                     next if ($parent eq 'instcode');
                   16929:                     if ($type eq 'Community') {
                   16930:                         next unless ($parent eq 'communities');
1.1239    raeburn  16931:                     } elsif ($type eq 'Placement') {
                   16932:                         next unless ($parent eq 'placement');
1.919     raeburn  16933:                     } else {
1.1239    raeburn  16934:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16935:                     }
1.663     raeburn  16936:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16937:                     my $item = &escape($parent).'::0';
                   16938:                     my $checked = '';
                   16939:                     if (@currcategories > 0) {
                   16940:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16941:                             $checked = ' checked="checked"';
1.663     raeburn  16942:                         }
                   16943:                     }
1.919     raeburn  16944:                     my $parent_title = $parent;
                   16945:                     if ($parent eq 'communities') {
                   16946:                         $parent_title = &mt('Communities');
1.1239    raeburn  16947:                     } elsif ($parent eq 'placement') {
                   16948:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16949:                     }
                   16950:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16951:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16952:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16953:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16954:                     my $depth = 1;
                   16955:                     push(@path,$parent);
1.1259    raeburn  16956:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16957:                     pop(@path);
1.919     raeburn  16958:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16959:                     $itemcount ++;
                   16960:                 }
1.919     raeburn  16961:                 if ($itemcount) {
                   16962:                     $output = &Apache::loncommon::start_data_table().
                   16963:                               $table.
                   16964:                               &Apache::loncommon::end_data_table();
                   16965:                 }
1.663     raeburn  16966:             }
                   16967:         }
                   16968:     }
                   16969:     return $output;
                   16970: }
                   16971: 
                   16972: =pod
                   16973: 
1.1162    raeburn  16974: =item * &assign_category_rows()
1.663     raeburn  16975: 
                   16976: Create a datatable row for display of nested categories in a domain,
                   16977: with checkboxes to allow a course to be categorized,called recursively.
                   16978: 
                   16979: Inputs:
                   16980: 
                   16981: itemcount - track row number for alternating colors
                   16982: 
                   16983: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16984:       categories and subcategories.
                   16985: 
                   16986: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16987: 
                   16988: parent - parent of current category item
                   16989: 
                   16990: path - Array containing all categories back up through the hierarchy from the
                   16991:        current category to the top level.
                   16992: 
                   16993: currcategories - reference to array of current categories assigned to the course
                   16994: 
1.1260    raeburn  16995: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16996:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16997: 
1.663     raeburn  16998: Returns: $output (markup to be displayed).
                   16999: 
                   17000: =cut
                   17001: 
                   17002: sub assign_category_rows {
1.1259    raeburn  17003:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  17004:     my ($text,$name,$item,$chgstr);
                   17005:     if (ref($cats) eq 'ARRAY') {
                   17006:         my $maxdepth = scalar(@{$cats});
                   17007:         if (ref($cats->[$depth]) eq 'HASH') {
                   17008:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   17009:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   17010:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  17011:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  17012:                 for (my $j=0; $j<$numchildren; $j++) {
                   17013:                     $name = $cats->[$depth]{$parent}[$j];
                   17014:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   17015:                     my $deeper = $depth+1;
                   17016:                     my $checked = '';
                   17017:                     if (ref($currcategories) eq 'ARRAY') {
                   17018:                         if (@{$currcategories} > 0) {
                   17019:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   17020:                                 $checked = ' checked="checked"';
1.663     raeburn  17021:                             }
                   17022:                         }
                   17023:                     }
1.664     raeburn  17024:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   17025:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  17026:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  17027:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   17028:                              '</td><td>';
1.663     raeburn  17029:                     if (ref($path) eq 'ARRAY') {
                   17030:                         push(@{$path},$name);
1.1259    raeburn  17031:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  17032:                         pop(@{$path});
                   17033:                     }
                   17034:                     $text .= '</td></tr>';
                   17035:                 }
                   17036:                 $text .= '</table></td>';
                   17037:             }
                   17038:         }
                   17039:     }
                   17040:     return $text;
                   17041: }
                   17042: 
1.1181    raeburn  17043: =pod
                   17044: 
                   17045: =back
                   17046: 
                   17047: =cut
                   17048: 
1.655     raeburn  17049: ############################################################
                   17050: ############################################################
                   17051: 
                   17052: 
1.443     albertel 17053: sub commit_customrole {
1.1408    raeburn  17054:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
1.1399    raeburn  17055:     my $result = &Apache::lonnet::assigncustomrole(
1.1408    raeburn  17056:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
                   17057:                      $context,$othdomby,$requester);
1.630     raeburn  17058:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 17059:                          ($start?', '.&mt('starting').' '.localtime($start):'').
1.1399    raeburn  17060:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
                   17061:     if (wantarray) {
                   17062:         return ($output,$result);
                   17063:     } else {
                   17064:         return $output;
                   17065:     }
1.443     albertel 17066: }
                   17067: 
                   17068: sub commit_standardrole {
1.1408    raeburn  17069:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
                   17070:         $othdomby,$requester) = @_;
1.1399    raeburn  17071:     my ($output,$logmsg,$linefeed,$result);
1.541     raeburn  17072:     if ($context eq 'auto') {
                   17073:         $linefeed = "\n";
                   17074:     } else {
                   17075:         $linefeed = "<br />\n";
                   17076:     }  
1.443     albertel 17077:     if ($three eq 'st') {
1.1399    raeburn  17078:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1408    raeburn  17079:                                       $one,$two,$sec,$context,$credits,$othdomby,
                   17080:                                       $requester);
1.541     raeburn  17081:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  17082:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   17083:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 17084:         } else {
1.541     raeburn  17085:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 17086:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17087:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   17088:             if ($context eq 'auto') {
                   17089:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   17090:             } else {
                   17091:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   17092:                &mt('Add to classlist').': <b>ok</b>';
                   17093:             }
                   17094:             $output .= $linefeed;
1.443     albertel 17095:         }
                   17096:     } else {
                   17097:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   17098:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17099:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.1408    raeburn  17100:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
                   17101:                                               '','',$context,$othdomby,$requester);
1.541     raeburn  17102:         if ($context eq 'auto') {
                   17103:             $output .= $result.$linefeed;
                   17104:         } else {
                   17105:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   17106:         }
1.443     albertel 17107:     }
1.1399    raeburn  17108:     if (wantarray) {
                   17109:         return ($output,$result);
                   17110:     } else {
                   17111:         return $output;
                   17112:     }
1.443     albertel 17113: }
                   17114: 
                   17115: sub commit_studentrole {
1.1116    raeburn  17116:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
1.1408    raeburn  17117:         $credits,$othdomby,$requester) = @_;
1.626     raeburn  17118:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  17119:     if ($context eq 'auto') {
                   17120:         $linefeed = "\n";
                   17121:     } else {
                   17122:         $linefeed = '<br />'."\n";
                   17123:     }
1.443     albertel 17124:     if (defined($one) && defined($two)) {
                   17125:         my $cid=$one.'_'.$two;
                   17126:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   17127:         my $secchange = 0;
                   17128:         my $expire_role_result;
                   17129:         my $modify_section_result;
1.628     raeburn  17130:         if ($oldsec ne '-1') { 
                   17131:             if ($oldsec ne $sec) {
1.443     albertel 17132:                 $secchange = 1;
1.628     raeburn  17133:                 my $now = time;
1.443     albertel 17134:                 my $uurl='/'.$cid;
                   17135:                 $uurl=~s/\_/\//g;
                   17136:                 if ($oldsec) {
                   17137:                     $uurl.='/'.$oldsec;
                   17138:                 }
1.626     raeburn  17139:                 $oldsecurl = $uurl;
1.628     raeburn  17140:                 $expire_role_result = 
1.1408    raeburn  17141:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
                   17142:                                                 '','','',$context,$othdomby,$requester);
                   17143:                 if ($env{'request.course.sec'} ne '') {
1.628     raeburn  17144:                     if ($expire_role_result eq 'refused') {
                   17145:                         my @roles = ('st');
                   17146:                         my @statuses = ('previous');
                   17147:                         my @roledoms = ($one);
                   17148:                         my $withsec = 1;
                   17149:                         my %roleshash = 
                   17150:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   17151:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   17152:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   17153:                             my ($oldstart,$oldend) = 
                   17154:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   17155:                             if ($oldend > 0 && $oldend <= $now) {
                   17156:                                 $expire_role_result = 'ok';
                   17157:                             }
                   17158:                         }
                   17159:                     }
                   17160:                 }
1.443     albertel 17161:                 $result = $expire_role_result;
                   17162:             }
                   17163:         }
                   17164:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  17165:             $modify_section_result = 
                   17166:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   17167:                                                            undef,undef,undef,$sec,
                   17168:                                                            $end,$start,'','',$cid,
1.1408    raeburn  17169:                                                            '',$context,$credits,'',
                   17170:                                                            $othdomby,$requester);
1.443     albertel 17171:             if ($modify_section_result =~ /^ok/) {
                   17172:                 if ($secchange == 1) {
1.628     raeburn  17173:                     if ($sec eq '') {
                   17174:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   17175:                     } else {
                   17176:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   17177:                     }
1.443     albertel 17178:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  17179:                     if ($sec eq '') {
                   17180:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   17181:                     } else {
                   17182:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17183:                     }
1.443     albertel 17184:                 } else {
1.628     raeburn  17185:                     if ($sec eq '') {
                   17186:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   17187:                     } else {
                   17188:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17189:                     }
1.443     albertel 17190:                 }
                   17191:             } else {
1.1115    raeburn  17192:                 if ($secchange) { 
1.628     raeburn  17193:                     $$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;
                   17194:                 } else {
                   17195:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   17196:                 }
1.443     albertel 17197:             }
                   17198:             $result = $modify_section_result;
                   17199:         } elsif ($secchange == 1) {
1.628     raeburn  17200:             if ($oldsec eq '') {
1.1103    raeburn  17201:                 $$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  17202:             } else {
                   17203:                 $$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;
                   17204:             }
1.626     raeburn  17205:             if ($expire_role_result eq 'refused') {
                   17206:                 my $newsecurl = '/'.$cid;
                   17207:                 $newsecurl =~ s/\_/\//g;
                   17208:                 if ($sec ne '') {
                   17209:                     $newsecurl.='/'.$sec;
                   17210:                 }
                   17211:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   17212:                     if ($sec eq '') {
                   17213:                         $$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;
                   17214:                     } else {
                   17215:                         $$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;
                   17216:                     }
                   17217:                 }
                   17218:             }
1.443     albertel 17219:         }
                   17220:     } else {
1.626     raeburn  17221:         $$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 17222:         $result = "error: incomplete course id\n";
                   17223:     }
                   17224:     return $result;
                   17225: }
                   17226: 
1.1108    raeburn  17227: sub show_role_extent {
                   17228:     my ($scope,$context,$role) = @_;
                   17229:     $scope =~ s{^/}{};
                   17230:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   17231:     push(@courseroles,'co');
                   17232:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   17233:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   17234:         $scope =~ s{/}{_};
                   17235:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   17236:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   17237:         my ($audom,$auname) = split(/\//,$scope);
                   17238:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   17239:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   17240:     } else {
                   17241:         $scope =~ s{/$}{};
                   17242:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   17243:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   17244:     }
                   17245: }
                   17246: 
1.443     albertel 17247: ############################################################
                   17248: ############################################################
                   17249: 
1.566     albertel 17250: sub check_clone {
1.578     raeburn  17251:     my ($args,$linefeed) = @_;
1.566     albertel 17252:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   17253:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   17254:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  17255:     my $clonetitle;
                   17256:     my @clonemsg;
1.566     albertel 17257:     my $can_clone = 0;
1.944     raeburn  17258:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  17259:     if ($lctype ne 'community') {
                   17260:         $lctype = 'course';
                   17261:     }
1.566     albertel 17262:     if ($clonehome eq 'no_host') {
1.944     raeburn  17263:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17264:             push(@clonemsg,({
                   17265:                               mt => 'No new community created.',
                   17266:                               args => [],
                   17267:                             },
                   17268:                             {
                   17269:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   17270:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   17271:                             }));
1.908     raeburn  17272:         } else {
1.1344    raeburn  17273:             push(@clonemsg,({
                   17274:                               mt => 'No new course created.',
                   17275:                               args => [],
                   17276:                             },
                   17277:                             {
                   17278:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   17279:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17280:                             }));
                   17281:         }
1.566     albertel 17282:     } else {
                   17283: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  17284:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  17285:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  17286:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  17287:                 push(@clonemsg,({
                   17288:                                   mt => 'No new community created.',
                   17289:                                   args => [],
                   17290:                                 },
                   17291:                                 {
                   17292:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   17293:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17294:                                 }));
                   17295:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  17296:             }
                   17297:         }
1.1262    raeburn  17298: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  17299:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 17300: 	    $can_clone = 1;
                   17301: 	} else {
1.1221    raeburn  17302: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 17303: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  17304:             if ($clonehash{'cloners'} eq '') {
                   17305:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   17306:                 if ($domdefs{'canclone'}) {
                   17307:                     unless ($domdefs{'canclone'} eq 'none') {
                   17308:                         if ($domdefs{'canclone'} eq 'domain') {
                   17309:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   17310:                                 $can_clone = 1;
                   17311:                             }
                   17312:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17313:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   17314:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   17315:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   17316:                                 $can_clone = 1;
                   17317:                             }
                   17318:                         }
                   17319:                     }
                   17320:                 }
1.578     raeburn  17321:             } else {
1.1221    raeburn  17322: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   17323:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  17324:                     $can_clone = 1;
1.1221    raeburn  17325:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  17326:                     $can_clone = 1;
1.1225    raeburn  17327:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   17328:                     $can_clone = 1;
1.1221    raeburn  17329:                 }
                   17330:                 unless ($can_clone) {
1.1225    raeburn  17331:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17332:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  17333:                         my (%gotdomdefaults,%gotcodedefaults);
                   17334:                         foreach my $cloner (@cloners) {
                   17335:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   17336:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   17337:                                 my (%codedefaults,@code_order);
                   17338:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   17339:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   17340:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   17341:                                     }
                   17342:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   17343:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   17344:                                     }
                   17345:                                 } else {
                   17346:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   17347:                                                                             \%codedefaults,
                   17348:                                                                             \@code_order);
                   17349:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   17350:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   17351:                                 }
                   17352:                                 if (@code_order > 0) {
                   17353:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   17354:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   17355:                                                                                 $args->{'crscode'})) {
                   17356:                                         $can_clone = 1;
                   17357:                                         last;
                   17358:                                     }
                   17359:                                 }
                   17360:                             }
                   17361:                         }
                   17362:                     }
1.1225    raeburn  17363:                 }
                   17364:             }
                   17365:             unless ($can_clone) {
                   17366:                 my $ccrole = 'cc';
                   17367:                 if ($args->{'crstype'} eq 'Community') {
                   17368:                     $ccrole = 'co';
                   17369:                 }
                   17370: 	        my %roleshash =
                   17371: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   17372: 					          $args->{'ccdomain'},
                   17373:                                                   'userroles',['active'],[$ccrole],
                   17374: 					          [$args->{'clonedomain'}]);
                   17375: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   17376:                     $can_clone = 1;
                   17377:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   17378:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   17379:                     $can_clone = 1;
1.1221    raeburn  17380:                 }
                   17381:             }
                   17382:             unless ($can_clone) {
                   17383:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17384:                     push(@clonemsg,({
                   17385:                                       mt => 'No new community created.',
                   17386:                                       args => [],
                   17387:                                     },
                   17388:                                     {
                   17389:                                       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]).',
                   17390:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17391:                                     }));
1.942     raeburn  17392:                 } else {
1.1344    raeburn  17393:                     push(@clonemsg,({
                   17394:                                       mt => 'No new course created.',
                   17395:                                       args => [],
                   17396:                                     },
                   17397:                                     {
                   17398:                                       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]).',
                   17399:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17400:                                     }));
1.1221    raeburn  17401:                 }
1.566     albertel 17402: 	    }
1.578     raeburn  17403:         }
1.566     albertel 17404:     }
1.1344    raeburn  17405:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17406: }
                   17407: 
1.444     albertel 17408: sub construct_course {
1.1262    raeburn  17409:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  17410:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   17411:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  17412:     my $linefeed =  '<br />'."\n";
                   17413:     if ($context eq 'auto') {
                   17414:         $linefeed = "\n";
                   17415:     }
1.566     albertel 17416: 
                   17417: #
                   17418: # Are we cloning?
                   17419: #
1.1344    raeburn  17420:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17421:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  17422: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 17423:         if (!$can_clone) {
1.1344    raeburn  17424: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 17425: 	}
                   17426:     }
                   17427: 
1.444     albertel 17428: #
                   17429: # Open course
                   17430: #
1.1239    raeburn  17431:     my $showncrstype;
                   17432:     if ($args->{'crstype'} eq 'Placement') {
                   17433:         $showncrstype = 'placement test'; 
                   17434:     } else {  
                   17435:         $showncrstype = lc($args->{'crstype'});
                   17436:     }
1.444     albertel 17437:     my %cenv=();
                   17438:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   17439:                                              $args->{'cdescr'},
                   17440:                                              $args->{'curl'},
                   17441:                                              $args->{'course_home'},
                   17442:                                              $args->{'nonstandard'},
                   17443:                                              $args->{'crscode'},
                   17444:                                              $args->{'ccuname'}.':'.
                   17445:                                              $args->{'ccdomain'},
1.882     raeburn  17446:                                              $args->{'crstype'},
1.1344    raeburn  17447:                                              $cnum,$context,$category,
                   17448:                                              $callercontext);
1.444     albertel 17449: 
                   17450:     # Note: The testing routines depend on this being output; see 
                   17451:     # Utils::Course. This needs to at least be output as a comment
                   17452:     # if anyone ever decides to not show this, and Utils::Course::new
                   17453:     # will need to be suitably modified.
1.1344    raeburn  17454:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17455:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17456:     } else {
                   17457:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17458:     }
1.943     raeburn  17459:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  17460:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17461:     }
                   17462: 
1.444     albertel 17463: #
                   17464: # Check if created correctly
                   17465: #
1.479     albertel 17466:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 17467:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  17468:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  17469:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17470:             $outcome .= &mt_user($user_lh,
                   17471:                             'Course creation failed, unrecognized course home server.');
                   17472:         } else {
                   17473:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   17474:         }
                   17475:         $outcome .= $linefeed;
                   17476:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17477:     }
1.541     raeburn  17478:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 17479: 
1.444     albertel 17480: #
1.566     albertel 17481: # Do the cloning
                   17482: #   
1.1344    raeburn  17483:     my @clonemsg;
1.566     albertel 17484:     if ($can_clone && $cloneid) {
1.1344    raeburn  17485:         push(@clonemsg,
                   17486:                       {
                   17487:                           mt => 'Created [_1] by cloning from [_2]',
                   17488:                           args => [$showncrstype,$clonetitle],
                   17489:                       });
1.566     albertel 17490: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 17491: # Copy all files
1.1344    raeburn  17492:         my @info =
                   17493: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   17494: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   17495:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   17496:                                                      $args->{'tinyurls'});
                   17497:         if (@info) {
                   17498:             push(@clonemsg,@info);
                   17499:         }
1.444     albertel 17500: # Restore URL
1.566     albertel 17501: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 17502: # Restore title
1.566     albertel 17503: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  17504: # Restore creation date, creator and creation context.
                   17505:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   17506:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   17507:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 17508: # Mark as cloned
1.566     albertel 17509: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      17510: # Need to clone grading mode
                   17511:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   17512:         $cenv{'grading'}=$newenv{'grading'};
                   17513: # Do not clone these environment entries
                   17514:         &Apache::lonnet::del('environment',
                   17515:                   ['default_enrollment_start_date',
                   17516:                    'default_enrollment_end_date',
                   17517:                    'question.email',
                   17518:                    'policy.email',
                   17519:                    'comment.email',
                   17520:                    'pch.users.denied',
1.725     raeburn  17521:                    'plc.users.denied',
                   17522:                    'hidefromcat',
1.1121    raeburn  17523:                    'checkforpriv',
1.1355    raeburn  17524:                    'categories'],
1.638     www      17525:                    $$crsudom,$$crsunum);
1.1170    raeburn  17526:         if ($args->{'textbook'}) {
                   17527:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   17528:         }
1.444     albertel 17529:     }
1.566     albertel 17530: 
1.444     albertel 17531: #
                   17532: # Set environment (will override cloned, if existing)
                   17533: #
                   17534:     my @sections = ();
                   17535:     my @xlists = ();
                   17536:     if ($args->{'crstype'}) {
                   17537:         $cenv{'type'}=$args->{'crstype'};
                   17538:     }
1.1371    raeburn  17539:     if ($args->{'lti'}) {
                   17540:         $cenv{'internal.lti'}=$args->{'lti'};
                   17541:     }
1.444     albertel 17542:     if ($args->{'crsid'}) {
                   17543:         $cenv{'courseid'}=$args->{'crsid'};
                   17544:     }
                   17545:     if ($args->{'crscode'}) {
                   17546:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   17547:     }
                   17548:     if ($args->{'crsquota'} ne '') {
                   17549:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   17550:     } else {
                   17551:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   17552:     }
                   17553:     if ($args->{'ccuname'}) {
                   17554:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   17555:                                         ':'.$args->{'ccdomain'};
                   17556:     } else {
                   17557:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   17558:     }
1.1116    raeburn  17559:     if ($args->{'defaultcredits'}) {
                   17560:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   17561:     }
1.444     albertel 17562:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1412    raeburn  17563:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 17564:     if ($args->{'crssections'}) {
                   17565:         $cenv{'internal.sectionnums'} = '';
                   17566:         if ($args->{'crssections'} =~ m/,/) {
                   17567:             @sections = split/,/,$args->{'crssections'};
                   17568:         } else {
                   17569:             $sections[0] = $args->{'crssections'};
                   17570:         }
                   17571:         if (@sections > 0) {
                   17572:             foreach my $item (@sections) {
                   17573:                 my ($sec,$gp) = split/:/,$item;
                   17574:                 my $class = $args->{'crscode'}.$sec;
                   17575:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   17576:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1412    raeburn  17577:                 if ($addcheck eq 'ok') {
                   17578:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17579:                         push(@oklcsecs,$gp);
                   17580:                     }
                   17581:                 } else {
1.1263    raeburn  17582:                     push(@badclasses,$class);
1.444     albertel 17583:                 }
                   17584:             }
                   17585:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   17586:         }
                   17587:     }
                   17588: # do not hide course coordinator from staff listing, 
                   17589: # even if privileged
                   17590:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  17591: # add course coordinator's domain to domains to check for privileged users
                   17592: # if different to course domain
                   17593:     if ($$crsudom ne $args->{'ccdomain'}) {
                   17594:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   17595:     }
1.444     albertel 17596: # add crosslistings
                   17597:     if ($args->{'crsxlist'}) {
                   17598:         $cenv{'internal.crosslistings'}='';
                   17599:         if ($args->{'crsxlist'} =~ m/,/) {
                   17600:             @xlists = split/,/,$args->{'crsxlist'};
                   17601:         } else {
                   17602:             $xlists[0] = $args->{'crsxlist'};
                   17603:         }
                   17604:         if (@xlists > 0) {
                   17605:             foreach my $item (@xlists) {
                   17606:                 my ($xl,$gp) = split/:/,$item;
                   17607:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   17608:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1412    raeburn  17609:                 if ($addcheck eq 'ok') {
                   17610:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17611:                         push(@oklcsecs,$gp);
                   17612:                     }
                   17613:                 } else {
1.1263    raeburn  17614:                     push(@badclasses,$xl);
1.444     albertel 17615:                 }
                   17616:             }
                   17617:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   17618:         }
                   17619:     }
                   17620:     if ($args->{'autoadds'}) {
                   17621:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   17622:     }
                   17623:     if ($args->{'autodrops'}) {
                   17624:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   17625:     }
                   17626: # check for notification of enrollment changes
                   17627:     my @notified = ();
                   17628:     if ($args->{'notify_owner'}) {
                   17629:         if ($args->{'ccuname'} ne '') {
                   17630:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   17631:         }
                   17632:     }
                   17633:     if ($args->{'notify_dc'}) {
                   17634:         if ($uname ne '') { 
1.630     raeburn  17635:             push(@notified,$uname.':'.$udom);
1.444     albertel 17636:         }
                   17637:     }
                   17638:     if (@notified > 0) {
                   17639:         my $notifylist;
                   17640:         if (@notified > 1) {
                   17641:             $notifylist = join(',',@notified);
                   17642:         } else {
                   17643:             $notifylist = $notified[0];
                   17644:         }
                   17645:         $cenv{'internal.notifylist'} = $notifylist;
                   17646:     }
                   17647:     if (@badclasses > 0) {
                   17648:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  17649:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   17650:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   17651:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 17652:         );
1.1264    raeburn  17653:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   17654:                            &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  17655:         if ($context eq 'auto') {
                   17656:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  17657:         } else {
1.566     albertel 17658:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  17659:         }
                   17660:         foreach my $item (@badclasses) {
1.541     raeburn  17661:             if ($context eq 'auto') {
1.1261    raeburn  17662:                 $outcome .= " - $item\n";
1.541     raeburn  17663:             } else {
1.1261    raeburn  17664:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  17665:             }
1.1261    raeburn  17666:         }
                   17667:         if ($context eq 'auto') {
                   17668:             $outcome .= $linefeed;
                   17669:         } else {
                   17670:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  17671:         } 
1.444     albertel 17672:     }
                   17673:     if ($args->{'no_end_date'}) {
                   17674:         $args->{'endaccess'} = 0;
                   17675:     }
1.1412    raeburn  17676: #  If an official course with institutional sections is created by cloning 
                   17677: #  an existing course, section-specific hiding of course totals in student's
                   17678: #  view of grades as copied from cloned course, will be checked for valid 
                   17679: #  sections.
                   17680:     if (($can_clone && $cloneid) &&
                   17681:         ($cenv{'internal.coursecode'} ne '') &&
                   17682:         ($cenv{'grading'} eq 'standard') &&
                   17683:         ($cenv{'hidetotals'} ne '') &&
                   17684:         ($cenv{'hidetotals'} ne 'all')) {
                   17685:         my @hidesecs;
                   17686:         my $deletehidetotals;
                   17687:         if (@oklcsecs) {
                   17688:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   17689:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   17690:                     push(@hidesecs,$sec);
                   17691:                 }
                   17692:             }
                   17693:             if (@hidesecs) {
                   17694:                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   17695:             } else {
                   17696:                 $deletehidetotals = 1;
                   17697:             }
                   17698:         } else {
                   17699:             $deletehidetotals = 1;
                   17700:         }
                   17701:         if ($deletehidetotals) {
                   17702:             delete($cenv{'hidetotals'});
                   17703:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   17704:         }
                   17705:     }
1.444     albertel 17706:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   17707:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   17708:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   17709:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   17710:     if ($args->{'showphotos'}) {
                   17711:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   17712:     }
                   17713:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   17714:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   17715:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   17716:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  17717:             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'); 
                   17718:             if ($context eq 'auto') {
                   17719:                 $outcome .= $krb_msg;
                   17720:             } else {
1.566     albertel 17721:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  17722:             }
                   17723:             $outcome .= $linefeed;
1.444     albertel 17724:         }
                   17725:     }
                   17726:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   17727:        if ($args->{'setpolicy'}) {
                   17728:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17729:        }
                   17730:        if ($args->{'setcontent'}) {
                   17731:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17732:        }
1.1251    raeburn  17733:        if ($args->{'setcomment'}) {
                   17734:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17735:        }
1.444     albertel 17736:     }
                   17737:     if ($args->{'reshome'}) {
                   17738: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   17739: 	$cenv{'reshome'}=~s/\/+$/\//;
                   17740:     }
                   17741: #
                   17742: # course has keyed access
                   17743: #
                   17744:     if ($args->{'setkeys'}) {
                   17745:        $cenv{'keyaccess'}='yes';
                   17746:     }
                   17747: # if specified, key authority is not course, but user
                   17748: # only active if keyaccess is yes
                   17749:     if ($args->{'keyauth'}) {
1.487     albertel 17750: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   17751: 	$user = &LONCAPA::clean_username($user);
                   17752: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     17753: 	if ($user ne '' && $domain ne '') {
1.487     albertel 17754: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 17755: 	}
                   17756:     }
                   17757: 
1.1166    raeburn  17758: #
1.1167    raeburn  17759: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17760: #
                   17761:     if ($args->{'uniquecode'}) {
                   17762:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17763:         if ($code) {
                   17764:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17765:             my %crsinfo =
                   17766:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17767:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17768:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17769:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17770:             } 
1.1166    raeburn  17771:             if (ref($coderef)) {
                   17772:                 $$coderef = $code;
                   17773:             }
                   17774:         }
                   17775:     }
                   17776: 
1.444     albertel 17777:     if ($args->{'disresdis'}) {
                   17778:         $cenv{'pch.roles.denied'}='st';
                   17779:     }
                   17780:     if ($args->{'disablechat'}) {
                   17781:         $cenv{'plc.roles.denied'}='st';
                   17782:     }
                   17783: 
                   17784:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17785:     # course
                   17786:     $cenv{'course.helper.not.run'} = 1;
                   17787:     #
                   17788:     # Use new Randomseed
                   17789:     #
                   17790:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17791:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17792:     #
                   17793:     # The encryption code and receipt prefix for this course
                   17794:     #
                   17795:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17796:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17797:     #
                   17798:     # By default, use standard grading
                   17799:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17800: 
1.541     raeburn  17801:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17802:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17803: #
                   17804: # Open all assignments
                   17805: #
                   17806:     if ($args->{'openall'}) {
1.1341    raeburn  17807:        my $opendate = time;
                   17808:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17809:            $opendate = $args->{'openallfrom'};
                   17810:        }
1.444     albertel 17811:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17812:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17813:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17814:        $outcome .= &mt('All assignments open starting [_1]',
                   17815:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17816:                    &Apache::lonnet::cput
                   17817:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17818:    }
                   17819: #
                   17820: # Set first page
                   17821: #
                   17822:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17823: 	    || ($cloneid)) {
                   17824: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17825: 
                   17826: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17827:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17828: 
1.444     albertel 17829:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17830:         my $title; my $url;
                   17831:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17832: 	    $title=&mt('Syllabus');
1.444     albertel 17833:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17834:         } else {
1.963     raeburn  17835:             $title=&mt('Table of Contents');
1.444     albertel 17836:             $url='/adm/navmaps';
                   17837:         }
1.445     albertel 17838: 
                   17839:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17840: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17841: 
                   17842: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17843:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17844:     }
1.566     albertel 17845: 
1.1237    raeburn  17846: # 
                   17847: # Set params for Placement Tests
                   17848: #
1.1239    raeburn  17849:     if ($args->{'crstype'} eq 'Placement') {
                   17850:        my %storecontent; 
                   17851:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17852:        my %defaults = (
                   17853:                         buttonshide   => { value => 'yes',
                   17854:                                            type => 'string_yesno',},
                   17855:                         type          => { value => 'randomizetry',
                   17856:                                            type  => 'string_questiontype',},
                   17857:                         maxtries      => { value => 1,
                   17858:                                            type => 'int_pos',},
                   17859:                         problemstatus => { value => 'no',
                   17860:                                            type  => 'string_problemstatus',},
                   17861:                       );
                   17862:        foreach my $key (keys(%defaults)) {
                   17863:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17864:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17865:        }
1.1237    raeburn  17866:        &Apache::lonnet::cput
                   17867:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17868:     }
                   17869: 
1.1344    raeburn  17870:     return (1,$outcome,\@clonemsg);
1.444     albertel 17871: }
                   17872: 
1.1166    raeburn  17873: sub make_unique_code {
                   17874:     my ($cdom,$cnum) = @_;
                   17875:     # get lock on uniquecodes db
                   17876:     my $lockhash = {
                   17877:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17878:                                                   ':'.$env{'user.domain'},
                   17879:                    };
                   17880:     my $tries = 0;
                   17881:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17882:     my ($code,$error);
                   17883:   
                   17884:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17885:         $tries ++;
                   17886:         sleep 1;
                   17887:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17888:     }
                   17889:     if ($gotlock eq 'ok') {
                   17890:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17891:         my $gotcode;
                   17892:         my $attempts = 0;
                   17893:         while ((!$gotcode) && ($attempts < 100)) {
                   17894:             $code = &generate_code();
                   17895:             if (!exists($currcodes{$code})) {
                   17896:                 $gotcode = 1;
                   17897:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17898:                     $error = 'nostore';
                   17899:                 }
                   17900:             }
                   17901:             $attempts ++;
                   17902:         }
                   17903:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17904:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17905:     } else {
                   17906:         $error = 'nolock';
                   17907:     }
                   17908:     return ($code,$error);
                   17909: }
                   17910: 
                   17911: sub generate_code {
                   17912:     my $code;
                   17913:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17914:     for (my $i=0; $i<6; $i++) {
                   17915:         my $lettnum = int (rand 2);
                   17916:         my $item = '';
                   17917:         if ($lettnum) {
                   17918:             $item = $letts[int( rand(18) )];
                   17919:         } else {
                   17920:             $item = 1+int( rand(8) );
                   17921:         }
                   17922:         $code .= $item;
                   17923:     }
                   17924:     return $code;
                   17925: }
                   17926: 
1.444     albertel 17927: ############################################################
                   17928: ############################################################
                   17929: 
1.1237    raeburn  17930: # Community, Course and Placement Test
1.378     raeburn  17931: sub course_type {
                   17932:     my ($cid) = @_;
                   17933:     if (!defined($cid)) {
                   17934:         $cid = $env{'request.course.id'};
                   17935:     }
1.404     albertel 17936:     if (defined($env{'course.'.$cid.'.type'})) {
                   17937:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17938:     } else {
                   17939:         return 'Course';
1.377     raeburn  17940:     }
                   17941: }
1.156     albertel 17942: 
1.406     raeburn  17943: sub group_term {
                   17944:     my $crstype = &course_type();
                   17945:     my %names = (
                   17946:                   'Course' => 'group',
1.865     raeburn  17947:                   'Community' => 'group',
1.1237    raeburn  17948:                   'Placement' => 'group',
1.406     raeburn  17949:                 );
                   17950:     return $names{$crstype};
                   17951: }
                   17952: 
1.902     raeburn  17953: sub course_types {
1.1310    raeburn  17954:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17955:     my %typename = (
                   17956:                          official   => 'Official course',
                   17957:                          unofficial => 'Unofficial course',
                   17958:                          community  => 'Community',
1.1165    raeburn  17959:                          textbook   => 'Textbook course',
1.1237    raeburn  17960:                          placement  => 'Placement test',
1.1310    raeburn  17961:                          lti        => 'LTI provider',
1.902     raeburn  17962:                    );
                   17963:     return (\@types,\%typename);
                   17964: }
                   17965: 
1.156     albertel 17966: sub icon {
                   17967:     my ($file)=@_;
1.505     albertel 17968:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17969:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17970:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17971:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17972: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17973: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17974: 	            $curfext.".gif") {
                   17975: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17976: 		$curfext.".gif";
                   17977: 	}
                   17978:     }
1.249     albertel 17979:     return &lonhttpdurl($iconname);
1.154     albertel 17980: } 
1.84      albertel 17981: 
1.575     albertel 17982: sub lonhttpdurl {
1.692     www      17983: #
                   17984: # Had been used for "small fry" static images on separate port 8080.
                   17985: # Modify here if lightweight http functionality desired again.
                   17986: # Currently eliminated due to increasing firewall issues.
                   17987: #
1.575     albertel 17988:     my ($url)=@_;
1.692     www      17989:     return $url;
1.215     albertel 17990: }
                   17991: 
1.213     albertel 17992: sub connection_aborted {
                   17993:     my ($r)=@_;
                   17994:     $r->print(" ");$r->rflush();
                   17995:     my $c = $r->connection;
                   17996:     return $c->aborted();
                   17997: }
                   17998: 
1.221     foxr     17999: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     18000: #    strings as 'strings'.
                   18001: sub escape_single {
1.221     foxr     18002:     my ($input) = @_;
1.223     albertel 18003:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     18004:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   18005:     return $input;
                   18006: }
1.223     albertel 18007: 
1.222     foxr     18008: #  Same as escape_single, but escape's "'s  This 
                   18009: #  can be used for  "strings"
                   18010: sub escape_double {
                   18011:     my ($input) = @_;
                   18012:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   18013:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   18014:     return $input;
                   18015: }
1.223     albertel 18016:  
1.222     foxr     18017: #   Escapes the last element of a full URL.
                   18018: sub escape_url {
                   18019:     my ($url)   = @_;
1.238     raeburn  18020:     my @urlslices = split(/\//, $url,-1);
1.369     www      18021:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  18022:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     18023: }
1.462     albertel 18024: 
1.820     raeburn  18025: sub compare_arrays {
                   18026:     my ($arrayref1,$arrayref2) = @_;
                   18027:     my (@difference,%count);
                   18028:     @difference = ();
                   18029:     %count = ();
                   18030:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   18031:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   18032:         foreach my $element (keys(%count)) {
                   18033:             if ($count{$element} == 1) {
                   18034:                 push(@difference,$element);
                   18035:             }
                   18036:         }
                   18037:     }
                   18038:     return @difference;
                   18039: }
                   18040: 
1.1322    raeburn  18041: sub lon_status_items {
                   18042:     my %defaults = (
                   18043:                      E         => 100,
                   18044:                      W         => 4,
                   18045:                      N         => 1,
1.1324    raeburn  18046:                      U         => 5,
1.1322    raeburn  18047:                      threshold => 200,
                   18048:                      sysmail   => 2500,
                   18049:                    );
                   18050:     my %names = (
                   18051:                    E => 'Errors',
                   18052:                    W => 'Warnings',
                   18053:                    N => 'Notices',
1.1324    raeburn  18054:                    U => 'Unsent',
1.1322    raeburn  18055:                 );
                   18056:     return (\%defaults,\%names);
                   18057: }
                   18058: 
1.817     bisitz   18059: # -------------------------------------------------------- Initialize user login
1.462     albertel 18060: sub init_user_environment {
1.463     albertel 18061:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 18062:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   18063: 
                   18064:     my $public=($username eq 'public' && $domain eq 'public');
                   18065: 
1.1415    raeburn  18066:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   18067:         $coauthorenv);
1.462     albertel 18068:     my $now=time;
                   18069: 
                   18070:     if ($public) {
                   18071: 	my $max_public=100;
                   18072: 	my $oldest;
                   18073: 	my $oldest_time=0;
                   18074: 	for(my $next=1;$next<=$max_public;$next++) {
                   18075: 	    if (-e $lonids."/publicuser_$next.id") {
                   18076: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   18077: 		if ($mtime<$oldest_time || !$oldest_time) {
                   18078: 		    $oldest_time=$mtime;
                   18079: 		    $oldest=$next;
                   18080: 		}
                   18081: 	    } else {
                   18082: 		$cookie="publicuser_$next";
                   18083: 		last;
                   18084: 	    }
                   18085: 	}
                   18086: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   18087:     } else {
1.1275    raeburn  18088: 	# See if old ID present, if so, remove if this isn't a robot,
                   18089: 	# killing any existing non-robot sessions
1.463     albertel 18090: 	if (!$args->{'robot'}) {
                   18091: 	    opendir(DIR,$lonids);
                   18092: 	    while ($filename=readdir(DIR)) {
                   18093: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  18094:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   18095:                             &GDBM_READER(),0640)) {
1.1295    raeburn  18096:                         my $linkedfile;
1.1320    raeburn  18097:                         if (exists($oldenv{'user.linkedenv'})) {
                   18098:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  18099:                         }
1.1320    raeburn  18100:                         untie(%oldenv);
                   18101:                         if (unlink("$lonids/$filename")) {
                   18102:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   18103:                                 if (-l "$lonids/$linkedfile.id") {
                   18104:                                     unlink("$lonids/$linkedfile.id");
                   18105:                                 }
1.1295    raeburn  18106:                             }
                   18107:                         }
                   18108:                     } else {
                   18109:                         unlink($lonids.'/'.$filename);
                   18110:                     }
1.463     albertel 18111: 		}
1.462     albertel 18112: 	    }
1.463     albertel 18113: 	    closedir(DIR);
1.1204    raeburn  18114: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   18115:             my $namespace = 'nohist_courseeditor';
                   18116:             my $lockingkey = 'paste'."\0".'locked_num';
                   18117:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   18118:                                                 $domain,$username);
                   18119:             if (exists($lockhash{$lockingkey})) {
                   18120:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   18121:                 unless ($delresult eq 'ok') {
                   18122:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   18123:                 }
                   18124:             }
1.462     albertel 18125: 	}
                   18126: # Give them a new cookie
1.463     albertel 18127: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      18128: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 18129: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 18130:     
                   18131: # Initialize roles
                   18132: 
1.1414    raeburn  18133: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  18134:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 18135:     }
                   18136: # ------------------------------------ Check browser type and MathML capability
                   18137: 
1.1194    raeburn  18138:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   18139:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 18140: 
                   18141: # ------------------------------------------------------------- Get environment
                   18142: 
                   18143:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   18144:     my ($tmp) = keys(%userenv);
1.1275    raeburn  18145:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 18146: 	undef(%userenv);
                   18147:     }
                   18148:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   18149: 	$form->{'interface'}=$userenv{'interface'};
                   18150:     }
                   18151:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   18152: 
                   18153: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   18154:     foreach my $option ('interface','localpath','localres') {
                   18155:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 18156:     }
                   18157: # --------------------------------------------------------- Write first profile
                   18158: 
                   18159:     {
1.1350    raeburn  18160:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 18161: 	my %initial_env = 
                   18162: 	    ("user.name"          => $username,
                   18163: 	     "user.domain"        => $domain,
                   18164: 	     "user.home"          => $authhost,
                   18165: 	     "browser.type"       => $clientbrowser,
                   18166: 	     "browser.version"    => $clientversion,
                   18167: 	     "browser.mathml"     => $clientmathml,
                   18168: 	     "browser.unicode"    => $clientunicode,
                   18169: 	     "browser.os"         => $clientos,
1.1137    raeburn  18170:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  18171:              "browser.info"       => $clientinfo,
1.1194    raeburn  18172:              "browser.osversion"  => $clientosversion,
1.462     albertel 18173: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   18174: 	     "request.course.fn"  => '',
                   18175: 	     "request.course.uri" => '',
                   18176: 	     "request.course.sec" => '',
                   18177: 	     "request.role"       => 'cm',
                   18178: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  18179: 	     "request.host"       => $ip,);
1.462     albertel 18180: 
                   18181:         if ($form->{'localpath'}) {
                   18182: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   18183: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   18184:         }
                   18185: 	
                   18186: 	if ($form->{'interface'}) {
                   18187: 	    $form->{'interface'}=~s/\W//gs;
                   18188: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   18189: 	    $env{'browser.interface'}=$form->{'interface'};
                   18190: 	}
                   18191: 
1.1157    raeburn  18192:         if ($form->{'iptoken'}) {
                   18193:             my $lonhost = $r->dir_config('lonHostID');
                   18194:             $initial_env{"user.noloadbalance"} = $lonhost;
                   18195:             $env{'user.noloadbalance'} = $lonhost;
                   18196:         }
                   18197: 
1.1268    raeburn  18198:         if ($form->{'noloadbalance'}) {
                   18199:             my @hosts = &Apache::lonnet::current_machine_ids();
                   18200:             my $hosthere = $form->{'noloadbalance'};
                   18201:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   18202:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   18203:                 $env{'user.noloadbalance'} = $hosthere;
                   18204:             }
                   18205:         }
                   18206: 
1.1016    raeburn  18207:         unless ($domain eq 'public') {
1.1273    raeburn  18208:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   18209:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   18210: 
1.1414    raeburn  18211:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
                   18212:                 $userenv{'availabletools.'.$tool} =
1.1273    raeburn  18213:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   18214:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   18215:             }
1.980     raeburn  18216: 
1.1311    raeburn  18217:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  18218:                 $userenv{'canrequest.'.$crstype} =
                   18219:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   18220:                                                       'reload','requestcourses',
                   18221:                                                       \%userenv,\%domdef,\%is_adv);
                   18222:             }
1.724     raeburn  18223: 
1.1418    raeburn  18224:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   18225:                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   18226:                 if ($userenv{'authoreditors'}) {
                   18227:                     $userenv{'editors'} = $userenv{'authoreditors'};
                   18228:                 } elsif ($domdef{'editors'} ne '') {
                   18229:                     $userenv{'editors'} = $domdef{'editors'};
                   18230:                 } else {
                   18231:                     $userenv{'editors'} = 'edit,xml';
                   18232:                 }
1.1431    raeburn  18233:                 if ($userenv{'authorarchive'}) {
                   18234:                     $userenv{'canarchive'} = 1;
                   18235:                 } elsif (($userenv{'authorarchive'} eq '') &&
                   18236:                          ($domdef{'archive'})) {
                   18237:                     $userenv{'canarchive'} = 1;
                   18238:                 }
1.1418    raeburn  18239:             }
                   18240: 
1.1273    raeburn  18241:             $userenv{'canrequest.author'} =
                   18242:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   18243:                                                   'reload','requestauthor',
1.980     raeburn  18244:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  18245:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   18246:                                                  $domain,$username);
                   18247:             my $reqstatus = $reqauthor{'author_status'};
                   18248:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   18249:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   18250:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   18251:                                                       $reqauthor{'author'}{'timestamp'};
                   18252:                 }
1.1092    raeburn  18253:             }
1.1287    raeburn  18254:             my ($types,$typename) = &course_types();
                   18255:             if (ref($types) eq 'ARRAY') {
                   18256:                 my @options = ('approval','validate','autolimit');
                   18257:                 my $optregex = join('|',@options);
                   18258:                 my (%willtrust,%trustchecked);
                   18259:                 foreach my $type (@{$types}) {
                   18260:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   18261:                     if ($dom_str ne '') {
                   18262:                         my $updatedstr = '';
                   18263:                         my @possdomains = split(',',$dom_str);
                   18264:                         foreach my $entry (@possdomains) {
                   18265:                             my ($extdom,$extopt) = split(':',$entry);
                   18266:                             unless ($trustchecked{$extdom}) {
                   18267:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   18268:                                 $trustchecked{$extdom} = 1;
                   18269:                             }
                   18270:                             if ($willtrust{$extdom}) {
                   18271:                                 $updatedstr .= $entry.',';
                   18272:                             }
                   18273:                         }
                   18274:                         $updatedstr =~ s/,$//;
                   18275:                         if ($updatedstr) {
                   18276:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   18277:                         } else {
                   18278:                             delete($userenv{'reqcrsotherdom.'.$type});
                   18279:                         }
                   18280:                     }
                   18281:                 }
                   18282:             }
1.1092    raeburn  18283:         }
1.462     albertel 18284: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  18285: 
1.462     albertel 18286: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   18287: 		 &GDBM_WRCREAT(),0640)) {
                   18288: 	    &_add_to_env(\%disk_env,\%initial_env);
                   18289: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   18290: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  18291:             if (ref($firstaccenv) eq 'HASH') {
                   18292:                 &_add_to_env(\%disk_env,$firstaccenv);
                   18293:             }
                   18294:             if (ref($timerintenv) eq 'HASH') {
                   18295:                 &_add_to_env(\%disk_env,$timerintenv);
                   18296:             }
1.1414    raeburn  18297:             if (ref($coauthorenv) eq 'HASH') {
                   18298:                 if (keys(%{$coauthorenv})) {
                   18299:                     &_add_to_env(\%disk_env,$coauthorenv);
                   18300:                 }
                   18301:             }
1.463     albertel 18302: 	    if (ref($args->{'extra_env'})) {
                   18303: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   18304: 	    }
1.462     albertel 18305: 	    untie(%disk_env);
                   18306: 	} else {
1.705     tempelho 18307: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   18308: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 18309: 	    return 'error: '.$!;
                   18310: 	}
                   18311:     }
                   18312:     $env{'request.role'}='cm';
                   18313:     $env{'request.role.adv'}=$env{'user.adv'};
                   18314:     $env{'browser.type'}=$clientbrowser;
                   18315: 
                   18316:     return $cookie;
                   18317: 
                   18318: }
                   18319: 
                   18320: sub _add_to_env {
                   18321:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  18322:     if (ref($env_data) eq 'HASH') {
                   18323:         while (my ($key,$value) = each(%$env_data)) {
                   18324: 	    $idf->{$prefix.$key} = $value;
                   18325: 	    $env{$prefix.$key}   = $value;
                   18326:         }
1.462     albertel 18327:     }
                   18328: }
                   18329: 
1.685     tempelho 18330: # --- Get the symbolic name of a problem and the url
                   18331: sub get_symb {
                   18332:     my ($request,$silent) = @_;
1.726     raeburn  18333:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 18334:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   18335:     if ($symb eq '') {
                   18336:         if (!$silent) {
1.1071    raeburn  18337:             if (ref($request)) { 
                   18338:                 $request->print("Unable to handle ambiguous references:$url:.");
                   18339:             }
1.685     tempelho 18340:             return ();
                   18341:         }
                   18342:     }
                   18343:     &Apache::lonenc::check_decrypt(\$symb);
                   18344:     return ($symb);
                   18345: }
                   18346: 
                   18347: # --------------------------------------------------------------Get annotation
                   18348: 
                   18349: sub get_annotation {
                   18350:     my ($symb,$enc) = @_;
                   18351: 
                   18352:     my $key = $symb;
                   18353:     if (!$enc) {
                   18354:         $key =
                   18355:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   18356:     }
                   18357:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   18358:     return $annotation{$key};
                   18359: }
                   18360: 
                   18361: sub clean_symb {
1.731     raeburn  18362:     my ($symb,$delete_enc) = @_;
1.685     tempelho 18363: 
                   18364:     &Apache::lonenc::check_decrypt(\$symb);
                   18365:     my $enc = $env{'request.enc'};
1.731     raeburn  18366:     if ($delete_enc) {
1.730     raeburn  18367:         delete($env{'request.enc'});
                   18368:     }
1.685     tempelho 18369: 
                   18370:     return ($symb,$enc);
                   18371: }
1.462     albertel 18372: 
1.1181    raeburn  18373: ############################################################
                   18374: ############################################################
                   18375: 
                   18376: =pod
                   18377: 
                   18378: =head1 Routines for building display used to search for courses
                   18379: 
                   18380: 
                   18381: =over 4
                   18382: 
                   18383: =item * &build_filters()
                   18384: 
                   18385: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  18386: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   18387: and quotacheck.pl
                   18388: 
1.1181    raeburn  18389: 
                   18390: Inputs:
                   18391: 
                   18392: filterlist - anonymous array of fields to include as potential filters 
                   18393: 
                   18394: crstype - course type
                   18395: 
                   18396: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   18397:               to pop-open a course selector (will contain "extra element"). 
                   18398: 
                   18399: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   18400: 
                   18401: filter - anonymous hash of criteria and their values
                   18402: 
                   18403: action - form action
                   18404: 
                   18405: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   18406: 
1.1182    raeburn  18407: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  18408: 
                   18409: cloneruname - username of owner of new course who wants to clone
                   18410: 
                   18411: clonerudom - domain of owner of new course who wants to clone
                   18412: 
                   18413: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   18414: 
                   18415: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   18416: 
                   18417: codedom - domain
                   18418: 
                   18419: formname - value of form element named "form". 
                   18420: 
                   18421: fixeddom - domain, if fixed.
                   18422: 
                   18423: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   18424: 
                   18425: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   18426: 
                   18427: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   18428: 
                   18429: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   18430: 
                   18431: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   18432: 
                   18433: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   18434: 
                   18435: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   18436: 
1.1182    raeburn  18437: 
1.1181    raeburn  18438: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   18439: 
1.1182    raeburn  18440: 
1.1181    raeburn  18441: Side Effects: None
                   18442: 
                   18443: =cut
                   18444: 
                   18445: # ---------------------------------------------- search for courses based on last activity etc.
                   18446: 
                   18447: sub build_filters {
                   18448:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   18449:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   18450:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   18451:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   18452:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  18453:     my ($list,$jscript);
1.1181    raeburn  18454:     my $onchange = 'javascript:updateFilters(this)';
                   18455:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   18456:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   18457:         $typeselectform,$instcodetitle);
                   18458:     if ($formname eq '') {
                   18459:         $formname = $caller;
                   18460:     }
                   18461:     foreach my $item (@{$filterlist}) {
                   18462:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   18463:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   18464:             if ($item eq 'domainfilter') {
                   18465:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   18466:             } elsif ($item eq 'coursefilter') {
                   18467:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   18468:             } elsif ($item eq 'ownerfilter') {
                   18469:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18470:             } elsif ($item eq 'ownerdomfilter') {
                   18471:                 $filter->{'ownerdomfilter'} =
                   18472:                     &LONCAPA::clean_domain($filter->{$item});
                   18473:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   18474:                                                        'ownerdomfilter',1);
                   18475:             } elsif ($item eq 'personfilter') {
                   18476:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18477:             } elsif ($item eq 'persondomfilter') {
                   18478:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   18479:                                                         'persondomfilter',1);
                   18480:             } else {
                   18481:                 $filter->{$item} =~ s/\W//g;
                   18482:             }
                   18483:             if (!$filter->{$item}) {
                   18484:                 $filter->{$item} = '';
                   18485:             }
                   18486:         }
                   18487:         if ($item eq 'domainfilter') {
                   18488:             my $allow_blank = 1;
                   18489:             if ($formname eq 'portform') {
                   18490:                 $allow_blank=0;
                   18491:             } elsif ($formname eq 'studentform') {
                   18492:                 $allow_blank=0;
                   18493:             }
                   18494:             if ($fixeddom) {
                   18495:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   18496:                                     ' value="'.$codedom.'" />'.
                   18497:                                     &Apache::lonnet::domain($codedom,'description');
                   18498:             } else {
                   18499:                 $domainselectform = &select_dom_form($filter->{$item},
                   18500:                                                      'domainfilter',
                   18501:                                                       $allow_blank,'',$onchange);
                   18502:             }
                   18503:         } else {
                   18504:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   18505:         }
                   18506:     }
                   18507: 
                   18508:     # last course activity filter and selection
                   18509:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   18510: 
                   18511:     # course created filter and selection
                   18512:     if (exists($filter->{'createdfilter'})) {
                   18513:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   18514:     }
                   18515: 
1.1239    raeburn  18516:     my $prefix = $crstype;
                   18517:     if ($crstype eq 'Placement') {
                   18518:         $prefix = 'Placement Test'
                   18519:     }
1.1181    raeburn  18520:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  18521:                 'cac' => "$prefix Activity",
                   18522:                 'ccr' => "$prefix Created",
                   18523:                 'cde' => "$prefix Title",
                   18524:                 'cdo' => "$prefix Domain",
1.1181    raeburn  18525:                 'ins' => 'Institutional Code',
                   18526:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  18527:                 'cow' => "$prefix Owner/Co-owner",
                   18528:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  18529:                 'cog' => 'Type',
                   18530:              );
                   18531: 
                   18532:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18533:         my $typeval = 'Course';
                   18534:         if ($crstype eq 'Community') {
                   18535:             $typeval = 'Community';
1.1239    raeburn  18536:         } elsif ($crstype eq 'Placement') {
                   18537:             $typeval = 'Placement';
1.1181    raeburn  18538:         }
                   18539:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   18540:     } else {
                   18541:         $typeselectform =  '<select name="type" size="1"';
                   18542:         if ($onchange) {
                   18543:             $typeselectform .= ' onchange="'.$onchange.'"';
                   18544:         }
                   18545:         $typeselectform .= '>'."\n";
1.1237    raeburn  18546:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  18547:             my $shown;
                   18548:             if ($posstype eq 'Placement') {
                   18549:                 $shown = &mt('Placement Test');
                   18550:             } else {
                   18551:                 $shown = &mt($posstype);
                   18552:             }
1.1181    raeburn  18553:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  18554:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  18555:         }
                   18556:         $typeselectform.="</select>";
                   18557:     }
                   18558: 
                   18559:     my ($cloneableonlyform,$cloneabletitle);
                   18560:     if (exists($filter->{'cloneableonly'})) {
                   18561:         my $cloneableon = '';
                   18562:         my $cloneableoff = ' checked="checked"';
                   18563:         if ($filter->{'cloneableonly'}) {
                   18564:             $cloneableon = $cloneableoff;
                   18565:             $cloneableoff = '';
                   18566:         }
                   18567:         $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>';
                   18568:         if ($formname eq 'ccrs') {
1.1187    bisitz   18569:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  18570:         } else {
                   18571:             $cloneabletitle = &mt('Cloneable by you');
                   18572:         }
                   18573:     }
                   18574:     my $officialjs;
                   18575:     if ($crstype eq 'Course') {
                   18576:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  18577: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   18578: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   18579:             if ($codedom) { 
1.1181    raeburn  18580:                 $officialjs = 1;
                   18581:                 ($instcodeform,$jscript,$$numtitlesref) =
                   18582:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   18583:                                                                   $officialjs,$codetitlesref);
                   18584:                 if ($jscript) {
1.1182    raeburn  18585:                     $jscript = '<script type="text/javascript">'."\n".
                   18586:                                '// <![CDATA['."\n".
                   18587:                                $jscript."\n".
                   18588:                                '// ]]>'."\n".
                   18589:                                '</script>'."\n";
1.1181    raeburn  18590:                 }
                   18591:             }
                   18592:             if ($instcodeform eq '') {
                   18593:                 $instcodeform =
                   18594:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   18595:                     $list->{'instcodefilter'}.'" />';
                   18596:                 $instcodetitle = $lt{'ins'};
                   18597:             } else {
                   18598:                 $instcodetitle = $lt{'inc'};
                   18599:             }
                   18600:             if ($fixeddom) {
                   18601:                 $instcodetitle .= '<br />('.$codedom.')';
                   18602:             }
                   18603:         }
                   18604:     }
                   18605:     my $output = qq|
                   18606: <form method="post" name="filterpicker" action="$action">
                   18607: <input type="hidden" name="form" value="$formname" />
                   18608: |;
                   18609:     if ($formname eq 'modifycourse') {
                   18610:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   18611:                    '<input type="hidden" name="prevphase" value="'.
                   18612:                    $prevphase.'" />'."\n";
1.1198    musolffc 18613:     } elsif ($formname eq 'quotacheck') {
                   18614:         $output .= qq|
                   18615: <input type="hidden" name="sortby" value="" />
                   18616: <input type="hidden" name="sortorder" value="" />
                   18617: |;
                   18618:     } else {
1.1181    raeburn  18619:         my $name_input;
                   18620:         if ($cnameelement ne '') {
                   18621:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   18622:                           $cnameelement.'" />';
                   18623:         }
                   18624:         $output .= qq|
1.1182    raeburn  18625: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   18626: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  18627: $name_input
                   18628: $roleelement
                   18629: $multelement
                   18630: $typeelement
                   18631: |;
                   18632:         if ($formname eq 'portform') {
                   18633:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   18634:         }
                   18635:     }
                   18636:     if ($fixeddom) {
                   18637:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   18638:     }
                   18639:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   18640:     if ($sincefilterform) {
                   18641:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   18642:                   .$sincefilterform
                   18643:                   .&Apache::lonhtmlcommon::row_closure();
                   18644:     }
                   18645:     if ($createdfilterform) {
                   18646:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   18647:                   .$createdfilterform
                   18648:                   .&Apache::lonhtmlcommon::row_closure();
                   18649:     }
                   18650:     if ($domainselectform) {
                   18651:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   18652:                   .$domainselectform
                   18653:                   .&Apache::lonhtmlcommon::row_closure();
                   18654:     }
                   18655:     if ($typeselectform) {
                   18656:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18657:             $output .= $typeselectform;
                   18658:         } else {
                   18659:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   18660:                       .$typeselectform
                   18661:                       .&Apache::lonhtmlcommon::row_closure();
                   18662:         }
                   18663:     }
                   18664:     if ($instcodeform) {
                   18665:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   18666:                   .$instcodeform
                   18667:                   .&Apache::lonhtmlcommon::row_closure();
                   18668:     }
                   18669:     if (exists($filter->{'ownerfilter'})) {
                   18670:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   18671:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18672:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   18673:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18674:                    $ownerdomselectform.'</td></tr></table>'.
                   18675:                    &Apache::lonhtmlcommon::row_closure();
                   18676:     }
                   18677:     if (exists($filter->{'personfilter'})) {
                   18678:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   18679:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18680:                    '<input type="text" name="personfilter" size="20" value="'.
                   18681:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18682:                    $persondomselectform.'</td></tr></table>'.
                   18683:                    &Apache::lonhtmlcommon::row_closure();
                   18684:     }
                   18685:     if (exists($filter->{'coursefilter'})) {
                   18686:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   18687:                   .'<input type="text" name="coursefilter" size="25" value="'
                   18688:                   .$list->{'coursefilter'}.'" />'
                   18689:                   .&Apache::lonhtmlcommon::row_closure();
                   18690:     }
                   18691:     if ($cloneableonlyform) {
                   18692:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   18693:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   18694:     }
                   18695:     if (exists($filter->{'descriptfilter'})) {
                   18696:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   18697:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   18698:                   .$list->{'descriptfilter'}.'" />'
                   18699:                   .&Apache::lonhtmlcommon::row_closure(1);
                   18700:     }
                   18701:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   18702:                '<input type="hidden" name="updater" value="" />'."\n".
                   18703:                '<input type="submit" name="gosearch" value="'.
                   18704:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   18705:     return $jscript.$clonewarning.$output;
                   18706: }
                   18707: 
                   18708: =pod 
                   18709: 
                   18710: =item * &timebased_select_form()
                   18711: 
1.1182    raeburn  18712: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  18713: filter e.g., Course Activity, Course Created, when searching for courses
                   18714: or communities
                   18715: 
                   18716: Inputs:
                   18717: 
                   18718: item - name of form element (sincefilter or createdfilter)
                   18719: 
                   18720: filter - anonymous hash of criteria and their values
                   18721: 
                   18722: Returns: HTML for a select box contained a blank, then six time selections,
                   18723:          with value set in incoming form variables currently selected. 
                   18724: 
                   18725: Side Effects: None
                   18726: 
                   18727: =cut
                   18728: 
                   18729: sub timebased_select_form {
                   18730:     my ($item,$filter) = @_;
                   18731:     if (ref($filter) eq 'HASH') {
                   18732:         $filter->{$item} =~ s/[^\d-]//g;
                   18733:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   18734:         return &select_form(
                   18735:                             $filter->{$item},
                   18736:                             $item,
                   18737:                             {      '-1' => '',
                   18738:                                 '86400' => &mt('today'),
                   18739:                                '604800' => &mt('last week'),
                   18740:                               '2592000' => &mt('last month'),
                   18741:                               '7776000' => &mt('last three months'),
                   18742:                              '15552000' => &mt('last six months'),
                   18743:                              '31104000' => &mt('last year'),
                   18744:                     'select_form_order' =>
                   18745:                            ['-1','86400','604800','2592000','7776000',
                   18746:                             '15552000','31104000']});
                   18747:     }
                   18748: }
                   18749: 
                   18750: =pod
                   18751: 
                   18752: =item * &js_changer()
                   18753: 
                   18754: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  18755: when course type or domain is changed, and also to hide 'Searching ...' on
                   18756: page load completion for page showing search result.
1.1181    raeburn  18757: 
                   18758: Inputs: None
                   18759: 
1.1183    raeburn  18760: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  18761: 
                   18762: Side Effects: None
                   18763: 
                   18764: =cut
                   18765: 
                   18766: sub js_changer {
                   18767:     return <<ENDJS;
                   18768: <script type="text/javascript">
                   18769: // <![CDATA[
                   18770: function updateFilters(caller) {
                   18771:     if (typeof(caller) != "undefined") {
                   18772:         document.filterpicker.updater.value = caller.name;
                   18773:     }
                   18774:     document.filterpicker.submit();
                   18775: }
1.1183    raeburn  18776: 
                   18777: function hideSearching() {
                   18778:     if (document.getElementById('searching')) {
                   18779:         document.getElementById('searching').style.display = 'none';
                   18780:     }
                   18781:     return;
                   18782: }
                   18783: 
1.1181    raeburn  18784: // ]]>
                   18785: </script>
                   18786: 
                   18787: ENDJS
                   18788: }
                   18789: 
                   18790: =pod
                   18791: 
1.1182    raeburn  18792: =item * &search_courses()
                   18793: 
                   18794: Process selected filters form course search form and pass to lonnet::courseiddump
                   18795: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18796: 
                   18797: Inputs:
                   18798: 
                   18799: dom - domain being searched 
                   18800: 
                   18801: type - course type ('Course' or 'Community' or '.' if any).
                   18802: 
                   18803: filter - anonymous hash of criteria and their values
                   18804: 
                   18805: numtitles - for institutional codes - number of categories
                   18806: 
                   18807: cloneruname - optional username of new course owner
                   18808: 
                   18809: clonerudom - optional domain of new course owner
                   18810: 
1.1221    raeburn  18811: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18812:             (used when DC is using course creation form)
                   18813: 
                   18814: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18815: 
1.1221    raeburn  18816: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18817:            (and so can clone automatically)
                   18818: 
                   18819: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18820: 
                   18821: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18822:               courses to clone 
1.1182    raeburn  18823: 
                   18824: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18825: 
                   18826: 
                   18827: Side Effects: None
                   18828: 
                   18829: =cut
                   18830: 
                   18831: 
                   18832: sub search_courses {
1.1221    raeburn  18833:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18834:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18835:     my (%courses,%showcourses,$cloner);
                   18836:     if (($filter->{'ownerfilter'} ne '') ||
                   18837:         ($filter->{'ownerdomfilter'} ne '')) {
                   18838:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18839:                                        $filter->{'ownerdomfilter'};
                   18840:     }
                   18841:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18842:         if (!$filter->{$item}) {
                   18843:             $filter->{$item}='.';
                   18844:         }
                   18845:     }
                   18846:     my $now = time;
                   18847:     my $timefilter =
                   18848:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18849:     my ($createdbefore,$createdafter);
                   18850:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18851:         $createdbefore = $now;
                   18852:         $createdafter = $now-$filter->{'createdfilter'};
                   18853:     }
                   18854:     my ($instcodefilter,$regexpok);
                   18855:     if ($numtitles) {
                   18856:         if ($env{'form.official'} eq 'on') {
                   18857:             $instcodefilter =
                   18858:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18859:             $regexpok = 1;
                   18860:         } elsif ($env{'form.official'} eq 'off') {
                   18861:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18862:             unless ($instcodefilter eq '') {
                   18863:                 $regexpok = -1;
                   18864:             }
                   18865:         }
                   18866:     } else {
                   18867:         $instcodefilter = $filter->{'instcodefilter'};
                   18868:     }
                   18869:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18870:     if ($type eq '') { $type = '.'; }
                   18871: 
                   18872:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18873:         $cloner = $cloneruname.':'.$clonerudom;
                   18874:     }
                   18875:     %courses = &Apache::lonnet::courseiddump($dom,
                   18876:                                              $filter->{'descriptfilter'},
                   18877:                                              $timefilter,
                   18878:                                              $instcodefilter,
                   18879:                                              $filter->{'combownerfilter'},
                   18880:                                              $filter->{'coursefilter'},
                   18881:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18882:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18883:                                              $filter->{'cloneableonly'},
                   18884:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18885:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18886:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18887:         my $ccrole;
                   18888:         if ($type eq 'Community') {
                   18889:             $ccrole = 'co';
                   18890:         } else {
                   18891:             $ccrole = 'cc';
                   18892:         }
                   18893:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18894:                                                      $filter->{'persondomfilter'},
                   18895:                                                      'userroles',undef,
                   18896:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18897:                                                      $dom);
                   18898:         foreach my $role (keys(%rolehash)) {
                   18899:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18900:             my $cid = $cdom.'_'.$cnum;
                   18901:             if (exists($courses{$cid})) {
                   18902:                 if (ref($courses{$cid}) eq 'HASH') {
                   18903:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18904:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18905:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18906:                         }
                   18907:                     } else {
                   18908:                         $courses{$cid}{roles} = [$courserole];
                   18909:                     }
                   18910:                     $showcourses{$cid} = $courses{$cid};
                   18911:                 }
                   18912:             }
                   18913:         }
                   18914:         %courses = %showcourses;
                   18915:     }
                   18916:     return %courses;
                   18917: }
                   18918: 
                   18919: =pod
                   18920: 
1.1181    raeburn  18921: =back
                   18922: 
1.1207    raeburn  18923: =head1 Routines for version requirements for current course.
                   18924: 
                   18925: =over 4
                   18926: 
                   18927: =item * &check_release_required()
                   18928: 
                   18929: Compares required LON-CAPA version with version on server, and
                   18930: if required version is newer looks for a server with the required version.
                   18931: 
                   18932: Looks first at servers in user's owen domain; if none suitable, looks at
                   18933: servers in course's domain are permitted to host sessions for user's domain.
                   18934: 
                   18935: Inputs:
                   18936: 
                   18937: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18938: 
                   18939: $courseid - Course ID of current course
                   18940: 
                   18941: $rolecode - User's current role in course (for switchserver query string).
                   18942: 
                   18943: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18944: 
                   18945: 
                   18946: Returns:
                   18947: 
                   18948: $switchserver - query string tp append to /adm/switchserver call (if 
                   18949:                 current server's LON-CAPA version is too old. 
                   18950: 
                   18951: $warning - Message is displayed if no suitable server could be found.
                   18952: 
                   18953: =cut
                   18954: 
                   18955: sub check_release_required {
                   18956:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18957:     my ($switchserver,$warning);
                   18958:     if ($required ne '') {
                   18959:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18960:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18961:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18962:             my $otherserver;
                   18963:             if (($major eq '' && $minor eq '') ||
                   18964:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18965:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18966:                 my $switchlcrev =
                   18967:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18968:                                                            $userdomserver);
                   18969:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18970:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18971:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18972:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18973:                     if ($cdom ne $env{'user.domain'}) {
                   18974:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18975:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18976:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18977:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18978:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18979:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18980:                         my $canhost =
                   18981:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18982:                                                               $coursedomserver,
                   18983:                                                               $remoterev,
                   18984:                                                               $udomdefaults{'remotesessions'},
                   18985:                                                               $defdomdefaults{'hostedsessions'});
                   18986: 
                   18987:                         if ($canhost) {
                   18988:                             $otherserver = $coursedomserver;
                   18989:                         } else {
                   18990:                             $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.");
                   18991:                         }
                   18992:                     } else {
                   18993:                         $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).");
                   18994:                     }
                   18995:                 } else {
                   18996:                     $otherserver = $userdomserver;
                   18997:                 }
                   18998:             }
                   18999:             if ($otherserver ne '') {
                   19000:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   19001:             }
                   19002:         }
                   19003:     }
                   19004:     return ($switchserver,$warning);
                   19005: }
                   19006: 
                   19007: =pod
                   19008: 
                   19009: =item * &check_release_result()
                   19010: 
                   19011: Inputs:
                   19012: 
                   19013: $switchwarning - Warning message if no suitable server found to host session.
                   19014: 
                   19015: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   19016:                 and current role.
                   19017: 
                   19018: Returns: HTML to display with information about requirement to switch server.
                   19019:          Either displaying warning with link to Roles/Courses screen or
                   19020:          display link to switchserver.
                   19021: 
1.1181    raeburn  19022: =cut
                   19023: 
1.1207    raeburn  19024: sub check_release_result {
                   19025:     my ($switchwarning,$switchserver) = @_;
                   19026:     my $output = &start_page('Selected course unavailable on this server').
                   19027:                  '<p class="LC_warning">';
                   19028:     if ($switchwarning) {
                   19029:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   19030:         if (&show_course()) {
                   19031:             $output .= &mt('Display courses');
                   19032:         } else {
                   19033:             $output .= &mt('Display roles');
                   19034:         }
                   19035:         $output .= '</a>';
                   19036:     } elsif ($switchserver) {
                   19037:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   19038:                    '<br />'.
                   19039:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   19040:                    &mt('Switch Server').
                   19041:                    '</a>';
                   19042:     }
                   19043:     $output .= '</p>'.&end_page();
                   19044:     return $output;
                   19045: }
                   19046: 
                   19047: =pod
                   19048: 
                   19049: =item * &needs_coursereinit()
                   19050: 
                   19051: Determine if course contents stored for user's session needs to be
                   19052: refreshed, because content has changed since "Big Hash" last tied.
                   19053: 
                   19054: Check for change is made if time last checked is more than 10 minutes ago
                   19055: (by default).
                   19056: 
                   19057: Inputs:
                   19058: 
                   19059: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   19060: 
                   19061: $interval (optional) - Time which may elapse (in s) between last check for content
                   19062:                        change in current course. (default: 600 s).  
                   19063: 
                   19064: Returns: an array; first element is:
                   19065: 
                   19066: =over 4
                   19067: 
                   19068: 'switch' - if content updates mean user's session
                   19069:            needs to be switched to a server running a newer LON-CAPA version
                   19070:  
                   19071: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   19072:            on current server hosting user's session                
                   19073: 
                   19074: ''       - if no action required.
                   19075: 
                   19076: =back
                   19077: 
                   19078: If first item element is 'switch':
                   19079: 
                   19080: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   19081: 
                   19082: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   19083:                               and current role. 
                   19084: 
                   19085: otherwise: no other elements returned.
                   19086: 
                   19087: =back
                   19088: 
                   19089: =cut
                   19090: 
                   19091: sub needs_coursereinit {
                   19092:     my ($loncaparev,$interval) = @_;
                   19093:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   19094:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19095:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   19096:     my $now = time;
                   19097:     if ($interval eq '') {
                   19098:         $interval = 600;
                   19099:     }
                   19100:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  19101:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  19102:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19103:         if ($blocked) {
                   19104:             return ();
                   19105:         }
1.1391    raeburn  19106:         my $update;
                   19107:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19108:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   19109:         if ($lastmainchange > $env{'request.course.tied'}) {
                   19110:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19111:             if ($needswitch) {
                   19112:                 return ('switch',$switchwarning,$switchserver);
                   19113:             }
                   19114:             $update = 'main';
                   19115:         }
                   19116:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   19117:             if ($update) {
                   19118:                 $update = 'both';
                   19119:             } else {
                   19120:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19121:                 if ($needswitch) {
                   19122:                     return ('switch',$switchwarning,$switchserver);
                   19123:                 } else {
                   19124:                     $update = 'supp';
1.1207    raeburn  19125:                 }
                   19126:             }
1.1391    raeburn  19127:         }
1.1453    raeburn  19128:         return ($update);
1.1391    raeburn  19129:     }
                   19130:     return ();
                   19131: }
                   19132: 
                   19133: sub switch_for_update {
                   19134:     my ($loncaparev,$cdom,$cnum) = @_;
                   19135:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19136:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   19137:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   19138:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   19139:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   19140:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   19141:             my ($switchserver,$switchwarning) =
                   19142:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   19143:                                         $curr_reqd_hash{'internal.releaserequired'});
                   19144:             if ($switchwarning ne '' || $switchserver ne '') {
                   19145:                 return ('switch',$switchwarning,$switchserver);
                   19146:             }
1.1207    raeburn  19147:         }
                   19148:     }
                   19149:     return ();
                   19150: }
1.1181    raeburn  19151: 
1.1083    raeburn  19152: sub update_content_constraints {
1.1395    raeburn  19153:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  19154:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19155:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  19156:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  19157:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  19158:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  19159:         if ($item eq 'resourcetag') {
                   19160:             if ($name eq 'responsetype') {
                   19161:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   19162:             }
1.1307    raeburn  19163:         } elsif ($item eq 'course') {
                   19164:             if ($name eq 'courserestype') {
                   19165:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   19166:             }
1.1083    raeburn  19167:         }
                   19168:     }
                   19169:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19170:     if (defined($navmap)) {
1.1307    raeburn  19171:         my (%allresponses,%allcrsrestypes);
                   19172:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   19173:             if ($res->is_tool()) {
                   19174:                 if ($allcrsrestypes{'exttool'}) {
                   19175:                     $allcrsrestypes{'exttool'} ++;
                   19176:                 } else {
                   19177:                     $allcrsrestypes{'exttool'} = 1;
                   19178:                 }
                   19179:                 next;
                   19180:             }
1.1083    raeburn  19181:             my %responses = $res->responseTypes();
                   19182:             foreach my $key (keys(%responses)) {
                   19183:                 next unless(exists($checkresponsetypes{$key}));
                   19184:                 $allresponses{$key} += $responses{$key};
                   19185:             }
                   19186:         }
                   19187:         foreach my $key (keys(%allresponses)) {
                   19188:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   19189:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19190:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19191:             }
                   19192:         }
1.1307    raeburn  19193:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  19194:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  19195:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19196:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19197:             }
                   19198:         }
1.1083    raeburn  19199:         undef($navmap);
                   19200:     }
1.1391    raeburn  19201:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  19202:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   19203:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19204:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   19205:         }
                   19206:     }
1.1083    raeburn  19207:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   19208:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   19209:     }
                   19210:     return;
                   19211: }
                   19212: 
1.1110    raeburn  19213: sub allmaps_incourse {
                   19214:     my ($cdom,$cnum,$chome,$cid) = @_;
                   19215:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   19216:         $cid = $env{'request.course.id'};
                   19217:         $cdom = $env{'course.'.$cid.'.domain'};
                   19218:         $cnum = $env{'course.'.$cid.'.num'};
                   19219:         $chome = $env{'course.'.$cid.'.home'};
                   19220:     }
                   19221:     my %allmaps = ();
                   19222:     my $lastchange =
                   19223:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19224:     if ($lastchange > $env{'request.course.tied'}) {
                   19225:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   19226:         unless ($ferr) {
1.1395    raeburn  19227:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  19228:         }
                   19229:     }
                   19230:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19231:     if (defined($navmap)) {
                   19232:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   19233:             $allmaps{$res->src()} = 1;
                   19234:         }
                   19235:     }
                   19236:     return \%allmaps;
                   19237: }
                   19238: 
1.1083    raeburn  19239: sub parse_supplemental_title {
                   19240:     my ($title) = @_;
                   19241: 
                   19242:     my ($foldertitle,$renametitle);
                   19243:     if ($title =~ /&amp;&amp;&amp;/) {
                   19244:         $title = &HTML::Entites::decode($title);
                   19245:     }
                   19246:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   19247:         $renametitle=$4;
                   19248:         my ($time,$uname,$udom) = ($1,$2,$3);
                   19249:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   19250:         my $name =  &plainname($uname,$udom);
                   19251:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   19252:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1401    raeburn  19253:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
1.1402    raeburn  19254:         if ($foldertitle ne '') {
1.1401    raeburn  19255:             $title .= ': <br />'.$foldertitle;
                   19256:         }
1.1083    raeburn  19257:     }
                   19258:     if (wantarray) {
                   19259:         return ($title,$foldertitle,$renametitle);
                   19260:     }
                   19261:     return $title;
                   19262: }
                   19263: 
1.1395    raeburn  19264: sub get_supplemental {
                   19265:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   19266:     my $hashid=$cnum.':'.$cdom;
                   19267:     my ($supplemental,$cached,$set_httprefs);
                   19268:     unless ($ignorecache) {
                   19269:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   19270:     }
                   19271:     unless (defined($cached)) {
                   19272:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   19273:         unless ($chome eq 'no_host') {
                   19274:             my @order = @LONCAPA::map::order;
                   19275:             my @resources = @LONCAPA::map::resources;
                   19276:             my @resparms = @LONCAPA::map::resparms;
                   19277:             my @zombies = @LONCAPA::map::zombies;
                   19278:             my ($errors,%ids,%hidden);
                   19279:             $errors =
                   19280:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   19281:                                       $errors,$possdel,\%ids,\%hidden);
                   19282:             @LONCAPA::map::order = @order;
                   19283:             @LONCAPA::map::resources = @resources;
                   19284:             @LONCAPA::map::resparms = @resparms;
                   19285:             @LONCAPA::map::zombies = @zombies;
                   19286:             $set_httprefs = 1;
                   19287:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19288:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19289:             }
                   19290:             $supplemental = {
                   19291:                                ids => \%ids,
                   19292:                                hidden => \%hidden,
                   19293:                             };
                   19294:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   19295:         }
                   19296:     }
                   19297:     return ($supplemental,$set_httprefs);
                   19298: }
                   19299: 
1.1143    raeburn  19300: sub recurse_supplemental {
1.1391    raeburn  19301:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   19302:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   19303:         my $mapnum;
                   19304:         if ($suppmap eq 'supplemental.sequence') {
                   19305:             $mapnum = 0;
                   19306:         } else {
                   19307:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   19308:         }
1.1143    raeburn  19309:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   19310:         if ($fatal) {
                   19311:             $errors ++;
                   19312:         } else {
1.1389    raeburn  19313:             my @order = @LONCAPA::map::order;
                   19314:             if (@order > 0) {
                   19315:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  19316:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  19317:                 foreach my $idx (@order) {
                   19318:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  19319:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  19320:                         my $id = $mapnum.':'.$idx;
                   19321:                         push(@{$suppids->{$src}},$id);
                   19322:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   19323:                             $hiddensupp->{$id} = 1;
                   19324:                         }
1.1146    raeburn  19325:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  19326:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   19327:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  19328:                         } else {
1.1391    raeburn  19329:                             my $allowed;
                   19330:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   19331:                                 $allowed = 1;
                   19332:                             } elsif ($possdel) {
                   19333:                                 foreach my $item (@{$suppids->{$src}}) {
                   19334:                                     next if ($item eq $id);
                   19335:                                     unless ($hiddensupp->{$item}) {
                   19336:                                        $allowed = 1;
                   19337:                                        last;
                   19338:                                     }
                   19339:                                 }
                   19340:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   19341:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   19342:                                 }
                   19343:                             }
                   19344:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   19345:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  19346:                             }
1.1143    raeburn  19347:                         }
                   19348:                     }
                   19349:                 }
                   19350:             }
                   19351:         }
                   19352:     }
1.1391    raeburn  19353:     return $errors;
                   19354: }
                   19355: 
                   19356: sub set_supp_httprefs {
                   19357:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   19358:     if (ref($supplemental) eq 'HASH') {
                   19359:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   19360:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   19361:                 next if ($src =~ /\.sequence$/);
                   19362:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   19363:                     my $allowed;
                   19364:                     if ($env{'request.role.adv'}) {
                   19365:                         $allowed = 1;
                   19366:                     } else {
                   19367:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   19368:                             unless ($supplemental->{'hidden'}->{$id}) {
                   19369:                                 $allowed = 1;
                   19370:                                 last;
                   19371:                             }
                   19372:                         }
                   19373:                     }
                   19374:                     if (exists($env{'httpref.'.$src})) {
                   19375:                         if ($possdel) {
                   19376:                             unless ($allowed) {
                   19377:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   19378:                             }
                   19379:                         }
                   19380:                     } elsif ($allowed) {
                   19381:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   19382:                     }
                   19383:                 }
                   19384:             }
                   19385:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19386:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19387:             }
                   19388:         }
                   19389:     }
                   19390: }
                   19391: 
                   19392: sub get_supp_parameter {
                   19393:     my ($resparm,$name)=@_;
                   19394:     return if ($resparm eq '');
                   19395:     my $value=undef;
                   19396:     my $ptype=undef;
                   19397:     foreach (split('&&&',$resparm)) {
                   19398:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   19399:         if ($thisname eq $name) {
                   19400:             $value=$thisvalue;
                   19401:             $ptype=$thistype;
                   19402:         }
                   19403:     }
                   19404:     return $value;
1.1143    raeburn  19405: }
                   19406: 
1.1101    raeburn  19407: sub symb_to_docspath {
1.1267    raeburn  19408:     my ($symb,$navmapref) = @_;
                   19409:     return unless ($symb && ref($navmapref));
1.1101    raeburn  19410:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   19411:     if ($resurl=~/\.(sequence|page)$/) {
                   19412:         $mapurl=$resurl;
                   19413:     } elsif ($resurl eq 'adm/navmaps') {
                   19414:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   19415:     }
                   19416:     my $mapresobj;
1.1267    raeburn  19417:     unless (ref($$navmapref)) {
                   19418:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   19419:     }
                   19420:     if (ref($$navmapref)) {
                   19421:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  19422:     }
                   19423:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   19424:     my $type=$2;
                   19425:     my $path;
                   19426:     if (ref($mapresobj)) {
                   19427:         my $pcslist = $mapresobj->map_hierarchy();
                   19428:         if ($pcslist ne '') {
                   19429:             foreach my $pc (split(/,/,$pcslist)) {
                   19430:                 next if ($pc <= 1);
1.1267    raeburn  19431:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  19432:                 if (ref($res)) {
                   19433:                     my $thisurl = $res->src();
                   19434:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   19435:                     my $thistitle = $res->title();
                   19436:                     $path .= '&'.
                   19437:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  19438:                              &escape($thistitle).
1.1101    raeburn  19439:                              ':'.$res->randompick().
                   19440:                              ':'.$res->randomout().
                   19441:                              ':'.$res->encrypted().
                   19442:                              ':'.$res->randomorder().
                   19443:                              ':'.$res->is_page();
                   19444:                 }
                   19445:             }
                   19446:         }
                   19447:         $path =~ s/^\&//;
                   19448:         my $maptitle = $mapresobj->title();
                   19449:         if ($mapurl eq 'default') {
1.1129    raeburn  19450:             $maptitle = 'Main Content';
1.1101    raeburn  19451:         }
                   19452:         $path .= (($path ne '')? '&' : '').
                   19453:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19454:                  &escape($maptitle).
1.1101    raeburn  19455:                  ':'.$mapresobj->randompick().
                   19456:                  ':'.$mapresobj->randomout().
                   19457:                  ':'.$mapresobj->encrypted().
                   19458:                  ':'.$mapresobj->randomorder().
                   19459:                  ':'.$mapresobj->is_page();
                   19460:     } else {
                   19461:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   19462:         my $ispage = (($type eq 'page')? 1 : '');
                   19463:         if ($mapurl eq 'default') {
1.1129    raeburn  19464:             $maptitle = 'Main Content';
1.1101    raeburn  19465:         }
                   19466:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19467:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  19468:     }
                   19469:     unless ($mapurl eq 'default') {
                   19470:         $path = 'default&'.
1.1146    raeburn  19471:                 &escape('Main Content').
1.1101    raeburn  19472:                 ':::::&'.$path;
                   19473:     }
                   19474:     return $path;
                   19475: }
                   19476: 
1.1393    raeburn  19477: sub validate_folderpath {
                   19478:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   19479:     if ($env{'form.folderpath'} ne '') {
                   19480:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  19481:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  19482:         for (my $i=0; $i<@items; $i++) {
                   19483:             my $odd = $i%2;
                   19484:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   19485:                 $badpath = 1;
1.1394    raeburn  19486:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  19487:                 my $idx = $i-1;
1.1394    raeburn  19488:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   19489:                     my $esc_name = $1;
                   19490:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   19491:                         $supppath .= '&'.$esc_name;
                   19492:                         $changed = 1;
                   19493:                     } else {
                   19494:                         $supppath .= '&'.$items[$i];
                   19495:                     }
                   19496:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   19497:                     $changed = 1;
1.1393    raeburn  19498:                     my $is_hidden;
                   19499:                     unless ($got_supp) {
1.1395    raeburn  19500:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  19501:                         if (ref($supplemental) eq 'HASH') {
                   19502:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   19503:                                 %supphidden = %{$supplemental->{'hidden'}};
                   19504:                             }
                   19505:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   19506:                                 %suppids = %{$supplemental->{'ids'}};
                   19507:                             }
                   19508:                         }
                   19509:                         $got_supp = 1;
                   19510:                     }
                   19511:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   19512:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   19513:                         if ($supphidden{$mapid}) {
                   19514:                             $is_hidden = 1;
                   19515:                         }
                   19516:                     }
1.1394    raeburn  19517:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   19518:                 } else {
                   19519:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  19520:                 }
                   19521:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   19522:                 $badpath = 1;
1.1394    raeburn  19523:             } elsif ($supplementalflag) {
1.1393    raeburn  19524:                 $supppath .= '&'.$items[$i];
                   19525:             }
                   19526:             last if ($badpath);
                   19527:         }
                   19528:         if ($badpath) {
                   19529:             delete($env{'form.folderpath'});
1.1394    raeburn  19530:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  19531:             $supppath =~ s/^\&//;
                   19532:             $env{'form.folderpath'} = $supppath;
                   19533:         }
                   19534:     }
                   19535:     return;
                   19536: }
                   19537: 
1.1094    raeburn  19538: sub captcha_display {
1.1327    raeburn  19539:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19540:     my ($output,$error);
1.1234    raeburn  19541:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  19542:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19543:     if ($captcha eq 'original') {
1.1094    raeburn  19544:         $output = &create_captcha();
                   19545:         unless ($output) {
1.1172    raeburn  19546:             $error = 'captcha';
1.1094    raeburn  19547:         }
                   19548:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19549:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  19550:         unless ($output) {
1.1172    raeburn  19551:             $error = 'recaptcha';
1.1094    raeburn  19552:         }
                   19553:     }
1.1234    raeburn  19554:     return ($output,$error,$captcha,$version);
1.1094    raeburn  19555: }
                   19556: 
                   19557: sub captcha_response {
1.1327    raeburn  19558:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19559:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  19560:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19561:     if ($captcha eq 'original') {
1.1094    raeburn  19562:         ($captcha_chk,$captcha_error) = &check_captcha();
                   19563:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19564:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  19565:     } else {
                   19566:         $captcha_chk = 1;
                   19567:     }
                   19568:     return ($captcha_chk,$captcha_error);
                   19569: }
                   19570: 
                   19571: sub get_captcha_config {
1.1327    raeburn  19572:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  19573:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  19574:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   19575:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   19576:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  19577:     if ($context eq 'usercreation') {
                   19578:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   19579:         if (ref($domconfig{$context}) eq 'HASH') {
                   19580:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   19581:             if (ref($hashtocheck) eq 'HASH') {
                   19582:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   19583:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   19584:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   19585:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   19586:                     }
                   19587:                     if ($privkey && $pubkey) {
                   19588:                         $captcha = 'recaptcha';
1.1234    raeburn  19589:                         $version = $hashtocheck->{'recaptchaversion'};
                   19590:                         if ($version ne '2') {
                   19591:                             $version = 1;
                   19592:                         }
1.1095    raeburn  19593:                     } else {
                   19594:                         $captcha = 'original';
                   19595:                     }
                   19596:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   19597:                     $captcha = 'original';
                   19598:                 }
1.1094    raeburn  19599:             }
1.1095    raeburn  19600:         } else {
                   19601:             $captcha = 'captcha';
                   19602:         }
                   19603:     } elsif ($context eq 'login') {
                   19604:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   19605:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   19606:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   19607:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  19608:             if ($privkey && $pubkey) {
                   19609:                 $captcha = 'recaptcha';
1.1234    raeburn  19610:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   19611:                 if ($version ne '2') {
                   19612:                     $version = 1; 
                   19613:                 }
1.1095    raeburn  19614:             } else {
                   19615:                 $captcha = 'original';
1.1094    raeburn  19616:             }
1.1095    raeburn  19617:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   19618:             $captcha = 'original';
1.1094    raeburn  19619:         }
1.1327    raeburn  19620:     } elsif ($context eq 'passwords') {
                   19621:         if ($dom_in_effect) {
                   19622:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   19623:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   19624:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   19625:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   19626:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   19627:                 }
                   19628:                 if ($privkey && $pubkey) {
                   19629:                     $captcha = 'recaptcha';
                   19630:                     $version = $passwdconf{'recaptchaversion'};
                   19631:                     if ($version ne '2') {
                   19632:                         $version = 1;
                   19633:                     }
                   19634:                 } else {
                   19635:                     $captcha = 'original';
                   19636:                 }
                   19637:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   19638:                 $captcha = 'original';
                   19639:             }
                   19640:         }
                   19641:     } 
1.1234    raeburn  19642:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  19643: }
                   19644: 
                   19645: sub create_captcha {
                   19646:     my %captcha_params = &captcha_settings();
                   19647:     my ($output,$maxtries,$tries) = ('',10,0);
                   19648:     while ($tries < $maxtries) {
                   19649:         $tries ++;
                   19650:         my $captcha = Authen::Captcha->new (
                   19651:                                            output_folder => $captcha_params{'output_dir'},
                   19652:                                            data_folder   => $captcha_params{'db_dir'},
                   19653:                                           );
                   19654:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   19655: 
                   19656:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   19657:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  19658:                       '<span class="LC_nobreak">'.
1.1453    raeburn  19659:                       '<label>'.&mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1390    raeburn  19660:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1453    raeburn  19661:                       '</label></span><br />'.
1.1176    raeburn  19662:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  19663:             last;
                   19664:         }
                   19665:     }
1.1323    raeburn  19666:     if ($output eq '') {
                   19667:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   19668:     }
1.1094    raeburn  19669:     return $output;
                   19670: }
                   19671: 
                   19672: sub captcha_settings {
                   19673:     my %captcha_params = (
                   19674:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   19675:                            www_output_dir => "/captchaspool",
                   19676:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   19677:                            numchars       => '5',
                   19678:                          );
                   19679:     return %captcha_params;
                   19680: }
                   19681: 
                   19682: sub check_captcha {
                   19683:     my ($captcha_chk,$captcha_error);
                   19684:     my $code = $env{'form.code'};
                   19685:     my $md5sum = $env{'form.crypt'};
                   19686:     my %captcha_params = &captcha_settings();
                   19687:     my $captcha = Authen::Captcha->new(
                   19688:                       output_folder => $captcha_params{'output_dir'},
                   19689:                       data_folder   => $captcha_params{'db_dir'},
                   19690:                   );
1.1109    raeburn  19691:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  19692:     my %captcha_hash = (
                   19693:                         0       => 'Code not checked (file error)',
                   19694:                        -1      => 'Failed: code expired',
                   19695:                        -2      => 'Failed: invalid code (not in database)',
                   19696:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   19697:     );
                   19698:     if ($captcha_chk != 1) {
                   19699:         $captcha_error = $captcha_hash{$captcha_chk}
                   19700:     }
                   19701:     return ($captcha_chk,$captcha_error);
                   19702: }
                   19703: 
                   19704: sub create_recaptcha {
1.1234    raeburn  19705:     my ($pubkey,$version) = @_;
                   19706:     if ($version >= 2) {
1.1367    raeburn  19707:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   19708:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  19709:     } else {
                   19710:         my $use_ssl;
                   19711:         if ($ENV{'SERVER_PORT'} == 443) {
                   19712:             $use_ssl = 1;
                   19713:         }
                   19714:         my $captcha = Captcha::reCAPTCHA->new;
                   19715:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   19716:                $captcha->get_html($pubkey,undef,$use_ssl).
                   19717:                &mt('If the text is hard to read, [_1] will replace them.',
                   19718:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   19719:                '<br /><br />';
                   19720:     }
1.1094    raeburn  19721: }
                   19722: 
                   19723: sub check_recaptcha {
1.1234    raeburn  19724:     my ($privkey,$version) = @_;
1.1094    raeburn  19725:     my $captcha_chk;
1.1350    raeburn  19726:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  19727:     if ($version >= 2) {
                   19728:         my %info = (
                   19729:                      secret   => $privkey, 
                   19730:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  19731:                      remoteip => $ip,
1.1234    raeburn  19732:                    );
1.1280    raeburn  19733:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   19734:         $request->content(join('&',map {
                   19735:                          my $name = escape($_);
                   19736:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   19737:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   19738:                          : &escape($info{$_}) );
                   19739:         } keys(%info)));
                   19740:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  19741:         if ($response->is_success)  {
                   19742:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   19743:             if (ref($data) eq 'HASH') {
                   19744:                 if ($data->{'success'}) {
                   19745:                     $captcha_chk = 1;
                   19746:                 }
                   19747:             }
                   19748:         }
                   19749:     } else {
                   19750:         my $captcha = Captcha::reCAPTCHA->new;
                   19751:         my $captcha_result =
                   19752:             $captcha->check_answer(
                   19753:                                     $privkey,
1.1350    raeburn  19754:                                     $ip,
1.1234    raeburn  19755:                                     $env{'form.recaptcha_challenge_field'},
                   19756:                                     $env{'form.recaptcha_response_field'},
                   19757:                                   );
                   19758:         if ($captcha_result->{is_valid}) {
                   19759:             $captcha_chk = 1;
                   19760:         }
1.1094    raeburn  19761:     }
                   19762:     return $captcha_chk;
                   19763: }
                   19764: 
1.1174    raeburn  19765: sub emailusername_info {
1.1244    raeburn  19766:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  19767:     my %titles = &Apache::lonlocal::texthash (
                   19768:                      lastname      => 'Last Name',
                   19769:                      firstname     => 'First Name',
                   19770:                      institution   => 'School/college/university',
                   19771:                      location      => "School's city, state/province, country",
                   19772:                      web           => "School's web address",
                   19773:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  19774:                      id            => 'Student/Employee ID',
1.1174    raeburn  19775:                  );
                   19776:     return (\@fields,\%titles);
                   19777: }
                   19778: 
1.1161    raeburn  19779: sub cleanup_html {
                   19780:     my ($incoming) = @_;
                   19781:     my $outgoing;
                   19782:     if ($incoming ne '') {
                   19783:         $outgoing = $incoming;
                   19784:         $outgoing =~ s/;/&#059;/g;
                   19785:         $outgoing =~ s/\#/&#035;/g;
                   19786:         $outgoing =~ s/\&/&#038;/g;
                   19787:         $outgoing =~ s/</&#060;/g;
                   19788:         $outgoing =~ s/>/&#062;/g;
                   19789:         $outgoing =~ s/\(/&#040/g;
                   19790:         $outgoing =~ s/\)/&#041;/g;
                   19791:         $outgoing =~ s/"/&#034;/g;
                   19792:         $outgoing =~ s/'/&#039;/g;
                   19793:         $outgoing =~ s/\$/&#036;/g;
                   19794:         $outgoing =~ s{/}{&#047;}g;
                   19795:         $outgoing =~ s/=/&#061;/g;
                   19796:         $outgoing =~ s/\\/&#092;/g
                   19797:     }
                   19798:     return $outgoing;
                   19799: }
                   19800: 
1.1190    musolffc 19801: # Checks for critical messages and returns a redirect url if one exists.
                   19802: # $interval indicates how often to check for messages.
1.1282    raeburn  19803: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19804: sub critical_redirect {
1.1282    raeburn  19805:     my ($interval,$context) = @_;
1.1356    raeburn  19806:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19807:         return ();
                   19808:     }
1.1190    musolffc 19809:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19810:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19811:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19812:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19813:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19814:             if ($blocked) {
                   19815:                 my $checkrole = "cm./$cdom/$cnum";
                   19816:                 if ($env{'request.course.sec'} ne '') {
                   19817:                     $checkrole .= "/$env{'request.course.sec'}";
                   19818:                 }
                   19819:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19820:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19821:                     return;
                   19822:                 }
                   19823:             }
                   19824:         }
1.1190    musolffc 19825:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19826:                                         $env{'user.name'});
                   19827:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19828:         my $redirecturl;
1.1190    musolffc 19829:         if ($what[0]) {
1.1356    raeburn  19830: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19831: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19832: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19833:                 return (1, $url);
1.1190    musolffc 19834:             }
1.1191    raeburn  19835:         }
                   19836:     } 
                   19837:     return ();
1.1190    musolffc 19838: }
                   19839: 
1.1174    raeburn  19840: # Use:
                   19841: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19842: #
                   19843: ##################################################
                   19844: #          password associated functions         #
                   19845: ##################################################
                   19846: sub des_keys {
                   19847:     # Make a new key for DES encryption.
                   19848:     # Each key has two parts which are returned separately.
                   19849:     # Please note:  Each key must be passed through the &hex function
                   19850:     # before it is output to the web browser.  The hex versions cannot
                   19851:     # be used to decrypt.
                   19852:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19853:                 '8','9','a','b','c','d','e','f');
                   19854:     my $lkey='';
                   19855:     for (0..7) {
                   19856:         $lkey.=$hexstr[rand(15)];
                   19857:     }
                   19858:     my $ukey='';
                   19859:     for (0..7) {
                   19860:         $ukey.=$hexstr[rand(15)];
                   19861:     }
                   19862:     return ($lkey,$ukey);
                   19863: }
                   19864: 
                   19865: sub des_decrypt {
                   19866:     my ($key,$cyphertext) = @_;
                   19867:     my $keybin=pack("H16",$key);
                   19868:     my $cypher;
                   19869:     if ($Crypt::DES::VERSION>=2.03) {
                   19870:         $cypher=new Crypt::DES $keybin;
                   19871:     } else {
                   19872:         $cypher=new DES $keybin;
                   19873:     }
1.1233    raeburn  19874:     my $plaintext='';
                   19875:     my $cypherlength = length($cyphertext);
                   19876:     my $numchunks = int($cypherlength/32);
                   19877:     for (my $j=0; $j<$numchunks; $j++) {
                   19878:         my $start = $j*32;
                   19879:         my $cypherblock = substr($cyphertext,$start,32);
                   19880:         my $chunk =
                   19881:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   19882:         $chunk .=
                   19883:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   19884:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   19885:         $plaintext .= $chunk;
                   19886:     }
1.1174    raeburn  19887:     return $plaintext;
                   19888: }
                   19889: 
1.1344    raeburn  19890: sub get_requested_shorturls {
1.1309    raeburn  19891:     my ($cdom,$cnum,$navmap) = @_;
                   19892:     return unless (ref($navmap));
1.1344    raeburn  19893:     my ($numnew,$errors);
1.1309    raeburn  19894:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   19895:     if (@toshorten) {
                   19896:         my (%maps,%resources,%titles);
                   19897:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   19898:                                                                'shorturls',$cdom,$cnum);
                   19899:         if (keys(%resources)) {
1.1344    raeburn  19900:             my %tocreate;
1.1309    raeburn  19901:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   19902:                 my $symb = $resources{$item};
                   19903:                 if ($symb) {
                   19904:                     $tocreate{$cnum.'&'.$symb} = 1;
                   19905:                 }
                   19906:             }
1.1344    raeburn  19907:             if (keys(%tocreate)) {
                   19908:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   19909:                                                       \%tocreate);
                   19910:             }
1.1309    raeburn  19911:         }
1.1344    raeburn  19912:     }
                   19913:     return ($numnew,$errors);
                   19914: }
                   19915: 
                   19916: sub make_short_symbs {
                   19917:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   19918:     my ($numnew,@errors);
                   19919:     if (ref($tocreateref) eq 'HASH') {
                   19920:         my %tocreate = %{$tocreateref};
1.1309    raeburn  19921:         if (keys(%tocreate)) {
                   19922:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   19923:             my $su = Short::URL->new(no_vowels => 1);
                   19924:             my $init = '';
                   19925:             my (%newunique,%addcourse,%courseonly,%failed);
                   19926:             # get lock on tiny db
                   19927:             my $now = time;
1.1344    raeburn  19928:             if ($lockuser eq '') {
                   19929:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   19930:             }
1.1309    raeburn  19931:             my $lockhash = {
1.1344    raeburn  19932:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  19933:                             };
                   19934:             my $tries = 0;
                   19935:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19936:             my ($code,$error);
                   19937:             while (($gotlock ne 'ok') && ($tries<3)) {
                   19938:                 $tries ++;
                   19939:                 sleep 1;
1.1319    raeburn  19940:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  19941:             }
                   19942:             if ($gotlock eq 'ok') {
                   19943:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   19944:                                        \%addcourse,\%courseonly,\%failed);
                   19945:                 if (keys(%failed)) {
                   19946:                     my $numfailed = scalar(keys(%failed));
                   19947:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   19948:                 }
                   19949:                 if (keys(%newunique)) {
                   19950:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   19951:                     if ($putres eq 'ok') {
                   19952:                         $numnew = scalar(keys(%newunique));
                   19953:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   19954:                         unless ($newputres eq 'ok') {
                   19955:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   19956:                         }
                   19957:                     } else {
                   19958:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   19959:                     }
                   19960:                 }
                   19961:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   19962:                 unless ($dellockres eq 'ok') {
                   19963:                     push(@errors,&mt('error: could not release lockfile'));
                   19964:                 }
                   19965:             } else {
                   19966:                 push(@errors,&mt('error: could not obtain lockfile'));
                   19967:             }
                   19968:             if (keys(%courseonly)) {
                   19969:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19970:                 if ($result ne 'ok') {
                   19971:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19972:                 }
                   19973:             }
                   19974:         }
                   19975:     }
                   19976:     return ($numnew,\@errors);
                   19977: }
                   19978: 
                   19979: sub shorten_symbs {
                   19980:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19981:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19982:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19983:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19984:     my (%possibles,%collisions);
                   19985:     foreach my $key (keys(%{$tocreate})) {
                   19986:         my $num = String::CRC32::crc32($key);
                   19987:         my $tiny = $su->encode($num,$init);
                   19988:         if ($tiny) {
                   19989:             $possibles{$tiny} = $key;
                   19990:         }
                   19991:     }
                   19992:     if (!$init) {
                   19993:         $init = 1;
                   19994:     } else {
                   19995:         $init ++;
                   19996:     }
                   19997:     if (keys(%possibles)) {
                   19998:         my @posstiny = keys(%possibles);
                   19999:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   20000:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   20001:         if (keys(%currtiny)) {
                   20002:             foreach my $key (keys(%currtiny)) {
                   20003:                 next if ($currtiny{$key} eq '');
                   20004:                 if ($currtiny{$key} eq $possibles{$key}) {
                   20005:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   20006:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   20007:                         $courseonly->{$tsymb} = $key;
                   20008:                     }
                   20009:                 } else {
                   20010:                     $collisions{$possibles{$key}} = 1;
                   20011:                 }
                   20012:                 delete($possibles{$key});
                   20013:             }
                   20014:         }
                   20015:         foreach my $key (keys(%possibles)) {
                   20016:             $newunique->{$key} = $possibles{$key};
                   20017:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   20018:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   20019:                 $addcourse->{$tsymb} = $key;
                   20020:             }
                   20021:         }
                   20022:     }
                   20023:     if (keys(%collisions)) {
                   20024:         if ($init <5) {
                   20025:             if (!$init) {
                   20026:                 $init = 1;
                   20027:             } else {
                   20028:                 $init ++;
                   20029:             }
                   20030:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   20031:                                    $newunique,$addcourse,$courseonly,$failed);
                   20032:         } else {
                   20033:             foreach my $key (keys(%collisions)) {
                   20034:                 $failed->{$key} = 1;
                   20035:             }
                   20036:         }
                   20037:     }
                   20038:     return $init;
                   20039: }
                   20040: 
1.1328    raeburn  20041: sub is_nonframeable {
1.1329    raeburn  20042:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   20043:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  20044:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  20045: 
                   20046:     $remprotocol = lc($remprotocol);
                   20047:     $remhost = lc($remhost);
                   20048:     my $remport = 80;
                   20049:     if ($remprotocol eq 'https') {
                   20050:         $remport = 443;
                   20051:     }
1.1330    raeburn  20052:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  20053:     if ($cached) {
                   20054:         unless ($nocache) {
                   20055:             if ($result) {
                   20056:                 return 1;
                   20057:             } else {
                   20058:                 return 0;
                   20059:             }
                   20060:         }
                   20061:     }
1.1328    raeburn  20062:     my $uselink;
                   20063:     my $request = new HTTP::Request('HEAD',$url);
                   20064:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   20065:     if ($response->is_success()) {
                   20066:         my $secpolicy = lc($response->header('content-security-policy'));
                   20067:         my $xframeop = lc($response->header('x-frame-options'));
                   20068:         $secpolicy =~ s/^\s+|\s+$//g;
                   20069:         $xframeop =~ s/^\s+|\s+$//g;
                   20070:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  20071:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  20072:             my ($origin,$protocol,$port);
                   20073:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   20074:                 $port = $ENV{'SERVER_PORT'};
                   20075:             } else {
                   20076:                 $port = 80;
                   20077:             }
                   20078:             if ($absolute eq '') {
                   20079:                 $protocol = 'http:';
                   20080:                 if ($port == 443) {
                   20081:                     $protocol = 'https:';
                   20082:                 }
                   20083:                 $origin = $protocol.'//'.lc($hostname);
                   20084:             } else {
                   20085:                 $origin = lc($absolute);
                   20086:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   20087:             }
                   20088:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   20089:                 my $framepolicy = $1;
                   20090:                 $framepolicy =~ s/^\s+|\s+$//g;
                   20091:                 my @policies = split(/\s+/,$framepolicy);
                   20092:                 if (@policies) {
                   20093:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   20094:                         $uselink = 1;
                   20095:                     } else {
                   20096:                         $uselink = 1;
                   20097:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   20098:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   20099:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   20100:                             undef($uselink);
                   20101:                         }
                   20102:                         if ($uselink) {
                   20103:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   20104:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   20105:                                     undef($uselink);
                   20106:                                 }
                   20107:                             }
                   20108:                         }
                   20109:                         if ($uselink) {
                   20110:                             my @possok;
                   20111:                             if ($ip ne '') {
                   20112:                                 push(@possok,$ip);
                   20113:                             }
                   20114:                             my $hoststr = '';
                   20115:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   20116:                                 if ($hoststr eq '') {
                   20117:                                     $hoststr = $part;
                   20118:                                 } else {
                   20119:                                     $hoststr = "$part.$hoststr";
                   20120:                                 }
                   20121:                                 if ($hoststr eq $hostname) {
                   20122:                                     push(@possok,$hostname);
                   20123:                                 } else {
                   20124:                                     push(@possok,"*.$hoststr");
                   20125:                                 }
                   20126:                             }
                   20127:                             if (@possok) {
                   20128:                                 foreach my $poss (@possok) {
                   20129:                                     last if (!$uselink);
                   20130:                                     foreach my $policy (@policies) {
                   20131:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   20132:                                             undef($uselink);
                   20133:                                             last;
                   20134:                                         }
                   20135:                                     }
                   20136:                                 }
                   20137:                             }
                   20138:                         }
                   20139:                     }
                   20140:                 }
                   20141:             } elsif ($xframeop ne '') {
                   20142:                 $uselink = 1;
                   20143:                 my @policies = split(/\s*,\s*/,$xframeop);
                   20144:                 if (@policies) {
                   20145:                     unless (grep(/^deny$/,@policies)) {
                   20146:                         if ($origin ne '') {
                   20147:                             if (grep(/^sameorigin$/,@policies)) {
                   20148:                                 if ($remotehost eq $origin) {
                   20149:                                     undef($uselink);
                   20150:                                 }
                   20151:                             }
                   20152:                             if ($uselink) {
                   20153:                                 foreach my $policy (@policies) {
                   20154:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   20155:                                         my $allowfrom = $1;
                   20156:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   20157:                                             undef($uselink);
                   20158:                                             last;
                   20159:                                         }
                   20160:                                     }
                   20161:                                 }
                   20162:                             }
                   20163:                         }
                   20164:                     }
                   20165:                 }
                   20166:             }
                   20167:         }
                   20168:     }
1.1329    raeburn  20169:     if ($nocache) {
                   20170:         if ($cached) {
                   20171:             my $devalidate;
                   20172:             if ($uselink && !$result) {
                   20173:                 $devalidate = 1;
                   20174:             } elsif (!$uselink && $result) {
                   20175:                 $devalidate = 1;
                   20176:             }
                   20177:             if ($devalidate) {
                   20178:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   20179:             }
                   20180:         }
                   20181:     } else {
                   20182:         if ($uselink) {
                   20183:             $result = 1;
                   20184:         } else {
                   20185:             $result = 0;
                   20186:         }
                   20187:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   20188:     }
1.1328    raeburn  20189:     return $uselink;
                   20190: }
                   20191: 
1.1359    raeburn  20192: sub page_menu {
                   20193:     my ($menucolls,$menunum) = @_;
                   20194:     my %menu;
                   20195:     foreach my $item (split(/;/,$menucolls)) {
                   20196:         my ($num,$value) = split(/\%/,$item);
                   20197:         if ($num eq $menunum) {
                   20198:             my @entries = split(/\&/,$value);
                   20199:             foreach my $entry (@entries) {
                   20200:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  20201:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  20202:                     $menu{$name} = $fields;
                   20203:                 } else {
                   20204:                     my @shown;
                   20205:                     if ($fields =~ /,/) {
                   20206:                         @shown = split(/,/,$fields);
                   20207:                     } else {
                   20208:                         @shown = ($fields);
                   20209:                     }
                   20210:                     if (@shown) {
                   20211:                         foreach my $field (@shown) {
                   20212:                             next if ($field eq '');
                   20213:                             $menu{$field} = 1;
                   20214:                         }
                   20215:                     }
                   20216:                 }
                   20217:             }
                   20218:         }
                   20219:     }
                   20220:     return %menu;
                   20221: }
                   20222: 
1.112     bowersj2 20223: 1;
                   20224: __END__;
1.41      ng       20225: 

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