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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1465  ! raeburn     4: # $Id: loncommon.pm,v 1.1464 2025/02/25 16:33:39 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;
1.1460    raeburn  5348:   $userview=~s/\Q<div class="LC_landmark" role="main"\E/<div class="LC_landmark"/; 
1.11      albertel 5349:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5350:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5351:   if (wantarray) {
                   5352:      return ($userview,$response);
                   5353:   } else {
                   5354:      return $userview;
                   5355:   }
                   5356: }
                   5357: 
                   5358: sub get_student_view_with_retries {
                   5359:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5360: 
                   5361:     my $ok = 0;                 # True if we got a good response.
                   5362:     my $content;
                   5363:     my $response;
                   5364: 
                   5365:     # Try to get the student_view done. within the retries count:
                   5366:     
                   5367:     do {
                   5368:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5369:          $ok      = $response->is_success;
                   5370:          if (!$ok) {
                   5371:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5372:          }
                   5373:          $retries--;
                   5374:     } while (!$ok && ($retries > 0));
                   5375:     
                   5376:     if (!$ok) {
                   5377:        $content = '';          # On error return an empty content.
                   5378:     }
1.651     www      5379:     if (wantarray) {
                   5380:        return ($content, $response);
                   5381:     } else {
                   5382:        return $content;
                   5383:     }
1.11      albertel 5384: }
                   5385: 
1.1349    raeburn  5386: sub css_links {
                   5387:     my ($currsymb,$level) = @_;
                   5388:     my ($links,@symbs,%cssrefs,%httpref);
                   5389:     if ($level eq 'map') {
                   5390:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5391:         if (ref($navmap)) {
                   5392:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5393:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5394:             foreach my $res (@resources) {
                   5395:                 if (ref($res) && $res->symb()) {
                   5396:                     push(@symbs,$res->symb());
                   5397:                 }
                   5398:             }
                   5399:         }
                   5400:     } else {
                   5401:         @symbs = ($currsymb);
                   5402:     }
                   5403:     foreach my $symb (@symbs) {
                   5404:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5405:         if ($css_href =~ /\S/) {
                   5406:             unless ($css_href =~ m{https?://}) {
                   5407:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5408:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5409:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5410:                 unless ($css_href =~ m{^/}) {
                   5411:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5412:                 }
                   5413:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5414:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5415:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5416:                         my $thisurl = $proburl;
                   5417:                         if ($env{'httpref.'.$proburl}) {
                   5418:                             $thisurl = $env{'httpref.'.$proburl};
                   5419:                         }
                   5420:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5421:                     }
                   5422:                 }
                   5423:             }
                   5424:             $cssrefs{$css_href} = 1;
                   5425:         }
                   5426:     }
                   5427:     if (keys(%httpref)) {
                   5428:         &Apache::lonnet::appenv(\%httpref);
                   5429:     }
                   5430:     if (keys(%cssrefs)) {
                   5431:         foreach my $css_href (keys(%cssrefs)) {
                   5432:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5433:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5434:         }
                   5435:     }
                   5436:     return $links;
                   5437: }
                   5438: 
1.112     bowersj2 5439: =pod
                   5440: 
1.648     raeburn  5441: =item * &get_student_answers() 
1.112     bowersj2 5442: 
                   5443: show a snapshot of how student was answering problem
                   5444: 
                   5445: =cut
                   5446: 
1.11      albertel 5447: sub get_student_answers {
1.100     sakharuk 5448:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5449:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5450:   my (%moreenv);
1.11      albertel 5451:   my @elements=('symb','courseid','domain','username');
                   5452:   foreach my $element (@elements) {
1.186     albertel 5453:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5454:   }
1.186     albertel 5455:   $moreenv{'grade_target'}='answer';
                   5456:   %moreenv=(%form,%moreenv);
1.497     raeburn  5457:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5458:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5459:   return $userview;
1.1       albertel 5460: }
1.116     albertel 5461: 
                   5462: =pod
                   5463: 
                   5464: =item * &submlink()
                   5465: 
1.242     albertel 5466: Inputs: $text $uname $udom $symb $target
1.116     albertel 5467: 
                   5468: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5469: 
                   5470: =cut
                   5471: 
                   5472: ###############################################
                   5473: sub submlink {
1.242     albertel 5474:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5475:     if (!($uname && $udom)) {
                   5476: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5477: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5478: 	if (!$symb) { $symb=$cursymb; }
                   5479:     }
1.254     matthew  5480:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5481:     $symb=&escape($symb);
1.960     bisitz   5482:     if ($target) { $target=" target=\"$target\""; }
                   5483:     return
                   5484:         '<a href="/adm/grades?command=submission'.
                   5485:         '&amp;symb='.$symb.
                   5486:         '&amp;student='.$uname.
                   5487:         '&amp;userdom='.$udom.'"'.
                   5488:         $target.'>'.$text.'</a>';
1.242     albertel 5489: }
                   5490: ##############################################
                   5491: 
                   5492: =pod
                   5493: 
                   5494: =item * &pgrdlink()
                   5495: 
                   5496: Inputs: $text $uname $udom $symb $target
                   5497: 
                   5498: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5499: 
                   5500: =cut
                   5501: 
                   5502: ###############################################
                   5503: sub pgrdlink {
                   5504:     my $link=&submlink(@_);
                   5505:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5506:     return $link;
                   5507: }
                   5508: ##############################################
                   5509: 
                   5510: =pod
                   5511: 
                   5512: =item * &pprmlink()
                   5513: 
                   5514: Inputs: $text $uname $udom $symb $target
                   5515: 
                   5516: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5517: student and a specific resource
1.242     albertel 5518: 
                   5519: =cut
                   5520: 
                   5521: ###############################################
                   5522: sub pprmlink {
                   5523:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5524:     if (!($uname && $udom)) {
                   5525: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5526: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5527: 	if (!$symb) { $symb=$cursymb; }
                   5528:     }
1.254     matthew  5529:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5530:     $symb=&escape($symb);
1.242     albertel 5531:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5532:     return '<a href="/adm/parmset?command=set&amp;'.
                   5533: 	'symb='.$symb.'&amp;uname='.$uname.
                   5534: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5535: }
                   5536: ##############################################
1.37      matthew  5537: 
1.112     bowersj2 5538: =pod
                   5539: 
                   5540: =back
                   5541: 
                   5542: =cut
                   5543: 
1.37      matthew  5544: ###############################################
1.51      www      5545: 
                   5546: 
                   5547: sub timehash {
1.687     raeburn  5548:     my ($thistime) = @_;
                   5549:     my $timezone = &Apache::lonlocal::gettimezone();
                   5550:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5551:                      ->set_time_zone($timezone);
                   5552:     my $wday = $dt->day_of_week();
                   5553:     if ($wday == 7) { $wday = 0; }
                   5554:     return ( 'second' => $dt->second(),
                   5555:              'minute' => $dt->minute(),
                   5556:              'hour'   => $dt->hour(),
                   5557:              'day'     => $dt->day_of_month(),
                   5558:              'month'   => $dt->month(),
                   5559:              'year'    => $dt->year(),
                   5560:              'weekday' => $wday,
                   5561:              'dayyear' => $dt->day_of_year(),
                   5562:              'dlsav'   => $dt->is_dst() );
1.51      www      5563: }
                   5564: 
1.370     www      5565: sub utc_string {
                   5566:     my ($date)=@_;
1.371     www      5567:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5568: }
                   5569: 
1.51      www      5570: sub maketime {
                   5571:     my %th=@_;
1.687     raeburn  5572:     my ($epoch_time,$timezone,$dt);
                   5573:     $timezone = &Apache::lonlocal::gettimezone();
                   5574:     eval {
                   5575:         $dt = DateTime->new( year   => $th{'year'},
                   5576:                              month  => $th{'month'},
                   5577:                              day    => $th{'day'},
                   5578:                              hour   => $th{'hour'},
                   5579:                              minute => $th{'minute'},
                   5580:                              second => $th{'second'},
                   5581:                              time_zone => $timezone,
                   5582:                          );
                   5583:     };
                   5584:     if (!$@) {
                   5585:         $epoch_time = $dt->epoch;
                   5586:         if ($epoch_time) {
                   5587:             return $epoch_time;
                   5588:         }
                   5589:     }
1.51      www      5590:     return POSIX::mktime(
                   5591:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5592:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5593: }
                   5594: 
                   5595: #########################################
1.51      www      5596: 
                   5597: sub findallcourses {
1.482     raeburn  5598:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5599:     my %roles;
                   5600:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5601:     my %courses;
1.51      www      5602:     my $now=time;
1.482     raeburn  5603:     if (!defined($uname)) {
                   5604:         $uname = $env{'user.name'};
                   5605:     }
                   5606:     if (!defined($udom)) {
                   5607:         $udom = $env{'user.domain'};
                   5608:     }
                   5609:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5610:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5611:         if (!%roles) {
                   5612:             %roles = (
                   5613:                        cc => 1,
1.907     raeburn  5614:                        co => 1,
1.482     raeburn  5615:                        in => 1,
                   5616:                        ep => 1,
                   5617:                        ta => 1,
                   5618:                        cr => 1,
                   5619:                        st => 1,
                   5620:              );
                   5621:         }
                   5622:         foreach my $entry (keys(%roleshash)) {
                   5623:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5624:             if ($trole =~ /^cr/) { 
                   5625:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5626:             } else {
                   5627:                 next if (!exists($roles{$trole}));
                   5628:             }
                   5629:             if ($tend) {
                   5630:                 next if ($tend < $now);
                   5631:             }
                   5632:             if ($tstart) {
                   5633:                 next if ($tstart > $now);
                   5634:             }
1.1058    raeburn  5635:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5636:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5637:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5638:             if ($secpart eq '') {
                   5639:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5640:                 $sec = 'none';
1.1058    raeburn  5641:                 $value .= $cnum.'/';
1.482     raeburn  5642:             } else {
                   5643:                 $cnum = $cnumpart;
                   5644:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5645:                 $value .= $cnum.'/'.$sec;
                   5646:             }
                   5647:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5648:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5649:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5650:                 }
                   5651:             } else {
                   5652:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5653:             }
1.482     raeburn  5654:         }
                   5655:     } else {
                   5656:         foreach my $key (keys(%env)) {
1.483     albertel 5657: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5658:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5659: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5660: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5661: 	        next if (%roles && !exists($roles{$role}));
                   5662: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5663:                 my $active=1;
                   5664:                 if ($starttime) {
                   5665: 		    if ($now<$starttime) { $active=0; }
                   5666:                 }
                   5667:                 if ($endtime) {
                   5668:                     if ($now>$endtime) { $active=0; }
                   5669:                 }
                   5670:                 if ($active) {
1.1058    raeburn  5671:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5672:                     if ($sec eq '') {
                   5673:                         $sec = 'none';
1.1058    raeburn  5674:                     } else {
                   5675:                         $value .= $sec;
                   5676:                     }
                   5677:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5678:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5679:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5680:                         }
                   5681:                     } else {
                   5682:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5683:                     }
1.474     raeburn  5684:                 }
                   5685:             }
1.51      www      5686:         }
                   5687:     }
1.474     raeburn  5688:     return %courses;
1.51      www      5689: }
1.37      matthew  5690: 
1.54      www      5691: ###############################################
1.474     raeburn  5692: 
                   5693: sub blockcheck {
1.1372    raeburn  5694:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5695:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5696:         my ($has_evb,$check_ipaccess);
                   5697:         my $dom = $env{'user.domain'};
                   5698:         if ($env{'request.course.id'}) {
                   5699:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5700:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5701:             my $checkrole = "cm./$cdom/$cnum";
                   5702:             my $sec = $env{'request.course.sec'};
                   5703:             if ($sec ne '') {
                   5704:                 $checkrole .= "/$sec";
                   5705:             }
                   5706:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5707:                 ($env{'request.role'} !~ /^st/)) {
                   5708:                 $has_evb = 1;
                   5709:             }
                   5710:             unless ($has_evb) {
                   5711:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
1.1444    raeburn  5712:                     ($activity eq 'index') || ($activity eq 'boards') || ($activity eq 'groups') || 
                   5713:                     ($activity eq 'chat')) {
1.1372    raeburn  5714:                     if ($udom eq $cdom) {
                   5715:                         $check_ipaccess = 1;
                   5716:                     }
                   5717:                 }
                   5718:             }
1.1375    raeburn  5719:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5720:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5721:             my $checkrole;
                   5722:             if ($env{'request.role.domain'} eq '') {
                   5723:                 $checkrole = "cm./$env{'user.domain'}/";
                   5724:             } else {
                   5725:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5726:             }
                   5727:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5728:                 $has_evb = 1;
                   5729:             }
1.1372    raeburn  5730:         }
                   5731:         unless ($has_evb || $check_ipaccess) {
                   5732:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5733:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5734:                 $dom = $udom;
                   5735:             }
                   5736:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5737:                 $check_ipaccess = 1;
                   5738:             } else {
                   5739:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5740:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5741:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5742:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5743:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5744:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5745:                         $check_ipaccess = 1;
                   5746:                     }
                   5747:                 }
                   5748:             }
                   5749:         }
                   5750:         if ($check_ipaccess) {
                   5751:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5752:             unless (defined($cached)) {
                   5753:                 my %domconfig =
                   5754:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5755:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5756:             }
                   5757:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5758:                 foreach my $id (keys(%{$ipaccessref})) {
                   5759:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5760:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5761:                         if ($range) {
                   5762:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5763:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5764:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5765:                                         return ('','','',$id,$dom);
                   5766:                                         last;
                   5767:                                     }
                   5768:                                 }
                   5769:                             }
                   5770:                         }
                   5771:                     }
                   5772:                 }
                   5773:             }
                   5774:         }
1.1373    raeburn  5775:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5776:             return ();
                   5777:         }
1.1372    raeburn  5778:     }
1.1189    raeburn  5779:     if (defined($udom) && defined($uname)) {
                   5780:         # If uname and udom are for a course, check for blocks in the course.
                   5781:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5782:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5783:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5784:             return ($startblock,$endblock,$triggerblock);
                   5785:         }
                   5786:     } else {
1.490     raeburn  5787:         $udom = $env{'user.domain'};
                   5788:         $uname = $env{'user.name'};
                   5789:     }
                   5790: 
1.502     raeburn  5791:     my $startblock = 0;
                   5792:     my $endblock = 0;
1.1062    raeburn  5793:     my $triggerblock = '';
1.1373    raeburn  5794:     my %live_courses;
                   5795:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5796:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5797:     }
1.474     raeburn  5798: 
1.490     raeburn  5799:     # If uname is for a user, and activity is course-specific, i.e.,
                   5800:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5801: 
1.490     raeburn  5802:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5803:          $activity eq 'groups' || $activity eq 'printout' ||
1.1444    raeburn  5804:          $activity eq 'search' || $activity eq 'index' ||
                   5805:          $activity eq 'reinit' || $activity eq 'alert') &&
1.1189    raeburn  5806:         ($env{'request.course.id'})) {
1.490     raeburn  5807:         foreach my $key (keys(%live_courses)) {
                   5808:             if ($key ne $env{'request.course.id'}) {
                   5809:                 delete($live_courses{$key});
                   5810:             }
                   5811:         }
                   5812:     }
                   5813: 
                   5814:     my $otheruser = 0;
                   5815:     my %own_courses;
                   5816:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5817:         # Resource belongs to user other than current user.
                   5818:         $otheruser = 1;
                   5819:         # Gather courses for current user
                   5820:         %own_courses = 
                   5821:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5822:     }
                   5823: 
                   5824:     # Gather active course roles - course coordinator, instructor, 
                   5825:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5826: 
                   5827:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5828:         my ($cdom,$cnum);
                   5829:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5830:             $cdom = $env{'course.'.$course.'.domain'};
                   5831:             $cnum = $env{'course.'.$course.'.num'};
                   5832:         } else {
1.490     raeburn  5833:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5834:         }
                   5835:         my $no_ownblock = 0;
                   5836:         my $no_userblock = 0;
1.533     raeburn  5837:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5838:             # Check if current user has 'evb' priv for this
                   5839:             if (defined($own_courses{$course})) {
                   5840:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5841:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5842:                     if ($sec ne 'none') {
                   5843:                         $checkrole .= '/'.$sec;
                   5844:                     }
                   5845:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5846:                         $no_ownblock = 1;
                   5847:                         last;
                   5848:                     }
                   5849:                 }
                   5850:             }
                   5851:             # if they have 'evb' priv and are currently not playing student
                   5852:             next if (($no_ownblock) &&
                   5853:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5854:         }
1.474     raeburn  5855:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5856:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5857:             if ($sec ne 'none') {
1.482     raeburn  5858:                 $checkrole .= '/'.$sec;
1.474     raeburn  5859:             }
1.490     raeburn  5860:             if ($otheruser) {
                   5861:                 # Resource belongs to user other than current user.
                   5862:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5863:                 my (%allroles,%userroles);
                   5864:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5865:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5866:                         my ($trole,$tdom,$tnum,$tsec);
                   5867:                         if ($entry =~ /^cr/) {
                   5868:                             ($trole,$tdom,$tnum,$tsec) = 
                   5869:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5870:                         } else {
                   5871:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5872:                         }
                   5873:                         my ($spec,$area,$trest);
                   5874:                         $area = '/'.$tdom.'/'.$tnum;
                   5875:                         $trest = $tnum;
                   5876:                         if ($tsec ne '') {
                   5877:                             $area .= '/'.$tsec;
                   5878:                             $trest .= '/'.$tsec;
                   5879:                         }
                   5880:                         $spec = $trole.'.'.$area;
                   5881:                         if ($trole =~ /^cr/) {
                   5882:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5883:                                                               $tdom,$spec,$trest,$area);
                   5884:                         } else {
                   5885:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5886:                                                                 $tdom,$spec,$trest,$area);
                   5887:                         }
                   5888:                     }
1.1276    raeburn  5889:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5890:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5891:                         if ($1) {
                   5892:                             $no_userblock = 1;
                   5893:                             last;
                   5894:                         }
1.486     raeburn  5895:                     }
                   5896:                 }
1.490     raeburn  5897:             } else {
                   5898:                 # Resource belongs to current user
                   5899:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5900:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5901:                     $no_ownblock = 1;
                   5902:                     last;
                   5903:                 }
1.474     raeburn  5904:             }
                   5905:         }
                   5906:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5907:         next if (($no_ownblock) &&
1.491     albertel 5908:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5909:         next if ($no_userblock);
1.474     raeburn  5910: 
1.1303    raeburn  5911:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5912:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5913: 
1.1062    raeburn  5914:         my ($start,$end,$trigger) = 
1.1347    raeburn  5915:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5916:         if (($start != 0) && 
                   5917:             (($startblock == 0) || ($startblock > $start))) {
                   5918:             $startblock = $start;
1.1062    raeburn  5919:             if ($trigger ne '') {
                   5920:                 $triggerblock = $trigger;
                   5921:             }
1.502     raeburn  5922:         }
                   5923:         if (($end != 0)  &&
                   5924:             (($endblock == 0) || ($endblock < $end))) {
                   5925:             $endblock = $end;
1.1062    raeburn  5926:             if ($trigger ne '') {
                   5927:                 $triggerblock = $trigger;
                   5928:             }
1.502     raeburn  5929:         }
1.490     raeburn  5930:     }
1.1062    raeburn  5931:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5932: }
                   5933: 
                   5934: sub get_blocks {
1.1347    raeburn  5935:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5936:     my $startblock = 0;
                   5937:     my $endblock = 0;
1.1062    raeburn  5938:     my $triggerblock = '';
1.490     raeburn  5939:     my $course = $cdom.'_'.$cnum;
                   5940:     $setters->{$course} = {};
                   5941:     $setters->{$course}{'staff'} = [];
                   5942:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5943:     $setters->{$course}{'triggers'} = [];
                   5944:     my (@blockers,%triggered);
                   5945:     my $now = time;
                   5946:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5947:     if ($activity eq 'docs') {
1.1348    raeburn  5948:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5949:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5950:             $blocked = 1;
                   5951:             $nosymbcache = 1;
1.1348    raeburn  5952:             $noenccheck = 1;
1.1347    raeburn  5953:         }
1.1348    raeburn  5954:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5955:         foreach my $block (@blockers) {
                   5956:             if ($block =~ /^firstaccess____(.+)$/) {
                   5957:                 my $item = $1;
                   5958:                 my $type = 'map';
                   5959:                 my $timersymb = $item;
                   5960:                 if ($item eq 'course') {
                   5961:                     $type = 'course';
                   5962:                 } elsif ($item =~ /___\d+___/) {
                   5963:                     $type = 'resource';
                   5964:                 } else {
                   5965:                     $timersymb = &Apache::lonnet::symbread($item);
                   5966:                 }
                   5967:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5968:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5969:                 $triggered{$block} = {
                   5970:                                        start => $start,
                   5971:                                        end   => $end,
                   5972:                                        type  => $type,
                   5973:                                      };
                   5974:             }
                   5975:         }
                   5976:     } else {
                   5977:         foreach my $block (keys(%commblocks)) {
                   5978:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5979:                 my ($start,$end) = ($1,$2);
                   5980:                 if ($start <= time && $end >= time) {
                   5981:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5982:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5983:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5984:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5985:                                     push(@blockers,$block);
                   5986:                                 }
                   5987:                             }
                   5988:                         }
                   5989:                     }
                   5990:                 }
                   5991:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5992:                 my $item = $1;
                   5993:                 my $timersymb = $item; 
                   5994:                 my $type = 'map';
                   5995:                 if ($item eq 'course') {
                   5996:                     $type = 'course';
                   5997:                 } elsif ($item =~ /___\d+___/) {
                   5998:                     $type = 'resource';
                   5999:                 } else {
                   6000:                     $timersymb = &Apache::lonnet::symbread($item);
                   6001:                 }
                   6002:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   6003:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   6004:                 if ($start && $end) {
                   6005:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  6006:                         if (ref($commblocks{$block}) eq 'HASH') {
                   6007:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6008:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   6009:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   6010:                                         push(@blockers,$block);
                   6011:                                         $triggered{$block} = {
                   6012:                                                                start => $start,
                   6013:                                                                end   => $end,
                   6014:                                                                type  => $type,
                   6015:                                                              };
                   6016:                                     }
                   6017:                                 }
                   6018:                             }
1.1062    raeburn  6019:                         }
                   6020:                     }
1.490     raeburn  6021:                 }
1.1062    raeburn  6022:             }
                   6023:         }
                   6024:     }
                   6025:     foreach my $blocker (@blockers) {
                   6026:         my ($staff_name,$staff_dom,$title,$blocks) =
                   6027:             &parse_block_record($commblocks{$blocker});
                   6028:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   6029:         my ($start,$end,$triggertype);
                   6030:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   6031:             ($start,$end) = ($1,$2);
                   6032:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   6033:             $start = $triggered{$blocker}{'start'};
                   6034:             $end = $triggered{$blocker}{'end'};
                   6035:             $triggertype = $triggered{$blocker}{'type'};
                   6036:         }
                   6037:         if ($start) {
                   6038:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   6039:             if ($triggertype) {
                   6040:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   6041:             } else {
                   6042:                 push(@{$$setters{$course}{'triggers'}},0);
                   6043:             }
                   6044:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   6045:                 $startblock = $start;
                   6046:                 if ($triggertype) {
                   6047:                     $triggerblock = $blocker;
1.474     raeburn  6048:                 }
                   6049:             }
1.1062    raeburn  6050:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   6051:                $endblock = $end;
                   6052:                if ($triggertype) {
                   6053:                    $triggerblock = $blocker;
                   6054:                }
                   6055:             }
1.474     raeburn  6056:         }
                   6057:     }
1.1062    raeburn  6058:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  6059: }
                   6060: 
                   6061: sub parse_block_record {
                   6062:     my ($record) = @_;
                   6063:     my ($setuname,$setudom,$title,$blocks);
                   6064:     if (ref($record) eq 'HASH') {
                   6065:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   6066:         $title = &unescape($record->{'event'});
                   6067:         $blocks = $record->{'blocks'};
                   6068:     } else {
                   6069:         my @data = split(/:/,$record,3);
                   6070:         if (scalar(@data) eq 2) {
                   6071:             $title = $data[1];
                   6072:             ($setuname,$setudom) = split(/@/,$data[0]);
                   6073:         } else {
                   6074:             ($setuname,$setudom,$title) = @data;
                   6075:         }
                   6076:         $blocks = { 'com' => 'on' };
                   6077:     }
                   6078:     return ($setuname,$setudom,$title,$blocks);
                   6079: }
                   6080: 
1.854     kalberla 6081: sub blocking_status {
1.1372    raeburn  6082:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  6083:     my %setters;
1.890     droeschl 6084: 
1.1061    raeburn  6085: # check for active blocking
1.1372    raeburn  6086:     if ($clientip eq '') {
                   6087:         $clientip = &Apache::lonnet::get_requestor_ip();
                   6088:     }
                   6089:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   6090:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  6091:     my $blocked = 0;
1.1372    raeburn  6092:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  6093:         $blocked = 1;
                   6094:     }
1.890     droeschl 6095: 
1.1061    raeburn  6096: # caller just wants to know whether a block is active
                   6097:     if (!wantarray) { return $blocked; }
                   6098: 
                   6099: # build a link to a popup window containing the details
                   6100:     my $querystring  = "?activity=$activity";
1.1351    raeburn  6101: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   6102:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  6103:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   6104:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  6105:     } elsif ($activity eq 'docs') {
1.1347    raeburn  6106:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   6107:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   6108:         if ($symb) {
                   6109:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   6110:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   6111:         }
1.1062    raeburn  6112:     }
1.1061    raeburn  6113: 
                   6114:     my $output .= <<'END_MYBLOCK';
                   6115: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   6116:     var options = "width=" + w + ",height=" + h + ",";
                   6117:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   6118:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   6119:     var newWin = window.open(url, wdwName, options);
                   6120:     newWin.focus();
                   6121: }
1.890     droeschl 6122: END_MYBLOCK
1.854     kalberla 6123: 
1.1061    raeburn  6124:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 6125:   
1.1061    raeburn  6126:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  6127:     my $text = &mt('Communication Blocked');
1.1217    raeburn  6128:     my $class = 'LC_comblock';
1.1062    raeburn  6129:     if ($activity eq 'docs') {
                   6130:         $text = &mt('Content Access Blocked');
1.1217    raeburn  6131:         $class = '';
1.1063    raeburn  6132:     } elsif ($activity eq 'printout') {
                   6133:         $text = &mt('Printing Blocked');
1.1232    raeburn  6134:     } elsif ($activity eq 'passwd') {
                   6135:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  6136:     } elsif ($activity eq 'grades') {
                   6137:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  6138:     } elsif ($activity eq 'search') {
                   6139:         $text = &mt('Search Blocked');
1.1444    raeburn  6140:     } elsif ($activity eq 'index') {
                   6141:         $text = &mt('Content Index Blocked');
1.1282    raeburn  6142:     } elsif ($activity eq 'alert') {
                   6143:         $text = &mt('Checking Critical Messages Blocked');
                   6144:     } elsif ($activity eq 'reinit') {
                   6145:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  6146:     } elsif ($activity eq 'about') {
                   6147:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  6148:     } elsif ($activity eq 'wishlist') {
                   6149:         $text = &mt('Access to Stored Links Blocked');
                   6150:     } elsif ($activity eq 'annotate') {
                   6151:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  6152:     }
1.1061    raeburn  6153:     $output .= <<"END_BLOCK";
1.1217    raeburn  6154: <div class='$class'>
1.869     kalberla 6155:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 6156:   title='$text'>
                   6157:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 6158:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 6159:   title='$text'>$text</a>
1.867     kalberla 6160: </div>
                   6161: 
                   6162: END_BLOCK
1.474     raeburn  6163: 
1.1061    raeburn  6164:     return ($blocked, $output);
1.854     kalberla 6165: }
1.490     raeburn  6166: 
1.60      matthew  6167: ###############################################
                   6168: 
1.682     raeburn  6169: sub check_ip_acc {
1.1201    raeburn  6170:     my ($acc,$clientip)=@_;
1.682     raeburn  6171:     &Apache::lonxml::debug("acc is $acc");
                   6172:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   6173:         return 1;
                   6174:     }
1.1339    raeburn  6175:     my ($ip,$allowed);
                   6176:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   6177:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   6178:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   6179:     } else {
1.1350    raeburn  6180:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   6181:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  6182:     }
1.682     raeburn  6183: 
                   6184:     my $name;
1.1219    raeburn  6185:     my %access = (
                   6186:                      allowfrom => 1,
                   6187:                      denyfrom  => 0,
                   6188:                  );
                   6189:     my @allows;
                   6190:     my @denies;
                   6191:     foreach my $item (split(',',$acc)) {
                   6192:         $item =~ s/^\s*//;
                   6193:         $item =~ s/\s*$//;
                   6194:         my $pattern;
                   6195:         if ($item =~ /^\!(.+)$/) {
                   6196:             push(@denies,$1);
                   6197:         } else {
                   6198:             push(@allows,$item);
                   6199:         }
                   6200:    }
                   6201:    my $numdenies = scalar(@denies);
                   6202:    my $numallows = scalar(@allows);
                   6203:    my $count = 0;
                   6204:    foreach my $pattern (@denies,@allows) {
                   6205:         $count ++; 
                   6206:         my $acctype = 'allowfrom';
                   6207:         if ($count <= $numdenies) {
                   6208:             $acctype = 'denyfrom';
                   6209:         }
1.682     raeburn  6210:         if ($pattern =~ /\*$/) {
                   6211:             #35.8.*
                   6212:             $pattern=~s/\*//;
1.1219    raeburn  6213:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6214:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   6215:             #35.8.3.[34-56]
                   6216:             my $low=$2;
                   6217:             my $high=$3;
                   6218:             $pattern=$1;
                   6219:             if ($ip =~ /^\Q$pattern\E/) {
                   6220:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  6221:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  6222:             }
                   6223:         } elsif ($pattern =~ /^\*/) {
                   6224:             #*.msu.edu
                   6225:             $pattern=~s/\*//;
                   6226:             if (!defined($name)) {
                   6227:                 use Socket;
                   6228:                 my $netaddr=inet_aton($ip);
                   6229:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6230:             }
1.1219    raeburn  6231:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  6232:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   6233:             #127.0.0.1
1.1219    raeburn  6234:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6235:         } else {
                   6236:             #some.name.com
                   6237:             if (!defined($name)) {
                   6238:                 use Socket;
                   6239:                 my $netaddr=inet_aton($ip);
                   6240:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6241:             }
1.1219    raeburn  6242:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   6243:         }
                   6244:         if ($allowed =~ /^(0|1)$/) { last; }
                   6245:     }
                   6246:     if ($allowed eq '') {
                   6247:         if ($numdenies && !$numallows) {
                   6248:             $allowed = 1;
                   6249:         } else {
                   6250:             $allowed = 0;
1.682     raeburn  6251:         }
                   6252:     }
                   6253:     return $allowed;
                   6254: }
                   6255: 
                   6256: ###############################################
                   6257: 
1.60      matthew  6258: =pod
                   6259: 
1.112     bowersj2 6260: =head1 Domain Template Functions
                   6261: 
                   6262: =over 4
                   6263: 
                   6264: =item * &determinedomain()
1.60      matthew  6265: 
                   6266: Inputs: $domain (usually will be undef)
                   6267: 
1.63      www      6268: Returns: Determines which domain should be used for designs
1.60      matthew  6269: 
                   6270: =cut
1.54      www      6271: 
1.60      matthew  6272: ###############################################
1.63      www      6273: sub determinedomain {
                   6274:     my $domain=shift;
1.531     albertel 6275:     if (! $domain) {
1.60      matthew  6276:         # Determine domain if we have not been given one
1.893     raeburn  6277:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 6278:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   6279:         if ($env{'request.role.domain'}) { 
                   6280:             $domain=$env{'request.role.domain'}; 
1.60      matthew  6281:         }
                   6282:     }
1.63      www      6283:     return $domain;
                   6284: }
                   6285: ###############################################
1.517     raeburn  6286: 
1.518     albertel 6287: sub devalidate_domconfig_cache {
                   6288:     my ($udom)=@_;
                   6289:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   6290: }
                   6291: 
                   6292: # ---------------------- Get domain configuration for a domain
                   6293: sub get_domainconf {
                   6294:     my ($udom) = @_;
                   6295:     my $cachetime=1800;
                   6296:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   6297:     if (defined($cached)) { return %{$result}; }
                   6298: 
                   6299:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  6300: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  6301:     my (%designhash,%legacy);
1.518     albertel 6302:     if (keys(%domconfig) > 0) {
                   6303:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  6304:             if (keys(%{$domconfig{'login'}})) {
                   6305:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  6306:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  6307:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   6308:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6309:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   6310:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   6311:                                         if ($key eq 'loginvia') {
                   6312:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   6313:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   6314:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   6315:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   6316: 
                   6317:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   6318:                                                 } else {
                   6319:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   6320:                                                 }
1.948     raeburn  6321:                                             }
1.1208    raeburn  6322:                                         } elsif ($key eq 'headtag') {
                   6323:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   6324:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  6325:                                             }
1.946     raeburn  6326:                                         }
1.1208    raeburn  6327:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   6328:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   6329:                                         }
1.946     raeburn  6330:                                     }
                   6331:                                 }
                   6332:                             }
1.1366    raeburn  6333:                         } elsif ($key eq 'saml') {
                   6334:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6335:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6336:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6337:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6338:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6339:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6340:                                         }
                   6341:                                     }
                   6342:                                 }
                   6343:                             }
1.946     raeburn  6344:                         } else {
                   6345:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6346:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6347:                                     $domconfig{'login'}{$key}{$img};
                   6348:                             }
1.699     raeburn  6349:                         }
                   6350:                     } else {
                   6351:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6352:                     }
1.632     raeburn  6353:                 }
                   6354:             } else {
                   6355:                 $legacy{'login'} = 1;
1.518     albertel 6356:             }
1.632     raeburn  6357:         } else {
                   6358:             $legacy{'login'} = 1;
1.518     albertel 6359:         }
                   6360:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6361:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6362:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6363:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6364:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6365:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6366:                         }
1.518     albertel 6367:                     }
                   6368:                 }
1.632     raeburn  6369:             } else {
                   6370:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6371:             }
1.632     raeburn  6372:         } else {
                   6373:             $legacy{'rolecolors'} = 1;
1.518     albertel 6374:         }
1.948     raeburn  6375:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6376:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6377:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6378:             }
                   6379:         }
1.632     raeburn  6380:         if (keys(%legacy) > 0) {
                   6381:             my %legacyhash = &get_legacy_domconf($udom);
                   6382:             foreach my $item (keys(%legacyhash)) {
                   6383:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6384:                     if ($legacy{'login'}) { 
                   6385:                         $designhash{$item} = $legacyhash{$item};
                   6386:                     }
                   6387:                 } else {
                   6388:                     if ($legacy{'rolecolors'}) {
                   6389:                         $designhash{$item} = $legacyhash{$item};
                   6390:                     }
1.518     albertel 6391:                 }
                   6392:             }
                   6393:         }
1.632     raeburn  6394:     } else {
                   6395:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6396:     }
                   6397:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6398: 				  $cachetime);
                   6399:     return %designhash;
                   6400: }
                   6401: 
1.632     raeburn  6402: sub get_legacy_domconf {
                   6403:     my ($udom) = @_;
                   6404:     my %legacyhash;
                   6405:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6406:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6407:     if (-e $designfile) {
1.1317    raeburn  6408:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6409:             while (my $line = <$fh>) {
                   6410:                 next if ($line =~ /^\#/);
                   6411:                 chomp($line);
                   6412:                 my ($key,$val)=(split(/\=/,$line));
                   6413:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6414:             }
                   6415:             close($fh);
                   6416:         }
                   6417:     }
1.1026    raeburn  6418:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6419:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6420:     }
                   6421:     return %legacyhash;
                   6422: }
                   6423: 
1.63      www      6424: =pod
                   6425: 
1.112     bowersj2 6426: =item * &domainlogo()
1.63      www      6427: 
                   6428: Inputs: $domain (usually will be undef)
                   6429: 
                   6430: Returns: A link to a domain logo, if the domain logo exists.
                   6431: If the domain logo does not exist, a description of the domain.
                   6432: 
                   6433: =cut
1.112     bowersj2 6434: 
1.63      www      6435: ###############################################
                   6436: sub domainlogo {
1.517     raeburn  6437:     my $domain = &determinedomain(shift);
1.518     albertel 6438:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6439:     # See if there is a logo
                   6440:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6441:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6442:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6443: 	    if ($imgsrc =~ m{^/res/}) {
                   6444: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6445: 		&Apache::lonnet::repcopy($local_name);
                   6446: 	    }
                   6447: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6448:         }
                   6449:         my $alttext = $domain;
                   6450:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6451:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6452:         }
                   6453:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6454:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6455:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6456:     } else {
1.60      matthew  6457:         return '';
1.59      www      6458:     }
                   6459: }
1.63      www      6460: ##############################################
                   6461: 
                   6462: =pod
                   6463: 
1.112     bowersj2 6464: =item * &designparm()
1.63      www      6465: 
                   6466: Inputs: $which parameter; $domain (usually will be undef)
                   6467: 
                   6468: Returns: value of designparamter $which
                   6469: 
                   6470: =cut
1.112     bowersj2 6471: 
1.397     albertel 6472: 
1.400     albertel 6473: ##############################################
1.397     albertel 6474: sub designparm {
                   6475:     my ($which,$domain)=@_;
                   6476:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6477:         return $env{'environment.color.'.$which};
1.96      www      6478:     }
1.63      www      6479:     $domain=&determinedomain($domain);
1.1016    raeburn  6480:     my %domdesign;
                   6481:     unless ($domain eq 'public') {
                   6482:         %domdesign = &get_domainconf($domain);
                   6483:     }
1.520     raeburn  6484:     my $output;
1.517     raeburn  6485:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6486:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6487:     } else {
1.520     raeburn  6488:         $output = $defaultdesign{$which};
                   6489:     }
                   6490:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6491:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6492:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6493:             if ($output =~ m{^/res/}) {
                   6494:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6495:                 &Apache::lonnet::repcopy($local_name);
                   6496:             }
1.520     raeburn  6497:             $output = &lonhttpdurl($output);
                   6498:         }
1.63      www      6499:     }
1.520     raeburn  6500:     return $output;
1.63      www      6501: }
1.59      www      6502: 
1.822     bisitz   6503: ##############################################
                   6504: =pod
                   6505: 
1.832     bisitz   6506: =item * &authorspace()
                   6507: 
1.1028    raeburn  6508: Inputs: $url (usually will be undef).
1.832     bisitz   6509: 
1.1132    raeburn  6510: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6511:          directory being viewed (or for which action is being taken). 
                   6512:          If $url is provided, and begins /priv/<domain>/<uname>
                   6513:          the path will be that portion of the $context argument.
                   6514:          Otherwise the path will be for the author space of the current
                   6515:          user when the current role is author, or for that of the 
                   6516:          co-author/assistant co-author space when the current role 
                   6517:          is co-author or assistant co-author.
1.832     bisitz   6518: 
                   6519: =cut
                   6520: 
                   6521: sub authorspace {
1.1028    raeburn  6522:     my ($url) = @_;
                   6523:     if ($url ne '') {
                   6524:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6525:            return $1;
                   6526:         }
                   6527:     }
1.832     bisitz   6528:     my $caname = '';
1.1024    www      6529:     my $cadom = '';
1.1028    raeburn  6530:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6531:         ($cadom,$caname) =
1.832     bisitz   6532:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6533:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6534:         $caname = $env{'user.name'};
1.1024    www      6535:         $cadom = $env{'user.domain'};
1.832     bisitz   6536:     }
1.1028    raeburn  6537:     if (($caname ne '') && ($cadom ne '')) {
                   6538:         return "/priv/$cadom/$caname/";
                   6539:     }
                   6540:     return;
1.832     bisitz   6541: }
                   6542: 
                   6543: ##############################################
                   6544: =pod
                   6545: 
1.822     bisitz   6546: =item * &head_subbox()
                   6547: 
                   6548: Inputs: $content (contains HTML code with page functions, etc.)
                   6549: 
                   6550: Returns: HTML div with $content
                   6551:          To be included in page header
                   6552: 
                   6553: =cut
                   6554: 
                   6555: sub head_subbox {
                   6556:     my ($content)=@_;
                   6557:     my $output =
1.993     raeburn  6558:         '<div class="LC_head_subbox">'
1.822     bisitz   6559:        .$content
                   6560:        .'</div>'
                   6561: }
                   6562: 
                   6563: ##############################################
                   6564: =pod
                   6565: 
                   6566: =item * &CSTR_pageheader()
                   6567: 
1.1026    raeburn  6568: Input: (optional) filename from which breadcrumb trail is built.
                   6569:        In most cases no input as needed, as $env{'request.filename'}
                   6570:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6571:        frameset flag
                   6572:        If page header is being requested for use in a frameset, then
                   6573:        the second (option) argument -- frameset will be true, and
                   6574:        the target attribute set for links should be target="_parent".
1.1433    raeburn  6575:        If $title is supplied as the third arg, that will be used to 
1.1407    raeburn  6576:        the left of the breadcrumbs tail for the current path.
1.822     bisitz   6577: 
                   6578: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6579:          To be included on Authoring Space pages
1.822     bisitz   6580: 
                   6581: =cut
                   6582: 
                   6583: sub CSTR_pageheader {
1.1407    raeburn  6584:     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  6585:     if ($trailfile eq '') {
                   6586:         $trailfile = $env{'request.filename'};
                   6587:     }
                   6588: 
                   6589: # this is for resources; directories have customtitle, and crumbs
                   6590: # and select recent are created in lonpubdir.pm
                   6591: 
                   6592:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6593:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6594:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6595:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6596:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6597: 
                   6598:     my $parentpath = '';
                   6599:     my $lastitem = '';
                   6600:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6601:         $parentpath = $1;
                   6602:         $lastitem = $2;
                   6603:     } else {
                   6604:         $lastitem = $thisdisfn;
                   6605:     }
1.921     bisitz   6606: 
1.1406    raeburn  6607:     my $crsauthor;
1.1246    raeburn  6608:     if (($env{'request.course.id'}) &&
                   6609:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6610:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6611:         $crsauthor = 1;
1.1406    raeburn  6612:         if ($title eq '') {
                   6613:             $title = &mt('Course Authoring Space');
                   6614:         }
                   6615:     } elsif ($title eq '') {
1.1246    raeburn  6616:         $title = &mt('Authoring Space');
                   6617:     }
                   6618: 
1.1379    raeburn  6619:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6620:     if ($frameset) {
                   6621:         $target = ' target="_parent"';
                   6622:         $crumbtarget = '_parent';
                   6623:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6624:         $target = '';
                   6625:         $crumbtarget = '';
1.1379    raeburn  6626:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6627:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6628:         $crumbtarget = $env{'request.deeplink.target'};
                   6629:     }
1.1313    raeburn  6630: 
1.921     bisitz   6631:     my $output =
1.1407    raeburn  6632:          '<div>'
1.822     bisitz   6633:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6634:         .'<b>'.$title.'</b> '
1.1314    raeburn  6635:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6636:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6637: 
                   6638:     if ($lastitem) {
                   6639:         $output .=
                   6640:              '<span class="LC_filename">'
                   6641:             .$lastitem
                   6642:             .'</span>';
                   6643:     }
1.1245    raeburn  6644: 
1.1246    raeburn  6645:     if ($crsauthor) {
1.1379    raeburn  6646:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6647:     } else {
                   6648:         $output .=
                   6649:              '<br />'
1.1314    raeburn  6650:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6651:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6652:             .'</form>'
1.1379    raeburn  6653:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6654:     }
1.1407    raeburn  6655:     $output .= '</div>';
1.921     bisitz   6656: 
                   6657:     return $output;
1.822     bisitz   6658: }
                   6659: 
1.1419    raeburn  6660: ##############################################
                   6661: =pod
                   6662: 
                   6663: =item * &nocodemirror()
                   6664: 
                   6665: Input: None
                   6666: 
                   6667: Returns: 1 if CodeMirror is deactivated based on
                   6668:          user's preference, or domain default,
                   6669:          if user indicated use of default.
                   6670: 
                   6671: =cut
                   6672: 
1.1416    raeburn  6673: sub nocodemirror {
                   6674:     my $nocodem = $env{'environment.nocodemirror'};
                   6675:     unless ($nocodem) {
                   6676:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   6677:         if ($domdefs{'nocodemirror'}) {
                   6678:             $nocodem = 'yes';
                   6679:         }
                   6680:     }
1.1417    raeburn  6681:     if ($nocodem eq 'yes') {
                   6682:         return 1;
                   6683:     }
                   6684:     return;
1.1416    raeburn  6685: }
                   6686: 
1.1419    raeburn  6687: ##############################################
                   6688: =pod
                   6689: 
                   6690: =item * &permitted_editors()
                   6691: 
1.1422    raeburn  6692: Input: $uri (optional)
1.1419    raeburn  6693: 
                   6694: Returns: %editors hash in which keys are editors
1.1429    raeburn  6695:          permitted in current Authoring Space,
                   6696:          or in current course for web pages
                   6697:          created in a course.
                   6698: 
1.1419    raeburn  6699:          Value for each key is 1. Possible keys
1.1429    raeburn  6700:          are: edit, xml, and daxe.
                   6701: 
                   6702:          For a regular Authoring Space, if no specific
1.1419    raeburn  6703:          set of editors has been set for the Author
                   6704:          who owns the Authoring Space, then the
                   6705:          domain default will be used.  If no domain
                   6706:          default has been set, then the keys will be
                   6707:          edit and xml.
                   6708: 
1.1429    raeburn  6709:          For a course author, or for web pages created
                   6710:          in a course, if no specific set of editors has
                   6711:          been set for the course, then the domain
                   6712:          course default will be used. If no domain
                   6713:          course default has been set, then the keys
                   6714:          will be edit and xml.
                   6715: 
1.1419    raeburn  6716: =cut
                   6717: 
1.1418    raeburn  6718: sub permitted_editors {
1.1422    raeburn  6719:     my ($uri) = @_;
1.1429    raeburn  6720:     my ($is_author,$is_coauthor,$is_course,$auname,$audom,%editors);
1.1418    raeburn  6721:     if ($env{'request.role'} =~ m{^au\./}) {
                   6722:         $is_author = 1;
                   6723:     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
                   6724:         ($audom,$auname) = ($1,$2);
                   6725:         if (($audom ne '') && ($auname ne '')) {
                   6726:             if (($env{'user.domain'} eq $audom) &&
                   6727:                 ($env{'user.name'} eq $auname)) {
                   6728:                 $is_author = 1;
                   6729:             } else {
                   6730:                 $is_coauthor = 1;
                   6731:             }
                   6732:         }
                   6733:     } elsif ($env{'request.course.id'}) {
1.1429    raeburn  6734:         my ($cdom,$cnum);
                   6735:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6736:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6737:         if (($env{'request.editurl'} =~ m{^/priv/\Q$cdom/$cnum\E/}) ||
1.1430    raeburn  6738:             ($env{'request.editurl'} =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}) ||
                   6739:             ($uri =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/})) {
1.1429    raeburn  6740:             $is_course = 1;
                   6741:         } elsif ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
1.1418    raeburn  6742:             ($audom,$auname) = ($1,$2);
                   6743:         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6744:             ($audom,$auname) = ($1,$2);
1.1422    raeburn  6745:         } elsif (($uri eq '/daxesave') &&
1.1429    raeburn  6746:                  (($env{'form.path'} =~ m{^/daxeopen/priv/\Q$cdom/$cnum\E/}) ||
                   6747:                   ($env{'form.path'} =~ m{^/daxeopen/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}))) {
                   6748:             $is_course = 1;
                   6749:         } elsif (($uri eq '/daxesave') &&
1.1422    raeburn  6750:                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
                   6751:             ($audom,$auname) = ($1,$2);
1.1418    raeburn  6752:         }
1.1429    raeburn  6753:         unless ($is_course) {
                   6754:             if (($audom ne '') && ($auname ne '')) {
                   6755:                 if (($env{'user.domain'} eq $audom) &&
                   6756:                     ($env{'user.name'} eq $auname)) {
                   6757:                     $is_author = 1;
                   6758:                 } else {
                   6759:                     $is_coauthor = 1;
                   6760:                 }
1.1418    raeburn  6761:             }
                   6762:         }
                   6763:     }
                   6764:     if ($is_author) {
                   6765:         if (exists($env{'environment.editors'})) {
                   6766:             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
                   6767:         } else {
                   6768:             %editors = ( edit => 1,
                   6769:                          xml => 1,
                   6770:                        );
                   6771:         }
                   6772:     } elsif ($is_coauthor) {
                   6773:         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
                   6774:             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
                   6775:         } else {
                   6776:             %editors = ( edit => 1,
                   6777:                          xml => 1,
                   6778:                        );
                   6779:         }
1.1429    raeburn  6780:     } elsif ($is_course) {
                   6781:         if (exists($env{'course.'.$env{'request.course.id'}.'.internal.crseditors'})) {
                   6782:             map { $editors{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.crseditors'});
                   6783:         } else {
                   6784:             my %domdefaults = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
                   6785:             if (exists($domdefaults{'crseditors'})) {
                   6786:                 map { $editors{$_} = 1; } split(/,/,$domdefaults{'crseditors'});
                   6787:             } else {
                   6788:                 %editors = ( edit => 1,
                   6789:                              xml => 1,
                   6790:                            );
                   6791:             }
                   6792:         }
1.1418    raeburn  6793:     } else {
                   6794:         %editors = ( edit => 1,
                   6795:                      xml => 1,
                   6796:                    );
                   6797:     }
                   6798:     return %editors;
                   6799: }
                   6800: 
1.60      matthew  6801: ###############################################
                   6802: ###############################################
                   6803: 
                   6804: =pod
                   6805: 
1.112     bowersj2 6806: =back
                   6807: 
1.549     albertel 6808: =head1 HTML Helpers
1.112     bowersj2 6809: 
                   6810: =over 4
                   6811: 
                   6812: =item * &bodytag()
1.60      matthew  6813: 
                   6814: Returns a uniform header for LON-CAPA web pages.
                   6815: 
                   6816: Inputs: 
                   6817: 
1.112     bowersj2 6818: =over 4
                   6819: 
                   6820: =item * $title, A title to be displayed on the page.
                   6821: 
                   6822: =item * $function, the current role (can be undef).
                   6823: 
                   6824: =item * $addentries, extra parameters for the <body> tag.
                   6825: 
                   6826: =item * $bodyonly, if defined, only return the <body> tag.
                   6827: 
                   6828: =item * $domain, if defined, force a given domain.
                   6829: 
                   6830: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6831:             text interface only)
1.60      matthew  6832: 
1.814     bisitz   6833: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6834:                      navigational links
1.317     albertel 6835: 
1.338     albertel 6836: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6837: 
1.460     albertel 6838: =item * $args, optional argument valid values are
                   6839:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6840:             use_absolute     -> for external resource or syllabus, this will
                   6841:                                 contain https://<hostname> if server uses
                   6842:                                 https (as per hosts.tab), but request is for http
                   6843:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6844: 
1.1096    raeburn  6845: =item * $advtoolsref, optional argument, ref to an array containing
                   6846:             inlineremote items to be added in "Functions" menu below
                   6847:             breadcrumbs.
                   6848: 
1.1316    raeburn  6849: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6850:             course, if LON-CAPA is in LTI Provider context. Value is
                   6851:             the scope of use, i.e., launch was for access to a single, a map
                   6852:             or the entire course.
                   6853: 
                   6854: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6855:             context, this will contain the URL for the landing item in
                   6856:             the course, after launch from an LTI Consumer
                   6857: 
1.1318    raeburn  6858: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6859:             context, this will contain a reference to hash of items
                   6860:             to be included in the page header and/or inline menu.
                   6861: 
1.1385    raeburn  6862: =item * $menucoll, optional argument, if specific menu collection is in
                   6863:             effect, either set as the default for the course, or set for
                   6864:             the deeplink paramater for $env{'request.deeplink.login'}
                   6865:             then $menucoll will be the number of that collection. 
                   6866: 
                   6867: =item * $menuref, optional argument, reference to a hash, containing the
                   6868:             menu options included for the menu in effect, based on the
                   6869:             configuration for the numbered menu collection in use.  
                   6870: 
                   6871: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6872:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6873:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6874:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6875:             being called a second time.
                   6876: 
1.112     bowersj2 6877: =back
                   6878: 
1.60      matthew  6879: Returns: A uniform header for LON-CAPA web pages.  
                   6880: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6881: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6882: other decorations will be returned.
                   6883: 
                   6884: =cut
                   6885: 
1.54      www      6886: sub bodytag {
1.831     bisitz   6887:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6888:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6889:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6890: 
1.954     raeburn  6891:     my $public;
                   6892:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6893:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6894:         $public = 1;
                   6895:     }
1.460     albertel 6896:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6897:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6898:     my $hostname = $args->{'hostname'};
1.339     albertel 6899: 
1.183     matthew  6900:     $function = &get_users_function() if (!$function);
1.339     albertel 6901:     my $font =   &designparm($function.'.font',$domain);
                   6902:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6903: 
1.803     bisitz   6904:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6905: 		   'bgcolor' => $pgbg,
1.339     albertel 6906: 		   'text'    => $font,
                   6907:                    'alink'   => &designparm($function.'.alink',$domain),
                   6908: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6909: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6910:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6911: 
1.63      www      6912:  # role and realm
1.1178    raeburn  6913:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6914:     if ($realm) {
                   6915:         $realm = '/'.$realm;
                   6916:     }
1.1357    raeburn  6917:     if ($role eq 'ca') {
1.479     albertel 6918:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6919:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6920:     } 
1.55      www      6921: # realm
1.1357    raeburn  6922:     my ($cid,$sec);
1.258     albertel 6923:     if ($env{'request.course.id'}) {
1.1357    raeburn  6924:         $cid = $env{'request.course.id'};
                   6925:         if ($env{'request.course.sec'}) {
                   6926:             $sec = $env{'request.course.sec'};
                   6927:         }
                   6928:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6929:         if (&Apache::lonnet::is_course($1,$2)) {
                   6930:             $cid = $1.'_'.$2;
                   6931:             $sec = $3;
                   6932:         }
                   6933:     }
                   6934:     if ($cid) {
1.378     raeburn  6935:         if ($env{'request.role'} !~ /^cr/) {
                   6936:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6937:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6938:             if ($env{'request.role.desc'}) {
                   6939:                 $role = $env{'request.role.desc'};
                   6940:             } else {
                   6941:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6942:             }
1.1257    raeburn  6943:         } else {
                   6944:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6945:         }
1.1357    raeburn  6946:         if ($sec) {
                   6947:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6948:         }   
1.1357    raeburn  6949: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6950:     } else {
                   6951:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6952:     }
1.433     albertel 6953: 
1.438     albertel 6954:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6955: 
1.101     www      6956: # construct main body tag
1.359     albertel 6957:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6958: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6959: 
1.1131    raeburn  6960:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6961: 
1.1130    raeburn  6962:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6963:         return $bodytag;
1.1130    raeburn  6964:     }
1.359     albertel 6965: 
1.954     raeburn  6966:     if ($public) {
1.433     albertel 6967: 	undef($role);
                   6968:     }
1.1318    raeburn  6969: 
1.1359    raeburn  6970:     my $showcrstitle = 1;
1.1357    raeburn  6971:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6972:         if (ref($ltimenu) eq 'HASH') {
                   6973:             unless ($ltimenu->{'role'}) {
                   6974:                 undef($role);
                   6975:             }
                   6976:             unless ($ltimenu->{'coursetitle'}) {
1.1359    raeburn  6977:                 $showcrstitle = 0;
                   6978:             }
                   6979:         }
                   6980:     } elsif (($cid) && ($menucoll)) {
                   6981:         if (ref($menuref) eq 'HASH') {
                   6982:             unless ($menuref->{'role'}) {
                   6983:                 undef($role);
                   6984:             }
                   6985:             unless ($menuref->{'crs'}) {
                   6986:                 $showcrstitle = 0;
1.1318    raeburn  6987:             }
                   6988:         }
                   6989:     }
                   6990: 
1.762     bisitz   6991:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6992:     #
                   6993:     # Extra info if you are the DC
                   6994:     my $dc_info = '';
1.1359    raeburn  6995:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6996:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6997:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6998:         $dc_info =~ s/\s+$//;
1.359     albertel 6999:     }
                   7000: 
1.1237    raeburn  7001:     my $crstype;
1.1357    raeburn  7002:     if ($cid) {
                   7003:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  7004:     } elsif ($args->{'crstype'}) {
                   7005:         $crstype = $args->{'crstype'};
                   7006:     }
                   7007:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   7008:         undef($role);
                   7009:     } else {
1.1242    raeburn  7010:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  7011:     }
1.853     droeschl 7012: 
1.903     droeschl 7013:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   7014: 
                   7015:         #    if ($env{'request.state'} eq 'construct') {
                   7016:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   7017:         #    }
                   7018: 
1.1440    raeburn  7019:         my $need_endlcint;
                   7020:         unless ($args->{'switchserver'}) {
                   7021:             $bodytag .= Apache::lonhtmlcommon::scripttag(
                   7022:                 Apache::lonmenu::utilityfunctions($httphost), 'start');
                   7023:             $need_endlcint = 1;
                   7024:         }
1.359     albertel 7025: 
1.1427    raeburn  7026:         my $collapsible;
1.1423    raeburn  7027:         if ($args->{'collapsible_header'} ne '') {
1.1427    raeburn  7028:             $collapsible = 1;
                   7029:             my ($menustate,$tiptext,$divclass);
                   7030:             if ($args->{'start_collapsed'}) {
                   7031:                 $menustate = 'collapsed';
                   7032:                 $tiptext = 'display';
                   7033:                 $divclass = 'hidden';
                   7034:             } else {
                   7035:                 $menustate = 'expanded';
                   7036:                 $tiptext = 'hide';
                   7037:                 $divclass = 'shown';
                   7038:             }
                   7039:             my $alttext = &mt('menu state: '.$menustate);
                   7040:             my $tooltip = &mt($tiptext.' standard menus');
1.1421    raeburn  7041:             $bodytag .= <<"END";
1.1461    raeburn  7042: <div id="LC_expandingContainer" style="display:inline;" role="navigation">
1.1421    raeburn  7043: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
1.1427    raeburn  7044: <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>
                   7045: <div class="LC_menus_content $divclass">
1.1421    raeburn  7046: END
                   7047:         }
1.1318    raeburn  7048:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  7049:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  7050:                                                               $args->{'links_disabled'},
1.1421    raeburn  7051:                                                               $args->{'links_target'},
1.1427    raeburn  7052:                                                               $collapsible);
1.1454    raeburn  7053:             my $labeltext = &HTML::Entities::encode(&mt('Primary links'));
1.1318    raeburn  7054:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   7055:                 if ($dc_info) {
                   7056:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   7057:                 }
1.1456    raeburn  7058:                 $bodytag .= qq|<div id="LC_nav_bar" role="navigation" aria-label="$labeltext">$left $role</div>|;
1.1454    raeburn  7059:                 unless (($realm eq '') && ($dc_info eq '')) {
                   7060:                     $bodytag .= qq|<div id="LC_realm" role="complementary"><em>$realm</em> $dc_info</div>|;
                   7061:                 }
1.1440    raeburn  7062:                 if ($need_endlcint) {
                   7063:                     $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7064:                 }
1.1318    raeburn  7065:                 return $bodytag;
                   7066:             }
1.894     droeschl 7067: 
1.1457    raeburn  7068:             $bodytag .= '<div class="LC_landmark" style="margin: 3px 0 0 0;" role="navigation" aria-label="'.$labeltext.'">';
1.1318    raeburn  7069:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   7070:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   7071:             }
1.916     droeschl 7072: 
1.1454    raeburn  7073:             $bodytag .= $right.'</div>';
1.852     droeschl 7074: 
1.1318    raeburn  7075:             if ($dc_info) {
                   7076:                 $dc_info = &dc_courseid_toggle($dc_info);
                   7077:             }
1.1454    raeburn  7078:             unless (($realm eq '') && ($dc_info eq '')) {
1.1457    raeburn  7079:                 $bodytag .= qq|<div id="LC_realm" role="complementary">$realm $dc_info</div>|;
1.1454    raeburn  7080:             }
1.1457    raeburn  7081:             $bodytag .= qq|<div style="clear: both; margin: 5px 0 0 0;"></div>|;
1.917     raeburn  7082:         }
1.916     droeschl 7083: 
1.1169    raeburn  7084:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  7085:         if ($args->{'no_secondary_menu'}) {
1.1440    raeburn  7086:             if ($need_endlcint) {
                   7087:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7088:             }
1.1168    raeburn  7089:             return $bodytag;
                   7090:         }
1.1169    raeburn  7091:         #don't show menus for public users
1.954     raeburn  7092:         if (!$public){
1.1318    raeburn  7093:             unless ($args->{'no_inline_menu'}) {
1.1459    raeburn  7094:                 $bodytag .= '<div class="LC_landmark" role="navigation" aria-label="Secondary Links">'.
                   7095:                             Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  7096:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  7097:                                                             $menucoll,$menuref,
1.1380    raeburn  7098:                                                             $args->{'links_disabled'},
1.1459    raeburn  7099:                                                             $args->{'links_target'}).
1.1460    raeburn  7100:                             '</div>';
1.1318    raeburn  7101:             }
1.903     droeschl 7102:             $bodytag .= Apache::lonmenu::serverform();
1.1440    raeburn  7103:             if ($need_endlcint) {
                   7104:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7105:             }
1.920     raeburn  7106:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 7107:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  7108:                                 $args->{'bread_crumbs'},'','',$hostname,
                   7109:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7110:             } elsif ($forcereg) {
                   7111:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  7112:                                 $args->{'group'},$args->{'hide_buttons'},
                   7113:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7114:             } else {
1.1459    raeburn  7115:                 $bodytag .=
1.1096    raeburn  7116:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   7117:                                                         $forcereg,$args->{'group'},
                   7118:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  7119:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  7120:             }
1.1440    raeburn  7121:         } else {
                   7122:             # this is to separate menu from content when there's no secondary
1.1441    raeburn  7123:             # menu. Especially needed for publicly accessible resources.
1.1459    raeburn  7124:             $bodytag .= '<hr style="clear:both" role="complementary" />';
1.1440    raeburn  7125:             if ($need_endlcint) {
                   7126:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7127:             }
1.235     raeburn  7128:         }
1.1423    raeburn  7129:         if ($args->{'collapsible_header'} ne '') {
                   7130:             $bodytag .= $args->{'collapsible_header'}.
                   7131:                         '<div id="LC_collapsible_separator"></div>'.
1.1421    raeburn  7132:                         '</div></div>';
                   7133:         }
1.235     raeburn  7134:         return $bodytag;
1.182     matthew  7135: }
                   7136: 
1.917     raeburn  7137: sub dc_courseid_toggle {
                   7138:     my ($dc_info) = @_;
1.980     raeburn  7139:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  7140:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  7141:            &mt('(More ...)').'</a></span>'.
                   7142:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   7143: }
                   7144: 
1.330     albertel 7145: sub make_attr_string {
                   7146:     my ($register,$attr_ref) = @_;
                   7147: 
                   7148:     if ($attr_ref && !ref($attr_ref)) {
                   7149: 	die("addentries Must be a hash ref ".
                   7150: 	    join(':',caller(1))." ".
                   7151: 	    join(':',caller(0))." ");
                   7152:     }
                   7153: 
                   7154:     if ($register) {
1.339     albertel 7155: 	my ($on_load,$on_unload);
                   7156: 	foreach my $key (keys(%{$attr_ref})) {
                   7157: 	    if      (lc($key) eq 'onload') {
                   7158: 		$on_load.=$attr_ref->{$key}.';';
                   7159: 		delete($attr_ref->{$key});
                   7160: 
                   7161: 	    } elsif (lc($key) eq 'onunload') {
                   7162: 		$on_unload.=$attr_ref->{$key}.';';
                   7163: 		delete($attr_ref->{$key});
                   7164: 	    }
                   7165: 	}
1.953     droeschl 7166: 	$attr_ref->{'onload'}  = $on_load;
                   7167: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 7168:     }
1.339     albertel 7169: 
1.330     albertel 7170:     my $attr_string;
1.1159    raeburn  7171:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 7172: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   7173:     }
                   7174:     return $attr_string;
                   7175: }
                   7176: 
                   7177: 
1.182     matthew  7178: ###############################################
1.251     albertel 7179: ###############################################
                   7180: 
                   7181: =pod
                   7182: 
                   7183: =item * &endbodytag()
                   7184: 
                   7185: Returns a uniform footer for LON-CAPA web pages.
                   7186: 
1.635     raeburn  7187: Inputs: 1 - optional reference to an args hash
                   7188: If in the hash, key for noredirectlink has a value which evaluates to true,
                   7189: a 'Continue' link is not displayed if the page contains an
                   7190: internal redirect in the <head></head> section,
                   7191: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 7192: 
                   7193: =cut
                   7194: 
                   7195: sub endbodytag {
1.635     raeburn  7196:     my ($args) = @_;
1.1080    raeburn  7197:     my $endbodytag;
                   7198:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   7199:         $endbodytag='</body>';
                   7200:     }
1.315     albertel 7201:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  7202:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  7203:             my ($endbodyjs,$idattr);
                   7204:             if ($env{'internal.head.to_opener'}) {
                   7205:                 my $linkid = 'LC_continue_link';
                   7206:                 $idattr = ' id="'.$linkid.'"';
                   7207:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   7208:                 $endbodyjs=<<ENDJS;
                   7209: <script type="text/javascript">
                   7210: // <![CDATA[
                   7211: function ebFunction(evt) {
                   7212:     evt.preventDefault();
                   7213:     var dest = '$redirect_for_js';
                   7214:     if (window.opener != null && !window.opener.closed) {
                   7215:         window.opener.location.href=dest;
                   7216:         window.close();
                   7217:     } else {
                   7218:         window.location.href=dest;
                   7219:     }
                   7220:     return false;
                   7221: }
                   7222: 
                   7223: \$(document).ready(function () {
                   7224:   if (document.getElementById('$linkid')) {
                   7225:     var clickelem = document.getElementById('$linkid');
                   7226:     clickelem.addEventListener('click',ebFunction,false);
                   7227:   }
                   7228: });
                   7229: // ]]>
                   7230: </script>
                   7231: ENDJS
                   7232:             }
1.635     raeburn  7233: 	    $endbodytag=
1.1386    raeburn  7234: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  7235: 	        &mt('Continue').'</a>'.
                   7236: 	        $endbodytag;
                   7237:         }
1.315     albertel 7238:     }
1.1411    raeburn  7239:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   7240:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   7241:     }
1.251     albertel 7242:     return $endbodytag;
                   7243: }
                   7244: 
1.352     albertel 7245: =pod
                   7246: 
                   7247: =item * &standard_css()
                   7248: 
                   7249: Returns a style sheet
                   7250: 
                   7251: Inputs: (all optional)
                   7252:             domain         -> force to color decorate a page for a specific
                   7253:                                domain
                   7254:             function       -> force usage of a specific rolish color scheme
                   7255:             bgcolor        -> override the default page bgcolor
                   7256: 
                   7257: =cut
                   7258: 
1.343     albertel 7259: sub standard_css {
1.345     albertel 7260:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 7261:     $function  = &get_users_function() if (!$function);
                   7262:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   7263:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 7264:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 7265: #second colour for later usage
1.345     albertel 7266:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 7267:     my $pgbg_or_bgcolor =
                   7268: 	         $bgcolor ||
1.352     albertel 7269: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 7270:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 7271:     my $alink  = &designparm($function.'.alink', $domain);
                   7272:     my $vlink  = &designparm($function.'.vlink', $domain);
                   7273:     my $link   = &designparm($function.'.link',  $domain);
                   7274: 
1.602     albertel 7275:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 7276:     my $mono                 = 'monospace';
1.850     bisitz   7277:     my $data_table_head      = $sidebg;
                   7278:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   7279:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 7280:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 7281:     my $data_table_highlight = '#FFFF00';
1.352     albertel 7282:     my $mail_new             = '#FFBB77';
                   7283:     my $mail_new_hover       = '#DD9955';
                   7284:     my $mail_read            = '#BBBB77';
                   7285:     my $mail_read_hover      = '#999944';
                   7286:     my $mail_replied         = '#AAAA88';
                   7287:     my $mail_replied_hover   = '#888855';
                   7288:     my $mail_other           = '#99BBBB';
                   7289:     my $mail_other_hover     = '#669999';
1.391     albertel 7290:     my $table_header         = '#DDDDDD';
1.489     raeburn  7291:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   7292:     my $lg_border_color      = '#C8C8C8';
1.952     onken    7293:     my $button_hover         = '#BF2317';
1.392     albertel 7294: 
1.608     albertel 7295:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   7296:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   7297:                                              : '0 3px 0 4px';
1.448     albertel 7298: 
1.523     albertel 7299: 
1.343     albertel 7300:     return <<END;
1.947     droeschl 7301: 
                   7302: /* needed for iframe to allow 100% height in FF */
                   7303: body, html { 
                   7304:     margin: 0;
                   7305:     padding: 0 0.5%;
                   7306:     height: 99%; /* to avoid scrollbars */
                   7307: }
                   7308: 
1.795     www      7309: body {
1.911     bisitz   7310:   font-family: $sans;
                   7311:   line-height:130%;
                   7312:   font-size:0.83em;
                   7313:   color:$font;
1.1436    raeburn  7314:   background-color: $pgbg_or_bgcolor;
1.795     www      7315: }
                   7316: 
1.959     onken    7317: a:focus,
                   7318: a:focus img {
1.795     www      7319:   color: red;
                   7320: }
1.698     harmsja  7321: 
1.911     bisitz   7322: form, .inline {
                   7323:   display: inline;
1.795     www      7324: }
1.721     harmsja  7325: 
1.1453    raeburn  7326: .LC_landmark {
                   7327:   margin: 0;
                   7328:   padding: 0;
                   7329:   border: none;
                   7330: }
                   7331: 
1.1443    raeburn  7332: .LC_visually_hidden:not(:focus):not(:active) {
                   7333:     clip-path: inset(50%);
                   7334:     height: 1px;
                   7335:     overflow: hidden;
                   7336:     position: absolute;
                   7337:     white-space: nowrap;
                   7338:     width: 1px;
                   7339:     display: inline;
                   7340: }
                   7341: 
1.1453    raeburn  7342: .LC_heading_2 {
                   7343:   font-size: 1.17em;
                   7344: }
                   7345: 
1.1458    raeburn  7346: .LC_heading_3 {
                   7347:   font-size: 1.0em;
                   7348: }
                   7349: 
1.1421    raeburn  7350: .LC_menus_content.shown{
1.1428    raeburn  7351:   display: block;
1.1421    raeburn  7352: }
                   7353: 
                   7354: .LC_menus_content.hidden {
                   7355:   display: none;
                   7356: }
                   7357: 
1.795     www      7358: .LC_right {
1.911     bisitz   7359:   text-align:right;
1.795     www      7360: }
                   7361: 
1.1449    raeburn  7362: .LC_center {
                   7363:   text-align:center;
                   7364: }
                   7365: 
1.795     www      7366: .LC_middle {
1.911     bisitz   7367:   vertical-align:middle;
1.795     www      7368: }
1.721     harmsja  7369: 
1.1130    raeburn  7370: .LC_floatleft {
                   7371:   float: left;
                   7372: }
                   7373: 
                   7374: .LC_floatright {
                   7375:   float: right;
                   7376: }
                   7377: 
1.911     bisitz   7378: .LC_400Box {
                   7379:   width:400px;
                   7380: }
1.721     harmsja  7381: 
1.1421    raeburn  7382: #LC_collapsible_separator {
                   7383:     border: 1px solid black;
                   7384:     width: 99.9%;
                   7385:     height: 0px;
                   7386: }
                   7387: 
1.947     droeschl 7388: .LC_iframecontainer {
                   7389:     width: 98%;
                   7390:     margin: 0;
                   7391:     position: fixed;
                   7392:     top: 8.5em;
                   7393:     bottom: 0;
                   7394: }
                   7395: 
                   7396: .LC_iframecontainer iframe{
                   7397:     border: none;
                   7398:     width: 100%;
                   7399:     height: 100%;
                   7400: }
                   7401: 
1.778     bisitz   7402: .LC_filename {
                   7403:   font-family: $mono;
                   7404:   white-space:pre;
1.921     bisitz   7405:   font-size: 120%;
1.778     bisitz   7406: }
                   7407: 
                   7408: .LC_fileicon {
                   7409:   border: none;
                   7410:   height: 1.3em;
                   7411:   vertical-align: text-bottom;
                   7412:   margin-right: 0.3em;
                   7413:   text-decoration:none;
                   7414: }
                   7415: 
1.1008    www      7416: .LC_setting {
                   7417:   text-decoration:underline;
                   7418: }
                   7419: 
1.350     albertel 7420: .LC_error {
                   7421:   color: red;
                   7422: }
1.795     www      7423: 
1.1097    bisitz   7424: .LC_warning {
                   7425:   color: darkorange;
                   7426: }
                   7427: 
1.457     albertel 7428: .LC_diff_removed {
1.733     bisitz   7429:   color: red;
1.394     albertel 7430: }
1.532     albertel 7431: 
                   7432: .LC_info,
1.457     albertel 7433: .LC_success,
                   7434: .LC_diff_added {
1.350     albertel 7435:   color: green;
                   7436: }
1.795     www      7437: 
1.802     bisitz   7438: div.LC_confirm_box {
                   7439:   background-color: #FAFAFA;
                   7440:   border: 1px solid $lg_border_color;
                   7441:   margin-right: 0;
                   7442:   padding: 5px;
                   7443: }
                   7444: 
                   7445: div.LC_confirm_box .LC_error img,
                   7446: div.LC_confirm_box .LC_success img {
                   7447:   vertical-align: middle;
                   7448: }
                   7449: 
1.1242    raeburn  7450: .LC_maxwidth {
                   7451:   max-width: 100%;
                   7452:   height: auto;
                   7453: }
                   7454: 
1.1243    raeburn  7455: .LC_textsize_mobile {
                   7456:   \@media only screen and (max-device-width: 480px) {
                   7457:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   7458:   }
                   7459: }
                   7460: 
1.440     albertel 7461: .LC_icon {
1.771     droeschl 7462:   border: none;
1.790     droeschl 7463:   vertical-align: middle;
1.771     droeschl 7464: }
                   7465: 
1.543     albertel 7466: .LC_docs_spacer {
                   7467:   width: 25px;
                   7468:   height: 1px;
1.771     droeschl 7469:   border: none;
1.543     albertel 7470: }
1.346     albertel 7471: 
1.532     albertel 7472: .LC_internal_info {
1.735     bisitz   7473:   color: #999999;
1.532     albertel 7474: }
                   7475: 
1.794     www      7476: .LC_discussion {
1.1050    www      7477:   background: $data_table_dark;
1.911     bisitz   7478:   border: 1px solid black;
                   7479:   margin: 2px;
1.794     www      7480: }
                   7481: 
                   7482: .LC_disc_action_left {
1.1050    www      7483:   background: $sidebg;
1.911     bisitz   7484:   text-align: left;
1.1050    www      7485:   padding: 4px;
                   7486:   margin: 2px;
1.794     www      7487: }
                   7488: 
                   7489: .LC_disc_action_right {
1.1050    www      7490:   background: $sidebg;
1.911     bisitz   7491:   text-align: right;
1.1050    www      7492:   padding: 4px;
                   7493:   margin: 2px;
1.794     www      7494: }
                   7495: 
                   7496: .LC_disc_new_item {
1.911     bisitz   7497:   background: white;
                   7498:   border: 2px solid red;
1.1050    www      7499:   margin: 4px;
                   7500:   padding: 4px;
1.794     www      7501: }
                   7502: 
                   7503: .LC_disc_old_item {
1.911     bisitz   7504:   background: white;
1.1050    www      7505:   margin: 4px;
                   7506:   padding: 4px;
1.794     www      7507: }
                   7508: 
1.458     albertel 7509: table.LC_pastsubmission {
                   7510:   border: 1px solid black;
                   7511:   margin: 2px;
                   7512: }
                   7513: 
1.924     bisitz   7514: table#LC_menubuttons {
1.345     albertel 7515:   width: 100%;
                   7516:   background: $pgbg;
1.392     albertel 7517:   border: 2px;
1.402     albertel 7518:   border-collapse: separate;
1.803     bisitz   7519:   padding: 0;
1.345     albertel 7520: }
1.392     albertel 7521: 
1.801     tempelho 7522: table#LC_title_bar a {
                   7523:   color: $fontmenu;
                   7524: }
1.836     bisitz   7525: 
1.807     droeschl 7526: table#LC_title_bar {
1.819     tempelho 7527:   clear: both;
1.836     bisitz   7528:   display: none;
1.807     droeschl 7529: }
                   7530: 
1.795     www      7531: table#LC_title_bar,
1.933     droeschl 7532: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 7533: table#LC_title_bar.LC_with_remote {
1.359     albertel 7534:   width: 100%;
1.392     albertel 7535:   border-color: $pgbg;
                   7536:   border-style: solid;
                   7537:   border-width: $border;
1.379     albertel 7538:   background: $pgbg;
1.801     tempelho 7539:   color: $fontmenu;
1.392     albertel 7540:   border-collapse: collapse;
1.803     bisitz   7541:   padding: 0;
1.819     tempelho 7542:   margin: 0;
1.359     albertel 7543: }
1.795     www      7544: 
1.933     droeschl 7545: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 7546:     margin: 0;
                   7547:     padding: 0;
1.933     droeschl 7548:     position: relative;
                   7549:     list-style: none;
1.913     droeschl 7550: }
1.933     droeschl 7551: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 7552:     display: inline;
                   7553: }
1.933     droeschl 7554: 
                   7555: .LC_breadcrumb_tools_navigation {
1.913     droeschl 7556:     padding: 0;
1.933     droeschl 7557:     margin: 0;
                   7558:     float: left;
1.913     droeschl 7559: }
1.933     droeschl 7560: .LC_breadcrumb_tools_tools {
                   7561:     padding: 0;
                   7562:     margin: 0;
1.913     droeschl 7563:     float: right;
                   7564: }
                   7565: 
1.1240    raeburn  7566: .LC_placement_prog {
                   7567:     padding-right: 20px;
                   7568:     font-weight: bold;
                   7569:     font-size: 90%;
                   7570: }
                   7571: 
1.359     albertel 7572: table#LC_title_bar td {
                   7573:   background: $tabbg;
                   7574: }
1.795     www      7575: 
1.911     bisitz   7576: table#LC_menubuttons img {
1.803     bisitz   7577:   border: none;
1.346     albertel 7578: }
1.795     www      7579: 
1.842     droeschl 7580: .LC_breadcrumbs_component {
1.911     bisitz   7581:   float: right;
                   7582:   margin: 0 1em;
1.357     albertel 7583: }
1.842     droeschl 7584: .LC_breadcrumbs_component img {
1.911     bisitz   7585:   vertical-align: middle;
1.777     tempelho 7586: }
1.795     www      7587: 
1.1243    raeburn  7588: .LC_breadcrumbs_hoverable {
                   7589:   background: $sidebg;
                   7590: }
                   7591: 
1.383     albertel 7592: td.LC_table_cell_checkbox {
                   7593:   text-align: center;
                   7594: }
1.795     www      7595: 
                   7596: .LC_fontsize_small {
1.911     bisitz   7597:   font-size: 70%;
1.705     tempelho 7598: }
                   7599: 
1.844     bisitz   7600: #LC_breadcrumbs {
1.911     bisitz   7601:   clear:both;
                   7602:   background: $sidebg;
                   7603:   border-bottom: 1px solid $lg_border_color;
                   7604:   line-height: 2.5em;
1.933     droeschl 7605:   overflow: hidden;
1.911     bisitz   7606:   margin: 0;
                   7607:   padding: 0;
1.995     raeburn  7608:   text-align: left;
1.819     tempelho 7609: }
1.862     bisitz   7610: 
1.1098    bisitz   7611: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7612:   clear:both;
                   7613:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7614:   border: 1px solid $sidebg;
1.1098    bisitz   7615:   margin: 0 0 10px 0;
1.966     bisitz   7616:   padding: 3px;
1.995     raeburn  7617:   text-align: left;
1.822     bisitz   7618: }
                   7619: 
1.795     www      7620: .LC_fontsize_medium {
1.911     bisitz   7621:   font-size: 85%;
1.705     tempelho 7622: }
                   7623: 
1.795     www      7624: .LC_fontsize_large {
1.911     bisitz   7625:   font-size: 120%;
1.705     tempelho 7626: }
                   7627: 
1.346     albertel 7628: .LC_menubuttons_inline_text {
                   7629:   color: $font;
1.698     harmsja  7630:   font-size: 90%;
1.701     harmsja  7631:   padding-left:3px;
1.346     albertel 7632: }
                   7633: 
1.934     droeschl 7634: .LC_menubuttons_inline_text img{
                   7635:   vertical-align: middle;
                   7636: }
                   7637: 
1.1051    www      7638: li.LC_menubuttons_inline_text img {
1.951     onken    7639:   cursor:pointer;
1.1002    droeschl 7640:   text-decoration: none;
1.951     onken    7641: }
                   7642: 
1.526     www      7643: .LC_menubuttons_link {
                   7644:   text-decoration: none;
                   7645: }
1.795     www      7646: 
1.522     albertel 7647: .LC_menubuttons_category {
1.521     www      7648:   color: $font;
1.526     www      7649:   background: $pgbg;
1.521     www      7650:   font-size: larger;
                   7651:   font-weight: bold;
                   7652: }
                   7653: 
1.346     albertel 7654: td.LC_menubuttons_text {
1.911     bisitz   7655:   color: $font;
1.346     albertel 7656: }
1.706     harmsja  7657: 
1.346     albertel 7658: .LC_current_location {
                   7659:   background: $tabbg;
                   7660: }
1.795     www      7661: 
1.1286    raeburn  7662: td.LC_zero_height {
                   7663:   line-height: 0; 
                   7664:   cellpadding: 0;
                   7665: }
                   7666: 
1.938     bisitz   7667: table.LC_data_table {
1.347     albertel 7668:   border: 1px solid #000000;
1.402     albertel 7669:   border-collapse: separate;
1.426     albertel 7670:   border-spacing: 1px;
1.610     albertel 7671:   background: $pgbg;
1.347     albertel 7672: }
1.795     www      7673: 
1.422     albertel 7674: .LC_data_table_dense {
                   7675:   font-size: small;
                   7676: }
1.795     www      7677: 
1.507     raeburn  7678: table.LC_nested_outer {
                   7679:   border: 1px solid #000000;
1.589     raeburn  7680:   border-collapse: collapse;
1.803     bisitz   7681:   border-spacing: 0;
1.507     raeburn  7682:   width: 100%;
                   7683: }
1.795     www      7684: 
1.879     raeburn  7685: table.LC_innerpickbox,
1.507     raeburn  7686: table.LC_nested {
1.803     bisitz   7687:   border: none;
1.589     raeburn  7688:   border-collapse: collapse;
1.803     bisitz   7689:   border-spacing: 0;
1.507     raeburn  7690:   width: 100%;
                   7691: }
1.795     www      7692: 
1.911     bisitz   7693: table.LC_data_table tr th,
                   7694: table.LC_calendar tr th,
1.879     raeburn  7695: table.LC_prior_tries tr th,
                   7696: table.LC_innerpickbox tr th {
1.349     albertel 7697:   font-weight: bold;
                   7698:   background-color: $data_table_head;
1.801     tempelho 7699:   color:$fontmenu;
1.701     harmsja  7700:   font-size:90%;
1.347     albertel 7701: }
1.795     www      7702: 
1.879     raeburn  7703: table.LC_innerpickbox tr th,
                   7704: table.LC_innerpickbox tr td {
                   7705:   vertical-align: top;
                   7706: }
                   7707: 
1.711     raeburn  7708: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7709:   background-color: #CCCCCC;
1.711     raeburn  7710:   font-weight: bold;
                   7711:   text-align: left;
                   7712: }
1.795     www      7713: 
1.912     bisitz   7714: table.LC_data_table tr.LC_odd_row > td {
                   7715:   background-color: $data_table_light;
                   7716:   padding: 2px;
                   7717:   vertical-align: top;
                   7718: }
                   7719: 
1.809     bisitz   7720: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7721:   background-color: $data_table_light;
1.912     bisitz   7722:   vertical-align: top;
                   7723: }
                   7724: 
                   7725: table.LC_data_table tr.LC_even_row > td {
                   7726:   background-color: $data_table_dark;
1.425     albertel 7727:   padding: 2px;
1.900     bisitz   7728:   vertical-align: top;
1.347     albertel 7729: }
1.795     www      7730: 
1.809     bisitz   7731: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7732:   background-color: $data_table_dark;
1.900     bisitz   7733:   vertical-align: top;
1.347     albertel 7734: }
1.795     www      7735: 
1.425     albertel 7736: table.LC_data_table tr.LC_data_table_highlight td {
                   7737:   background-color: $data_table_darker;
                   7738: }
1.795     www      7739: 
1.639     raeburn  7740: table.LC_data_table tr td.LC_leftcol_header {
                   7741:   background-color: $data_table_head;
                   7742:   font-weight: bold;
                   7743: }
1.795     www      7744: 
1.451     albertel 7745: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7746: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7747:   font-weight: bold;
                   7748:   font-style: italic;
                   7749:   text-align: center;
                   7750:   padding: 8px;
1.347     albertel 7751: }
1.795     www      7752: 
1.1114    raeburn  7753: table.LC_data_table tr.LC_empty_row td,
                   7754: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7755:   background-color: $sidebg;
                   7756: }
                   7757: 
                   7758: table.LC_nested tr.LC_empty_row td {
                   7759:   background-color: #FFFFFF;
                   7760: }
                   7761: 
1.890     droeschl 7762: table.LC_caption {
                   7763: }
                   7764: 
1.507     raeburn  7765: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7766:   padding: 4ex
                   7767: }
1.795     www      7768: 
1.507     raeburn  7769: table.LC_nested_outer tr th {
                   7770:   font-weight: bold;
1.801     tempelho 7771:   color:$fontmenu;
1.507     raeburn  7772:   background-color: $data_table_head;
1.701     harmsja  7773:   font-size: small;
1.507     raeburn  7774:   border-bottom: 1px solid #000000;
                   7775: }
1.795     www      7776: 
1.507     raeburn  7777: table.LC_nested_outer tr td.LC_subheader {
                   7778:   background-color: $data_table_head;
                   7779:   font-weight: bold;
                   7780:   font-size: small;
                   7781:   border-bottom: 1px solid #000000;
                   7782:   text-align: right;
1.451     albertel 7783: }
1.795     www      7784: 
1.507     raeburn  7785: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7786:   background-color: #CCCCCC;
1.451     albertel 7787:   font-weight: bold;
                   7788:   font-size: small;
1.507     raeburn  7789:   text-align: center;
                   7790: }
1.795     www      7791: 
1.589     raeburn  7792: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7793: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7794:   text-align: left;
1.451     albertel 7795: }
1.795     www      7796: 
1.507     raeburn  7797: table.LC_nested td {
1.735     bisitz   7798:   background-color: #FFFFFF;
1.451     albertel 7799:   font-size: small;
1.507     raeburn  7800: }
1.795     www      7801: 
1.507     raeburn  7802: table.LC_nested_outer tr th.LC_right_item,
                   7803: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7804: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7805: table.LC_nested tr td.LC_right_item {
1.451     albertel 7806:   text-align: right;
                   7807: }
                   7808: 
1.507     raeburn  7809: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7810:   background-color: #EEEEEE;
1.451     albertel 7811: }
                   7812: 
1.473     raeburn  7813: table.LC_createuser {
                   7814: }
                   7815: 
                   7816: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7817:   font-size: small;
1.473     raeburn  7818: }
                   7819: 
                   7820: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7821:   background-color: #CCCCCC;
1.473     raeburn  7822:   font-weight: bold;
                   7823:   text-align: center;
                   7824: }
                   7825: 
1.349     albertel 7826: table.LC_calendar {
                   7827:   border: 1px solid #000000;
                   7828:   border-collapse: collapse;
1.917     raeburn  7829:   width: 98%;
1.349     albertel 7830: }
1.795     www      7831: 
1.349     albertel 7832: table.LC_calendar_pickdate {
                   7833:   font-size: xx-small;
                   7834: }
1.795     www      7835: 
1.349     albertel 7836: table.LC_calendar tr td {
                   7837:   border: 1px solid #000000;
                   7838:   vertical-align: top;
1.917     raeburn  7839:   width: 14%;
1.349     albertel 7840: }
1.795     www      7841: 
1.349     albertel 7842: table.LC_calendar tr td.LC_calendar_day_empty {
                   7843:   background-color: $data_table_dark;
                   7844: }
1.795     www      7845: 
1.779     bisitz   7846: table.LC_calendar tr td.LC_calendar_day_current {
                   7847:   background-color: $data_table_highlight;
1.777     tempelho 7848: }
1.795     www      7849: 
1.938     bisitz   7850: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7851:   background-color: $mail_new;
                   7852: }
1.795     www      7853: 
1.938     bisitz   7854: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7855:   background-color: $mail_new_hover;
                   7856: }
1.795     www      7857: 
1.938     bisitz   7858: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7859:   background-color: $mail_read;
                   7860: }
1.795     www      7861: 
1.938     bisitz   7862: /*
                   7863: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7864:   background-color: $mail_read_hover;
                   7865: }
1.938     bisitz   7866: */
1.795     www      7867: 
1.938     bisitz   7868: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7869:   background-color: $mail_replied;
                   7870: }
1.795     www      7871: 
1.938     bisitz   7872: /*
                   7873: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7874:   background-color: $mail_replied_hover;
                   7875: }
1.938     bisitz   7876: */
1.795     www      7877: 
1.938     bisitz   7878: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7879:   background-color: $mail_other;
                   7880: }
1.795     www      7881: 
1.938     bisitz   7882: /*
                   7883: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7884:   background-color: $mail_other_hover;
                   7885: }
1.938     bisitz   7886: */
1.494     raeburn  7887: 
1.777     tempelho 7888: table.LC_data_table tr > td.LC_browser_file,
                   7889: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7890:   background: #AAEE77;
1.389     albertel 7891: }
1.795     www      7892: 
1.777     tempelho 7893: table.LC_data_table tr > td.LC_browser_file_locked,
                   7894: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7895:   background: #FFAA99;
1.387     albertel 7896: }
1.795     www      7897: 
1.777     tempelho 7898: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7899:   background: #888888;
1.779     bisitz   7900: }
1.795     www      7901: 
1.777     tempelho 7902: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7903: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7904:   background: #F8F866;
1.777     tempelho 7905: }
1.795     www      7906: 
1.696     bisitz   7907: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7908:   background: #E0E8FF;
1.387     albertel 7909: }
1.696     bisitz   7910: 
1.707     bisitz   7911: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7912:   /* background: #77FF77; */
1.707     bisitz   7913: }
1.795     www      7914: 
1.707     bisitz   7915: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7916:   border-right: 8px solid #FFFF77;
1.707     bisitz   7917: }
1.795     www      7918: 
1.707     bisitz   7919: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7920:   border-right: 8px solid #FFAA77;
1.707     bisitz   7921: }
1.795     www      7922: 
1.707     bisitz   7923: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7924:   border-right: 8px solid #FF7777;
1.707     bisitz   7925: }
1.795     www      7926: 
1.707     bisitz   7927: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7928:   border-right: 8px solid #AAFF77;
1.707     bisitz   7929: }
1.795     www      7930: 
1.707     bisitz   7931: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7932:   border-right: 8px solid #11CC55;
1.707     bisitz   7933: }
                   7934: 
1.388     albertel 7935: span.LC_current_location {
1.701     harmsja  7936:   font-size:larger;
1.388     albertel 7937:   background: $pgbg;
                   7938: }
1.387     albertel 7939: 
1.1029    www      7940: span.LC_current_nav_location {
                   7941:   font-weight:bold;
                   7942:   background: $sidebg;
                   7943: }
                   7944: 
1.395     albertel 7945: span.LC_parm_menu_item {
                   7946:   font-size: larger;
                   7947: }
1.795     www      7948: 
1.395     albertel 7949: span.LC_parm_scope_all {
                   7950:   color: red;
                   7951: }
1.795     www      7952: 
1.395     albertel 7953: span.LC_parm_scope_folder {
                   7954:   color: green;
                   7955: }
1.795     www      7956: 
1.395     albertel 7957: span.LC_parm_scope_resource {
                   7958:   color: orange;
                   7959: }
1.795     www      7960: 
1.395     albertel 7961: span.LC_parm_part {
                   7962:   color: blue;
                   7963: }
1.795     www      7964: 
1.911     bisitz   7965: span.LC_parm_folder,
                   7966: span.LC_parm_symb {
1.395     albertel 7967:   font-size: x-small;
                   7968:   font-family: $mono;
                   7969:   color: #AAAAAA;
                   7970: }
                   7971: 
1.977     bisitz   7972: ul.LC_parm_parmlist li {
                   7973:   display: inline-block;
                   7974:   padding: 0.3em 0.8em;
                   7975:   vertical-align: top;
                   7976:   width: 150px;
                   7977:   border-top:1px solid $lg_border_color;
                   7978: }
                   7979: 
1.795     www      7980: td.LC_parm_overview_level_menu,
                   7981: td.LC_parm_overview_map_menu,
                   7982: td.LC_parm_overview_parm_selectors,
                   7983: td.LC_parm_overview_restrictions  {
1.396     albertel 7984:   border: 1px solid black;
                   7985:   border-collapse: collapse;
                   7986: }
1.795     www      7987: 
1.1285    raeburn  7988: span.LC_parm_recursive,
                   7989: td.LC_parm_recursive {
                   7990:   font-weight: bold;
                   7991:   font-size: smaller;
                   7992: }
                   7993: 
1.396     albertel 7994: table.LC_parm_overview_restrictions td {
                   7995:   border-width: 1px 4px 1px 4px;
                   7996:   border-style: solid;
                   7997:   border-color: $pgbg;
                   7998:   text-align: center;
                   7999: }
1.795     www      8000: 
1.396     albertel 8001: table.LC_parm_overview_restrictions th {
                   8002:   background: $tabbg;
                   8003:   border-width: 1px 4px 1px 4px;
                   8004:   border-style: solid;
                   8005:   border-color: $pgbg;
                   8006: }
1.795     www      8007: 
1.1459    raeburn  8008: h1.LC_helpmenu {
                   8009:   display: inline;
                   8010:   font-size: 100%;
                   8011:   font-weight: normal;
                   8012:   line-height: 1em;
                   8013:   margin: 0;
                   8014:   padding: 0;
                   8015:   border: 0;
1.398     albertel 8016: }
1.795     www      8017: 
1.1456    raeburn  8018: .LC_helpdesk_headbox {
                   8019:   border: 2px groove threedface;
                   8020:   padding: 1em;
                   8021: }
                   8022: 
                   8023: h1.LC_helpdesk_legend {
                   8024:   float: left;
                   8025:   margin: -1.7em 0 0;
                   8026:   padding: 0 .5em;
1.397     albertel 8027:   background: $pgbg;
1.1456    raeburn  8028:   font-size: 1em;
                   8029:   font-weight: bold;
                   8030: }
                   8031: 
                   8032: h1.LC_helpdesk_title {
                   8033:   display: inline;
                   8034:   font-size: 1em;
                   8035:   line-height: 2.5em;
                   8036:   margin: 0;
1.803     bisitz   8037:   padding: 0;
1.1456    raeburn  8038:   vertical-align: bottom;
1.397     albertel 8039: }
1.795     www      8040: 
1.1456    raeburn  8041: .LC_helpdesk_links {
                   8042:   border: 1px solid black;
                   8043:   padding: 3px;
1.397     albertel 8044:   background: $tabbg;
1.399     albertel 8045:   text-align: center;
                   8046:   font-weight: bold;
1.1456    raeburn  8047:   display: inline;
                   8048:   margin-right: -6px;
                   8049: }
                   8050: 
                   8051: .LC_helpdesk_img,
                   8052: .LC_helpdesk_text {
                   8053:   padding: 0;
                   8054:   margin: 0;
                   8055:   border: 0;
                   8056:   display: inline;
1.397     albertel 8057: }
1.396     albertel 8058: 
1.1456    raeburn  8059: .LC_helpdesk_img a:link,
                   8060: .LC_helpdesk_img a:visited,
                   8061: .LC_helpdesk_img a:active,
                   8062: .LC_helpdesk_text a:link,
                   8063: .LC_helpdesk_text a:visited,
                   8064: .LC_helpdesk_text a:active {
1.397     albertel 8065:   text-decoration: none;
                   8066:   color: $font;
                   8067: }
1.795     www      8068: 
1.1456    raeburn  8069: div.LC_helpdesk_text a:hover {
1.397     albertel 8070:   text-decoration: underline;
                   8071:   color: $vlink;
                   8072: }
1.396     albertel 8073: 
1.417     albertel 8074: .LC_chrt_popup_exists {
                   8075:   border: 1px solid #339933;
                   8076:   margin: -1px;
                   8077: }
1.795     www      8078: 
1.417     albertel 8079: .LC_chrt_popup_up {
                   8080:   border: 1px solid yellow;
                   8081:   margin: -1px;
                   8082: }
1.795     www      8083: 
1.417     albertel 8084: .LC_chrt_popup {
                   8085:   border: 1px solid #8888FF;
                   8086:   background: #CCCCFF;
                   8087: }
1.795     www      8088: 
1.421     albertel 8089: table.LC_pick_box {
                   8090:   border-collapse: separate;
                   8091:   background: white;
                   8092:   border: 1px solid black;
                   8093:   border-spacing: 1px;
                   8094: }
1.795     www      8095: 
1.1454    raeburn  8096: table.LC_pick_box th.LC_pick_box_title {
1.850     bisitz   8097:   background: $sidebg;
1.421     albertel 8098:   font-weight: bold;
1.900     bisitz   8099:   text-align: left;
1.740     bisitz   8100:   vertical-align: top;
1.421     albertel 8101:   width: 184px;
                   8102:   padding: 8px;
                   8103: }
1.795     www      8104: 
1.579     raeburn  8105: table.LC_pick_box td.LC_pick_box_value {
                   8106:   text-align: left;
                   8107:   padding: 8px;
                   8108: }
1.795     www      8109: 
1.579     raeburn  8110: table.LC_pick_box td.LC_pick_box_select {
                   8111:   text-align: left;
                   8112:   padding: 8px;
                   8113: }
1.795     www      8114: 
1.424     albertel 8115: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   8116:   padding: 0;
1.421     albertel 8117:   height: 1px;
                   8118:   background: black;
                   8119: }
1.795     www      8120: 
1.421     albertel 8121: table.LC_pick_box td.LC_pick_box_submit {
                   8122:   text-align: right;
                   8123: }
1.795     www      8124: 
1.579     raeburn  8125: table.LC_pick_box td.LC_evenrow_value {
                   8126:   text-align: left;
                   8127:   padding: 8px;
                   8128:   background-color: $data_table_light;
                   8129: }
1.795     www      8130: 
1.579     raeburn  8131: table.LC_pick_box td.LC_oddrow_value {
                   8132:   text-align: left;
                   8133:   padding: 8px;
                   8134:   background-color: $data_table_light;
                   8135: }
1.795     www      8136: 
1.579     raeburn  8137: span.LC_helpform_receipt_cat {
                   8138:   font-weight: bold;
                   8139: }
1.795     www      8140: 
1.424     albertel 8141: table.LC_group_priv_box {
                   8142:   background: white;
                   8143:   border: 1px solid black;
                   8144:   border-spacing: 1px;
                   8145: }
1.795     www      8146: 
1.424     albertel 8147: table.LC_group_priv_box td.LC_pick_box_title {
                   8148:   background: $tabbg;
                   8149:   font-weight: bold;
                   8150:   text-align: right;
                   8151:   width: 184px;
                   8152: }
1.795     www      8153: 
1.424     albertel 8154: table.LC_group_priv_box td.LC_groups_fixed {
                   8155:   background: $data_table_light;
                   8156:   text-align: center;
                   8157: }
1.795     www      8158: 
1.424     albertel 8159: table.LC_group_priv_box td.LC_groups_optional {
                   8160:   background: $data_table_dark;
                   8161:   text-align: center;
                   8162: }
1.795     www      8163: 
1.424     albertel 8164: table.LC_group_priv_box td.LC_groups_functionality {
                   8165:   background: $data_table_darker;
                   8166:   text-align: center;
                   8167:   font-weight: bold;
                   8168: }
1.795     www      8169: 
1.424     albertel 8170: table.LC_group_priv td {
                   8171:   text-align: left;
1.803     bisitz   8172:   padding: 0;
1.424     albertel 8173: }
                   8174: 
                   8175: .LC_navbuttons {
                   8176:   margin: 2ex 0ex 2ex 0ex;
                   8177: }
1.795     www      8178: 
1.423     albertel 8179: .LC_topic_bar {
                   8180:   font-weight: bold;
                   8181:   background: $tabbg;
1.918     wenzelju 8182:   margin: 1em 0em 1em 2em;
1.805     bisitz   8183:   padding: 3px;
1.918     wenzelju 8184:   font-size: 1.2em;
1.423     albertel 8185: }
1.795     www      8186: 
1.423     albertel 8187: .LC_topic_bar span {
1.918     wenzelju 8188:   left: 0.5em;
                   8189:   position: absolute;
1.423     albertel 8190:   vertical-align: middle;
1.918     wenzelju 8191:   font-size: 1.2em;
1.423     albertel 8192: }
1.795     www      8193: 
1.423     albertel 8194: table.LC_course_group_status {
                   8195:   margin: 20px;
                   8196: }
1.795     www      8197: 
1.423     albertel 8198: table.LC_status_selector td {
                   8199:   vertical-align: top;
                   8200:   text-align: center;
1.424     albertel 8201:   padding: 4px;
                   8202: }
1.795     www      8203: 
1.599     albertel 8204: div.LC_feedback_link {
1.616     albertel 8205:   clear: both;
1.829     kalberla 8206:   background: $sidebg;
1.779     bisitz   8207:   width: 100%;
1.829     kalberla 8208:   padding-bottom: 10px;
                   8209:   border: 1px $tabbg solid;
1.833     kalberla 8210:   height: 22px;
                   8211:   line-height: 22px;
                   8212:   padding-top: 5px;
                   8213: }
                   8214: 
                   8215: div.LC_feedback_link img {
                   8216:   height: 22px;
1.867     kalberla 8217:   vertical-align:middle;
1.829     kalberla 8218: }
                   8219: 
1.911     bisitz   8220: div.LC_feedback_link a {
1.829     kalberla 8221:   text-decoration: none;
1.489     raeburn  8222: }
1.795     www      8223: 
1.867     kalberla 8224: div.LC_comblock {
1.911     bisitz   8225:   display:inline;
1.867     kalberla 8226:   color:$font;
                   8227:   font-size:90%;
                   8228: }
                   8229: 
                   8230: div.LC_feedback_link div.LC_comblock {
                   8231:   padding-left:5px;
                   8232: }
                   8233: 
                   8234: div.LC_feedback_link div.LC_comblock a {
                   8235:   color:$font;
                   8236: }
                   8237: 
1.489     raeburn  8238: span.LC_feedback_link {
1.858     bisitz   8239:   /* background: $feedback_link_bg; */
1.599     albertel 8240:   font-size: larger;
                   8241: }
1.795     www      8242: 
1.599     albertel 8243: span.LC_message_link {
1.858     bisitz   8244:   /* background: $feedback_link_bg; */
1.599     albertel 8245:   font-size: larger;
                   8246:   position: absolute;
                   8247:   right: 1em;
1.489     raeburn  8248: }
1.421     albertel 8249: 
1.515     albertel 8250: table.LC_prior_tries {
1.524     albertel 8251:   border: 1px solid #000000;
                   8252:   border-collapse: separate;
                   8253:   border-spacing: 1px;
1.515     albertel 8254: }
1.523     albertel 8255: 
1.515     albertel 8256: table.LC_prior_tries td {
1.524     albertel 8257:   padding: 2px;
1.515     albertel 8258: }
1.523     albertel 8259: 
                   8260: .LC_answer_correct {
1.795     www      8261:   background: lightgreen;
                   8262:   color: darkgreen;
                   8263:   padding: 6px;
1.523     albertel 8264: }
1.795     www      8265: 
1.523     albertel 8266: .LC_answer_charged_try {
1.797     www      8267:   background: #FFAAAA;
1.795     www      8268:   color: darkred;
                   8269:   padding: 6px;
1.523     albertel 8270: }
1.795     www      8271: 
1.779     bisitz   8272: .LC_answer_not_charged_try,
1.523     albertel 8273: .LC_answer_no_grade,
                   8274: .LC_answer_late {
1.795     www      8275:   background: lightyellow;
1.523     albertel 8276:   color: black;
1.795     www      8277:   padding: 6px;
1.523     albertel 8278: }
1.795     www      8279: 
1.523     albertel 8280: .LC_answer_previous {
1.795     www      8281:   background: lightblue;
                   8282:   color: darkblue;
                   8283:   padding: 6px;
1.523     albertel 8284: }
1.795     www      8285: 
1.779     bisitz   8286: .LC_answer_no_message {
1.777     tempelho 8287:   background: #FFFFFF;
                   8288:   color: black;
1.795     www      8289:   padding: 6px;
1.779     bisitz   8290: }
1.795     www      8291: 
1.1334    raeburn  8292: .LC_answer_unknown,
                   8293: .LC_answer_warning {
1.779     bisitz   8294:   background: orange;
                   8295:   color: black;
1.795     www      8296:   padding: 6px;
1.777     tempelho 8297: }
1.795     www      8298: 
1.1446    raeburn  8299: .LC_prob_status {
1.1447    raeburn  8300:   margin-top: 5px;
1.1446    raeburn  8301:   padding-top: 0;
                   8302:   padding-left: 0;
                   8303:   padding-bottom: 0;
                   8304:   padding-right: 5px;
                   8305: }
                   8306: 
1.1448    raeburn  8307: .LC_mail_actions {
                   8308:   float: left;
                   8309:   padding: 0;
                   8310:   margin: 6px;
                   8311: }
                   8312: 
                   8313: .LC_vertical_line {
                   8314:   width: 1px;
                   8315:   background-color: black;
                   8316:   height: 4em;
                   8317:   float: left;
                   8318:   margin: 0;
                   8319:   padding: 0;
                   8320: }
                   8321: 
1.529     albertel 8322: span.LC_prior_numerical,
                   8323: span.LC_prior_string,
                   8324: span.LC_prior_custom,
                   8325: span.LC_prior_reaction,
                   8326: span.LC_prior_math {
1.925     bisitz   8327:   font-family: $mono;
1.523     albertel 8328:   white-space: pre;
                   8329: }
                   8330: 
1.525     albertel 8331: span.LC_prior_string {
1.925     bisitz   8332:   font-family: $mono;
1.525     albertel 8333:   white-space: pre;
                   8334: }
                   8335: 
1.523     albertel 8336: table.LC_prior_option {
                   8337:   width: 100%;
                   8338:   border-collapse: collapse;
                   8339: }
1.795     www      8340: 
1.911     bisitz   8341: table.LC_prior_rank,
1.795     www      8342: table.LC_prior_match {
1.528     albertel 8343:   border-collapse: collapse;
                   8344: }
1.795     www      8345: 
1.528     albertel 8346: table.LC_prior_option tr td,
                   8347: table.LC_prior_rank tr td,
                   8348: table.LC_prior_match tr td {
1.524     albertel 8349:   border: 1px solid #000000;
1.515     albertel 8350: }
                   8351: 
1.855     bisitz   8352: .LC_nobreak {
1.544     albertel 8353:   white-space: nowrap;
1.519     raeburn  8354: }
                   8355: 
1.576     raeburn  8356: span.LC_cusr_emph {
                   8357:   font-style: italic;
                   8358: }
                   8359: 
1.633     raeburn  8360: span.LC_cusr_subheading {
                   8361:   font-weight: normal;
                   8362:   font-size: 85%;
                   8363: }
                   8364: 
1.861     bisitz   8365: div.LC_docs_entry_move {
1.859     bisitz   8366:   border: 1px solid #BBBBBB;
1.545     albertel 8367:   background: #DDDDDD;
1.861     bisitz   8368:   width: 22px;
1.859     bisitz   8369:   padding: 1px;
                   8370:   margin: 0;
1.545     albertel 8371: }
                   8372: 
1.861     bisitz   8373: table.LC_data_table tr > td.LC_docs_entry_commands,
                   8374: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 8375:   font-size: x-small;
                   8376: }
1.795     www      8377: 
1.861     bisitz   8378: .LC_docs_entry_parameter {
                   8379:   white-space: nowrap;
                   8380: }
                   8381: 
1.544     albertel 8382: .LC_docs_copy {
1.545     albertel 8383:   color: #000099;
1.544     albertel 8384: }
1.795     www      8385: 
1.544     albertel 8386: .LC_docs_cut {
1.545     albertel 8387:   color: #550044;
1.544     albertel 8388: }
1.795     www      8389: 
1.544     albertel 8390: .LC_docs_rename {
1.545     albertel 8391:   color: #009900;
1.544     albertel 8392: }
1.795     www      8393: 
1.544     albertel 8394: .LC_docs_remove {
1.545     albertel 8395:   color: #990000;
                   8396: }
                   8397: 
1.1284    raeburn  8398: .LC_docs_alias {
                   8399:   color: #440055;  
                   8400: }
                   8401: 
1.1286    raeburn  8402: .LC_domprefs_email,
1.1284    raeburn  8403: .LC_docs_alias_name,
1.547     albertel 8404: .LC_docs_reinit_warn,
                   8405: .LC_docs_ext_edit {
                   8406:   font-size: x-small;
                   8407: }
                   8408: 
1.545     albertel 8409: table.LC_docs_adddocs td,
                   8410: table.LC_docs_adddocs th {
                   8411:   border: 1px solid #BBBBBB;
                   8412:   padding: 4px;
                   8413:   background: #DDDDDD;
1.543     albertel 8414: }
                   8415: 
1.584     albertel 8416: table.LC_sty_begin {
                   8417:   background: #BBFFBB;
                   8418: }
1.795     www      8419: 
1.584     albertel 8420: table.LC_sty_end {
                   8421:   background: #FFBBBB;
                   8422: }
                   8423: 
1.589     raeburn  8424: table.LC_double_column {
1.803     bisitz   8425:   border-width: 0;
1.589     raeburn  8426:   border-collapse: collapse;
                   8427:   width: 100%;
                   8428:   padding: 2px;
                   8429: }
                   8430: 
                   8431: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  8432:   top: 2px;
1.589     raeburn  8433:   left: 2px;
                   8434:   width: 47%;
                   8435:   vertical-align: top;
                   8436: }
                   8437: 
                   8438: table.LC_double_column tr td.LC_right_col {
                   8439:   top: 2px;
1.779     bisitz   8440:   right: 2px;
1.589     raeburn  8441:   width: 47%;
                   8442:   vertical-align: top;
                   8443: }
                   8444: 
1.591     raeburn  8445: div.LC_left_float {
                   8446:   float: left;
                   8447:   padding-right: 5%;
1.597     albertel 8448:   padding-bottom: 4px;
1.591     raeburn  8449: }
                   8450: 
                   8451: div.LC_clear_float_header {
1.597     albertel 8452:   padding-bottom: 2px;
1.591     raeburn  8453: }
                   8454: 
                   8455: div.LC_clear_float_footer {
1.597     albertel 8456:   padding-top: 10px;
1.591     raeburn  8457:   clear: both;
                   8458: }
                   8459: 
1.597     albertel 8460: div.LC_grade_show_user {
1.941     bisitz   8461: /*  border-left: 5px solid $sidebg; */
                   8462:   border-top: 5px solid #000000;
                   8463:   margin: 50px 0 0 0;
1.936     bisitz   8464:   padding: 15px 0 5px 10px;
1.597     albertel 8465: }
1.795     www      8466: 
1.936     bisitz   8467: div.LC_grade_show_user_odd_row {
1.941     bisitz   8468: /*  border-left: 5px solid #000000; */
                   8469: }
                   8470: 
                   8471: div.LC_grade_show_user div.LC_Box {
                   8472:   margin-right: 50px;
1.597     albertel 8473: }
                   8474: 
1.1461    raeburn  8475: div.LC_grade_show_user div.LC_Box table tr th {
                   8476:   font-weight: normal;
                   8477: }
                   8478: 
1.597     albertel 8479: div.LC_grade_submissions,
                   8480: div.LC_grade_message_center,
1.936     bisitz   8481: div.LC_grade_info_links {
1.597     albertel 8482:   margin: 5px;
                   8483:   width: 99%;
                   8484:   background: #FFFFFF;
                   8485: }
1.795     www      8486: 
1.597     albertel 8487: div.LC_grade_submissions_header,
1.936     bisitz   8488: div.LC_grade_message_center_header {
1.705     tempelho 8489:   font-weight: bold;
                   8490:   font-size: large;
1.597     albertel 8491: }
1.795     www      8492: 
1.597     albertel 8493: div.LC_grade_submissions_body,
1.936     bisitz   8494: div.LC_grade_message_center_body {
1.597     albertel 8495:   border: 1px solid black;
                   8496:   width: 99%;
                   8497:   background: #FFFFFF;
                   8498: }
1.795     www      8499: 
1.613     albertel 8500: table.LC_scantron_action {
                   8501:   width: 100%;
                   8502: }
1.795     www      8503: 
1.613     albertel 8504: table.LC_scantron_action tr th {
1.698     harmsja  8505:   font-weight:bold;
                   8506:   font-style:normal;
1.613     albertel 8507: }
1.795     www      8508: 
1.1461    raeburn  8509: div.LC_edit_problem_daxe_header {
                   8510:   padding: 3px;
                   8511:   background: $tabbg;
                   8512:   z-index: 100;
                   8513: }
                   8514: 
1.779     bisitz   8515: .LC_edit_problem_header,
1.614     albertel 8516: div.LC_edit_problem_footer {
1.705     tempelho 8517:   font-weight: normal;
                   8518:   font-size:  medium;
1.602     albertel 8519:   margin: 2px;
1.1060    bisitz   8520:   background-color: $sidebg;
1.600     albertel 8521: }
1.795     www      8522: 
1.600     albertel 8523: div.LC_edit_problem_header,
1.602     albertel 8524: div.LC_edit_problem_header div,
1.614     albertel 8525: div.LC_edit_problem_footer,
                   8526: div.LC_edit_problem_footer div,
1.602     albertel 8527: div.LC_edit_problem_editxml_header,
                   8528: div.LC_edit_problem_editxml_header div {
1.1205    golterma 8529:   z-index: 100;
1.600     albertel 8530: }
1.795     www      8531: 
1.600     albertel 8532: div.LC_edit_problem_header_title {
1.705     tempelho 8533:   font-weight: bold;
                   8534:   font-size: larger;
1.602     albertel 8535:   background: $tabbg;
                   8536:   padding: 3px;
1.1060    bisitz   8537:   margin: 0 0 5px 0;
1.602     albertel 8538: }
1.795     www      8539: 
1.602     albertel 8540: table.LC_edit_problem_header_title {
                   8541:   width: 100%;
1.600     albertel 8542:   background: $tabbg;
1.602     albertel 8543: }
                   8544: 
1.1205    golterma 8545: div.LC_edit_actionbar {
                   8546:     background-color: $sidebg;
1.1218    droeschl 8547:     margin: 0;
                   8548:     padding: 0;
                   8549:     line-height: 200%;
1.602     albertel 8550: }
1.795     www      8551: 
1.1218    droeschl 8552: div.LC_edit_actionbar div{
                   8553:     padding: 0;
                   8554:     margin: 0;
                   8555:     display: inline-block;
1.600     albertel 8556: }
1.795     www      8557: 
1.1124    bisitz   8558: .LC_edit_opt {
                   8559:   padding-left: 1em;
                   8560:   white-space: nowrap;
                   8561: }
                   8562: 
1.1152    golterma 8563: .LC_edit_problem_latexhelper{
                   8564:     text-align: right;
                   8565: }
                   8566: 
                   8567: #LC_edit_problem_colorful div{
                   8568:     margin-left: 40px;
                   8569: }
                   8570: 
1.1205    golterma 8571: #LC_edit_problem_codemirror div{
                   8572:     margin-left: 0px;
                   8573: }
                   8574: 
1.911     bisitz   8575: img.stift {
1.803     bisitz   8576:   border-width: 0;
                   8577:   vertical-align: middle;
1.677     riegler  8578: }
1.680     riegler  8579: 
1.1460    raeburn  8580: div.LC_mainmenu {
                   8581:   margin: 3px 2px 2px 1px;
                   8582:   float: left;
1.777     tempelho 8583: }
1.795     www      8584: 
1.716     raeburn  8585: div.LC_createcourse {
1.911     bisitz   8586:   margin: 10px 10px 10px 10px;
1.716     raeburn  8587: }
                   8588: 
1.917     raeburn  8589: .LC_dccid {
1.1130    raeburn  8590:   float: right;
1.917     raeburn  8591:   margin: 0.2em 0 0 0;
                   8592:   padding: 0;
                   8593:   font-size: 90%;
                   8594:   display:none;
                   8595: }
                   8596: 
1.897     wenzelju 8597: ol.LC_primary_menu a:hover,
1.721     harmsja  8598: ol#LC_MenuBreadcrumbs a:hover,
                   8599: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 8600: ul#LC_secondary_menu a:hover,
1.721     harmsja  8601: .LC_FormSectionClearButton input:hover
1.795     www      8602: ul.LC_TabContent   li:hover a {
1.952     onken    8603:   color:$button_hover;
1.911     bisitz   8604:   text-decoration:none;
1.693     droeschl 8605: }
                   8606: 
1.779     bisitz   8607: h1 {
1.911     bisitz   8608:   padding: 0;
                   8609:   line-height:130%;
1.693     droeschl 8610: }
1.698     harmsja  8611: 
1.911     bisitz   8612: h2,
                   8613: h3,
                   8614: h4,
                   8615: h5,
                   8616: h6 {
                   8617:   margin: 5px 0 5px 0;
                   8618:   padding: 0;
                   8619:   line-height:130%;
1.693     droeschl 8620: }
1.795     www      8621: 
                   8622: .LC_hcell {
1.911     bisitz   8623:   padding:3px 15px 3px 15px;
                   8624:   margin: 0;
                   8625:   background-color:$tabbg;
                   8626:   color:$fontmenu;
                   8627:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8628: }
1.795     www      8629: 
1.840     bisitz   8630: .LC_Box > .LC_hcell {
1.911     bisitz   8631:   margin: 0 -10px 10px -10px;
1.835     bisitz   8632: }
                   8633: 
1.721     harmsja  8634: .LC_noBorder {
1.911     bisitz   8635:   border: 0;
1.698     harmsja  8636: }
1.693     droeschl 8637: 
1.721     harmsja  8638: .LC_FormSectionClearButton input {
1.911     bisitz   8639:   background-color:transparent;
                   8640:   border: none;
                   8641:   cursor:pointer;
                   8642:   text-decoration:underline;
1.693     droeschl 8643: }
1.763     bisitz   8644: 
                   8645: .LC_help_open_topic {
1.911     bisitz   8646:   color: #FFFFFF;
                   8647:   background-color: #EEEEFF;
                   8648:   margin: 1px;
                   8649:   padding: 4px;
                   8650:   border: 1px solid #000033;
                   8651:   white-space: nowrap;
                   8652:   /* vertical-align: middle; */
1.759     neumanie 8653: }
1.693     droeschl 8654: 
1.911     bisitz   8655: dl,
                   8656: ul,
                   8657: div,
                   8658: fieldset {
                   8659:   margin: 10px 10px 10px 0;
                   8660:   /* overflow: hidden; */
1.693     droeschl 8661: }
1.795     www      8662: 
1.1404    raeburn  8663: fieldset#LC_selectuser {
1.1460    raeburn  8664:   margin: -1px 0 0 0;
                   8665:   padding: 0;
                   8666:   border: 0;
1.1404    raeburn  8667: }
                   8668: 
1.1211    raeburn  8669: article.geogebraweb div {
                   8670:     margin: 0;
                   8671: }
                   8672: 
1.838     bisitz   8673: fieldset > legend {
1.911     bisitz   8674:   font-weight: bold;
                   8675:   padding: 0 5px 0 5px;
1.838     bisitz   8676: }
                   8677: 
1.813     bisitz   8678: #LC_nav_bar {
1.911     bisitz   8679:   float: left;
1.995     raeburn  8680:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8681:   margin: 0 0 2px 0;
1.807     droeschl 8682: }
                   8683: 
1.916     droeschl 8684: #LC_realm {
                   8685:   margin: 0.2em 0 0 0;
                   8686:   padding: 0;
                   8687:   font-weight: bold;
                   8688:   text-align: center;
1.995     raeburn  8689:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8690: }
                   8691: 
1.911     bisitz   8692: #LC_nav_bar em {
                   8693:   font-weight: bold;
                   8694:   font-style: normal;
1.807     droeschl 8695: }
                   8696: 
1.897     wenzelju 8697: ol.LC_primary_menu {
1.934     droeschl 8698:   margin: 0;
1.1076    raeburn  8699:   padding: 0;
1.807     droeschl 8700: }
                   8701: 
1.852     droeschl 8702: ol#LC_PathBreadcrumbs {
1.911     bisitz   8703:   margin: 0;
1.693     droeschl 8704: }
                   8705: 
1.897     wenzelju 8706: ol.LC_primary_menu li {
1.1076    raeburn  8707:   color: RGB(80, 80, 80);
                   8708:   vertical-align: middle;
                   8709:   text-align: left;
                   8710:   list-style: none;
1.1205    golterma 8711:   position: relative;
1.1076    raeburn  8712:   float: left;
1.1205    golterma 8713:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8714:   line-height: 1.5em;
1.1076    raeburn  8715: }
                   8716: 
1.1205    golterma 8717: ol.LC_primary_menu li a,
                   8718: ol.LC_primary_menu li p {
1.1076    raeburn  8719:   display: block;
                   8720:   margin: 0;
                   8721:   padding: 0 5px 0 10px;
                   8722:   text-decoration: none;
                   8723: }
                   8724: 
1.1205    golterma 8725: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8726:   display: inline-block;
                   8727:   width: 95%;
                   8728:   text-align: left;
                   8729: }
                   8730: 
                   8731: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8732:   display: inline-block;	
                   8733:   width: 5%;
                   8734:   float: right;
                   8735:   text-align: right;
                   8736:   font-size: 70%;
                   8737: }
                   8738: 
                   8739: ol.LC_primary_menu ul {
1.1076    raeburn  8740:   display: none;
1.1205    golterma 8741:   width: 15em;
1.1076    raeburn  8742:   background-color: $data_table_light;
1.1205    golterma 8743:   position: absolute;
                   8744:   top: 100%;
1.1076    raeburn  8745: }
                   8746: 
1.1205    golterma 8747: ol.LC_primary_menu ul ul {
                   8748:   left: 100%;
                   8749:   top: 0;
                   8750: }
                   8751: 
                   8752: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8753:   display: block;
                   8754:   position: absolute;
                   8755:   margin: 0;
                   8756:   padding: 0;
1.1078    raeburn  8757:   z-index: 2;
1.1076    raeburn  8758: }
                   8759: 
                   8760: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8761: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8762:   font-size: 90%;
1.911     bisitz   8763:   vertical-align: top;
1.1076    raeburn  8764:   float: none;
1.1079    raeburn  8765:   border-left: 1px solid black;
                   8766:   border-right: 1px solid black;
1.1205    golterma 8767: /* A dark bottom border to visualize different menu options; 
                   8768: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8769:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8770: }
                   8771: 
1.1205    golterma 8772: ol.LC_primary_menu li li p:hover {
                   8773:   color:$button_hover;
                   8774:   text-decoration:none;
                   8775:   background-color:$data_table_dark;
1.1076    raeburn  8776: }
                   8777: 
                   8778: ol.LC_primary_menu li li a:hover {
                   8779:    color:$button_hover;
                   8780:    background-color:$data_table_dark;
1.693     droeschl 8781: }
                   8782: 
1.1205    golterma 8783: /* Font-size equal to the size of the predecessors*/
                   8784: ol.LC_primary_menu li:hover li li {
                   8785:   font-size: 100%;
                   8786: }
                   8787: 
1.897     wenzelju 8788: ol.LC_primary_menu li img {
1.911     bisitz   8789:   vertical-align: bottom;
1.934     droeschl 8790:   height: 1.1em;
1.1077    raeburn  8791:   margin: 0.2em 0 0 0;
1.693     droeschl 8792: }
                   8793: 
1.897     wenzelju 8794: ol.LC_primary_menu a {
1.911     bisitz   8795:   color: RGB(80, 80, 80);
                   8796:   text-decoration: none;
1.693     droeschl 8797: }
1.795     www      8798: 
1.949     droeschl 8799: ol.LC_primary_menu a.LC_new_message {
                   8800:   font-weight:bold;
                   8801:   color: darkred;
                   8802: }
                   8803: 
1.975     raeburn  8804: ol.LC_docs_parameters {
                   8805:   margin-left: 0;
                   8806:   padding: 0;
                   8807:   list-style: none;
                   8808: }
                   8809: 
                   8810: ol.LC_docs_parameters li {
                   8811:   margin: 0;
                   8812:   padding-right: 20px;
                   8813:   display: inline;
                   8814: }
                   8815: 
1.976     raeburn  8816: ol.LC_docs_parameters li:before {
                   8817:   content: "\\002022 \\0020";
                   8818: }
                   8819: 
                   8820: li.LC_docs_parameters_title {
                   8821:   font-weight: bold;
                   8822: }
                   8823: 
                   8824: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8825:   content: "";
                   8826: }
                   8827: 
1.897     wenzelju 8828: ul#LC_secondary_menu {
1.1107    raeburn  8829:   clear: right;
1.911     bisitz   8830:   color: $fontmenu;
                   8831:   background: $tabbg;
                   8832:   list-style: none;
                   8833:   padding: 0;
                   8834:   margin: 0;
                   8835:   width: 100%;
1.995     raeburn  8836:   text-align: left;
1.1107    raeburn  8837:   float: left;
1.808     droeschl 8838: }
                   8839: 
1.897     wenzelju 8840: ul#LC_secondary_menu li {
1.911     bisitz   8841:   font-weight: bold;
                   8842:   line-height: 1.8em;
1.1107    raeburn  8843:   border-right: 1px solid black;
                   8844:   float: left;
                   8845: }
                   8846: 
                   8847: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8848:   background-color: $data_table_light;
                   8849: }
                   8850: 
                   8851: ul#LC_secondary_menu li a {
1.911     bisitz   8852:   padding: 0 0.8em;
1.1107    raeburn  8853: }
                   8854: 
                   8855: ul#LC_secondary_menu li ul {
                   8856:   display: none;
                   8857: }
                   8858: 
                   8859: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8860:   display: block;
                   8861:   position: absolute;
                   8862:   margin: 0;
                   8863:   padding: 0;
                   8864:   list-style:none;
                   8865:   float: none;
                   8866:   background-color: $data_table_light;
                   8867:   z-index: 2;
                   8868:   margin-left: -1px;
                   8869: }
                   8870: 
                   8871: ul#LC_secondary_menu li ul li {
                   8872:   font-size: 90%;
                   8873:   vertical-align: top;
                   8874:   border-left: 1px solid black;
1.911     bisitz   8875:   border-right: 1px solid black;
1.1119    raeburn  8876:   background-color: $data_table_light;
1.1107    raeburn  8877:   list-style:none;
                   8878:   float: none;
                   8879: }
                   8880: 
                   8881: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8882:   background-color: $data_table_dark;
1.807     droeschl 8883: }
                   8884: 
1.847     tempelho 8885: ul.LC_TabContent {
1.911     bisitz   8886:   display:block;
                   8887:   background: $sidebg;
                   8888:   border-bottom: solid 1px $lg_border_color;
                   8889:   list-style:none;
1.1020    raeburn  8890:   margin: -1px -10px 0 -10px;
1.911     bisitz   8891:   padding: 0;
1.693     droeschl 8892: }
                   8893: 
1.795     www      8894: ul.LC_TabContent li,
                   8895: ul.LC_TabContentBigger li {
1.911     bisitz   8896:   float:left;
1.741     harmsja  8897: }
1.795     www      8898: 
1.897     wenzelju 8899: ul#LC_secondary_menu li a {
1.911     bisitz   8900:   color: $fontmenu;
                   8901:   text-decoration: none;
1.693     droeschl 8902: }
1.795     www      8903: 
1.721     harmsja  8904: ul.LC_TabContent {
1.952     onken    8905:   min-height:20px;
1.721     harmsja  8906: }
1.795     www      8907: 
                   8908: ul.LC_TabContent li {
1.911     bisitz   8909:   vertical-align:middle;
1.959     onken    8910:   padding: 0 16px 0 10px;
1.911     bisitz   8911:   background-color:$tabbg;
                   8912:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8913:   border-left: solid 1px $font;
1.721     harmsja  8914: }
1.795     www      8915: 
1.847     tempelho 8916: ul.LC_TabContent .right {
1.911     bisitz   8917:   float:right;
1.847     tempelho 8918: }
                   8919: 
1.911     bisitz   8920: ul.LC_TabContent li a,
                   8921: ul.LC_TabContent li {
                   8922:   color:rgb(47,47,47);
                   8923:   text-decoration:none;
                   8924:   font-size:95%;
                   8925:   font-weight:bold;
1.952     onken    8926:   min-height:20px;
                   8927: }
                   8928: 
1.959     onken    8929: ul.LC_TabContent li a:hover,
                   8930: ul.LC_TabContent li a:focus {
1.952     onken    8931:   color: $button_hover;
1.959     onken    8932:   background:none;
                   8933:   outline:none;
1.952     onken    8934: }
                   8935: 
                   8936: ul.LC_TabContent li:hover {
                   8937:   color: $button_hover;
                   8938:   cursor:pointer;
1.721     harmsja  8939: }
1.795     www      8940: 
1.911     bisitz   8941: ul.LC_TabContent li.active {
1.952     onken    8942:   color: $font;
1.911     bisitz   8943:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8944:   border-bottom:solid 1px #FFFFFF;
                   8945:   cursor: default;
1.744     ehlerst  8946: }
1.795     www      8947: 
1.959     onken    8948: ul.LC_TabContent li.active a {
                   8949:   color:$font;
                   8950:   background:#FFFFFF;
                   8951:   outline: none;
                   8952: }
1.1047    raeburn  8953: 
                   8954: ul.LC_TabContent li.goback {
                   8955:   float: left;
                   8956:   border-left: none;
                   8957: }
                   8958: 
1.870     tempelho 8959: #maincoursedoc {
1.911     bisitz   8960:   clear:both;
1.870     tempelho 8961: }
                   8962: 
                   8963: ul.LC_TabContentBigger {
1.911     bisitz   8964:   display:block;
                   8965:   list-style:none;
                   8966:   padding: 0;
1.870     tempelho 8967: }
                   8968: 
1.795     www      8969: ul.LC_TabContentBigger li {
1.911     bisitz   8970:   vertical-align:bottom;
                   8971:   height: 30px;
                   8972:   font-size:110%;
                   8973:   font-weight:bold;
                   8974:   color: #737373;
1.841     tempelho 8975: }
                   8976: 
1.957     onken    8977: ul.LC_TabContentBigger li.active {
                   8978:   position: relative;
                   8979:   top: 1px;
                   8980: }
                   8981: 
1.870     tempelho 8982: ul.LC_TabContentBigger li a {
1.911     bisitz   8983:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8984:   height: 30px;
                   8985:   line-height: 30px;
                   8986:   text-align: center;
                   8987:   display: block;
                   8988:   text-decoration: none;
1.958     onken    8989:   outline: none;  
1.741     harmsja  8990: }
1.795     www      8991: 
1.870     tempelho 8992: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8993:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8994:   color:$font;
1.744     ehlerst  8995: }
1.795     www      8996: 
1.870     tempelho 8997: ul.LC_TabContentBigger li b {
1.911     bisitz   8998:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8999:   display: block;
                   9000:   float: left;
                   9001:   padding: 0 30px;
1.957     onken    9002:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 9003: }
                   9004: 
1.956     onken    9005: ul.LC_TabContentBigger li:hover b {
                   9006:   color:$button_hover;
                   9007: }
                   9008: 
1.870     tempelho 9009: ul.LC_TabContentBigger li.active b {
1.911     bisitz   9010:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   9011:   color:$font;
1.957     onken    9012:   border: 0;
1.741     harmsja  9013: }
1.693     droeschl 9014: 
1.870     tempelho 9015: 
1.862     bisitz   9016: ul.LC_CourseBreadcrumbs {
                   9017:   background: $sidebg;
1.1020    raeburn  9018:   height: 2em;
1.862     bisitz   9019:   padding-left: 10px;
1.1020    raeburn  9020:   margin: 0;
1.862     bisitz   9021:   list-style-position: inside;
                   9022: }
                   9023: 
1.911     bisitz   9024: ol#LC_MenuBreadcrumbs,
1.862     bisitz   9025: ol#LC_PathBreadcrumbs {
1.911     bisitz   9026:   padding-left: 10px;
                   9027:   margin: 0;
1.933     droeschl 9028:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 9029: }
                   9030: 
1.911     bisitz   9031: ol#LC_MenuBreadcrumbs li,
                   9032: ol#LC_PathBreadcrumbs li,
1.862     bisitz   9033: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   9034:   display: inline;
1.933     droeschl 9035:   white-space: normal;  
1.693     droeschl 9036: }
                   9037: 
1.823     bisitz   9038: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   9039: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   9040:   text-decoration: none;
                   9041:   font-size:90%;
1.693     droeschl 9042: }
1.795     www      9043: 
1.969     droeschl 9044: ol#LC_MenuBreadcrumbs h1 {
                   9045:   display: inline;
                   9046:   font-size: 90%;
                   9047:   line-height: 2.5em;
                   9048:   margin: 0;
                   9049:   padding: 0;
                   9050: }
                   9051: 
1.795     www      9052: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   9053:   text-decoration:none;
                   9054:   font-size:100%;
                   9055:   font-weight:bold;
1.693     droeschl 9056: }
1.795     www      9057: 
1.840     bisitz   9058: .LC_Box {
1.911     bisitz   9059:   border: solid 1px $lg_border_color;
                   9060:   padding: 0 10px 10px 10px;
1.746     neumanie 9061: }
1.795     www      9062: 
1.1020    raeburn  9063: .LC_DocsBox {
                   9064:   border: solid 1px $lg_border_color;
                   9065:   padding: 0 0 10px 10px;
                   9066: }
                   9067: 
1.795     www      9068: .LC_AboutMe_Image {
1.911     bisitz   9069:   float:left;
                   9070:   margin-right:10px;
1.747     neumanie 9071: }
1.795     www      9072: 
                   9073: .LC_Clear_AboutMe_Image {
1.911     bisitz   9074:   clear:left;
1.747     neumanie 9075: }
1.795     www      9076: 
1.721     harmsja  9077: dl.LC_ListStyleClean dt {
1.911     bisitz   9078:   padding-right: 5px;
                   9079:   display: table-header-group;
1.693     droeschl 9080: }
                   9081: 
1.721     harmsja  9082: dl.LC_ListStyleClean dd {
1.911     bisitz   9083:   display: table-row;
1.693     droeschl 9084: }
                   9085: 
1.721     harmsja  9086: .LC_ListStyleClean,
                   9087: .LC_ListStyleSimple,
                   9088: .LC_ListStyleNormal,
1.795     www      9089: .LC_ListStyleSpecial {
1.911     bisitz   9090:   /* display:block; */
                   9091:   list-style-position: inside;
                   9092:   list-style-type: none;
                   9093:   overflow: hidden;
                   9094:   padding: 0;
1.693     droeschl 9095: }
                   9096: 
1.721     harmsja  9097: .LC_ListStyleSimple li,
                   9098: .LC_ListStyleSimple dd,
                   9099: .LC_ListStyleNormal li,
                   9100: .LC_ListStyleNormal dd,
                   9101: .LC_ListStyleSpecial li,
1.795     www      9102: .LC_ListStyleSpecial dd {
1.911     bisitz   9103:   margin: 0;
                   9104:   padding: 5px 5px 5px 10px;
                   9105:   clear: both;
1.693     droeschl 9106: }
                   9107: 
1.721     harmsja  9108: .LC_ListStyleClean li,
                   9109: .LC_ListStyleClean dd {
1.911     bisitz   9110:   padding-top: 0;
                   9111:   padding-bottom: 0;
1.693     droeschl 9112: }
                   9113: 
1.721     harmsja  9114: .LC_ListStyleSimple dd,
1.795     www      9115: .LC_ListStyleSimple li {
1.911     bisitz   9116:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 9117: }
                   9118: 
1.721     harmsja  9119: .LC_ListStyleSpecial li,
                   9120: .LC_ListStyleSpecial dd {
1.911     bisitz   9121:   list-style-type: none;
                   9122:   background-color: RGB(220, 220, 220);
                   9123:   margin-bottom: 4px;
1.693     droeschl 9124: }
                   9125: 
1.721     harmsja  9126: table.LC_SimpleTable {
1.911     bisitz   9127:   margin:5px;
                   9128:   border:solid 1px $lg_border_color;
1.795     www      9129: }
1.693     droeschl 9130: 
1.721     harmsja  9131: table.LC_SimpleTable tr {
1.911     bisitz   9132:   padding: 0;
                   9133:   border:solid 1px $lg_border_color;
1.693     droeschl 9134: }
1.795     www      9135: 
                   9136: table.LC_SimpleTable thead {
1.911     bisitz   9137:   background:rgb(220,220,220);
1.693     droeschl 9138: }
                   9139: 
1.721     harmsja  9140: div.LC_columnSection {
1.911     bisitz   9141:   display: block;
                   9142:   clear: both;
                   9143:   overflow: hidden;
                   9144:   margin: 0;
1.693     droeschl 9145: }
                   9146: 
1.721     harmsja  9147: div.LC_columnSection>* {
1.911     bisitz   9148:   float: left;
                   9149:   margin: 10px 20px 10px 0;
                   9150:   overflow:hidden;
1.693     droeschl 9151: }
1.721     harmsja  9152: 
1.795     www      9153: table em {
1.911     bisitz   9154:   font-weight: bold;
                   9155:   font-style: normal;
1.748     schulted 9156: }
1.795     www      9157: 
1.779     bisitz   9158: table.LC_tableBrowseRes,
1.795     www      9159: table.LC_tableOfContent {
1.911     bisitz   9160:   border:none;
                   9161:   border-spacing: 1px;
                   9162:   padding: 3px;
                   9163:   background-color: #FFFFFF;
                   9164:   font-size: 90%;
1.753     droeschl 9165: }
1.789     droeschl 9166: 
1.911     bisitz   9167: table.LC_tableOfContent {
                   9168:   border-collapse: collapse;
1.789     droeschl 9169: }
                   9170: 
1.771     droeschl 9171: table.LC_tableBrowseRes a,
1.768     schulted 9172: table.LC_tableOfContent a {
1.911     bisitz   9173:   background-color: transparent;
                   9174:   text-decoration: none;
1.753     droeschl 9175: }
                   9176: 
1.795     www      9177: table.LC_tableOfContent img {
1.911     bisitz   9178:   border: none;
                   9179:   height: 1.3em;
                   9180:   vertical-align: text-bottom;
                   9181:   margin-right: 0.3em;
1.753     droeschl 9182: }
1.757     schulted 9183: 
1.795     www      9184: a#LC_content_toolbar_firsthomework {
1.911     bisitz   9185:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  9186: }
                   9187: 
1.795     www      9188: a#LC_content_toolbar_everything {
1.911     bisitz   9189:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  9190: }
                   9191: 
1.795     www      9192: a#LC_content_toolbar_uncompleted {
1.911     bisitz   9193:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  9194: }
                   9195: 
1.795     www      9196: #LC_content_toolbar_clearbubbles {
1.911     bisitz   9197:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  9198: }
                   9199: 
1.795     www      9200: a#LC_content_toolbar_changefolder {
1.911     bisitz   9201:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 9202: }
                   9203: 
1.795     www      9204: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   9205:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 9206: }
                   9207: 
1.1043    raeburn  9208: a#LC_content_toolbar_edittoplevel {
                   9209:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   9210: }
                   9211: 
1.1384    raeburn  9212: a#LC_content_toolbar_printout {
                   9213:   background-image:url(/res/adm/pages/printout.gif);
                   9214: }
                   9215: 
1.795     www      9216: ul#LC_toolbar li a:hover {
1.911     bisitz   9217:   background-position: bottom center;
1.757     schulted 9218: }
                   9219: 
1.795     www      9220: ul#LC_toolbar {
1.911     bisitz   9221:   padding: 0;
                   9222:   margin: 2px;
                   9223:   list-style:none;
1.1449    raeburn  9224:   display:inline;
1.911     bisitz   9225:   background-color:white;
1.1082    raeburn  9226:   overflow: auto;
1.757     schulted 9227: }
                   9228: 
1.795     www      9229: ul#LC_toolbar li {
1.911     bisitz   9230:   border:1px solid white;
                   9231:   padding: 0;
                   9232:   margin: 0;
                   9233:   float: left;
                   9234:   display:inline;
                   9235:   vertical-align:middle;
1.1082    raeburn  9236:   white-space: nowrap;
1.911     bisitz   9237: }
1.757     schulted 9238: 
1.783     amueller 9239: 
1.795     www      9240: a.LC_toolbarItem {
1.911     bisitz   9241:   display:block;
                   9242:   padding: 0;
                   9243:   margin: 0;
                   9244:   height: 32px;
                   9245:   width: 32px;
                   9246:   color:white;
                   9247:   border: none;
                   9248:   background-repeat:no-repeat;
                   9249:   background-color:transparent;
1.757     schulted 9250: }
                   9251: 
1.1449    raeburn  9252: .LC_navtools {
                   9253:   display: inline-block;
                   9254:   padding: 0;
                   9255:   margin: 2px;
                   9256:   vertical-align: middle;
                   9257: }
                   9258: 
1.915     droeschl 9259: ul.LC_funclist {
                   9260:     margin: 0;
                   9261:     padding: 0.5em 1em 0.5em 0;
                   9262: }
                   9263: 
1.933     droeschl 9264: ul.LC_funclist > li:first-child {
                   9265:     font-weight:bold; 
                   9266:     margin-left:0.8em;
                   9267: }
                   9268: 
1.915     droeschl 9269: ul.LC_funclist + ul.LC_funclist {
                   9270:     /* 
                   9271:        left border as a seperator if we have more than
                   9272:        one list 
                   9273:     */
                   9274:     border-left: 1px solid $sidebg;
                   9275:     /* 
                   9276:        this hides the left border behind the border of the 
                   9277:        outer box if element is wrapped to the next 'line' 
                   9278:     */
                   9279:     margin-left: -1px;
                   9280: }
                   9281: 
1.843     bisitz   9282: ul.LC_funclist li {
1.915     droeschl 9283:   display: inline;
1.782     bisitz   9284:   white-space: nowrap;
1.915     droeschl 9285:   margin: 0 0 0 25px;
                   9286:   line-height: 150%;
1.782     bisitz   9287: }
                   9288: 
1.974     wenzelju 9289: .LC_hidden {
                   9290:   display: none;
                   9291: }
                   9292: 
1.1030    www      9293: .LCmodal-overlay {
                   9294: 		position:fixed;
                   9295: 		top:0;
                   9296: 		right:0;
                   9297: 		bottom:0;
                   9298: 		left:0;
                   9299: 		height:100%;
                   9300: 		width:100%;
                   9301: 		margin:0;
                   9302: 		padding:0;
                   9303: 		background:#999;
                   9304: 		opacity:.75;
                   9305: 		filter: alpha(opacity=75);
                   9306: 		-moz-opacity: 0.75;
                   9307: 		z-index:101;
                   9308: }
                   9309: 
                   9310: * html .LCmodal-overlay {   
                   9311: 		position: absolute;
                   9312: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   9313: }
                   9314: 
                   9315: .LCmodal-window {
                   9316: 		position:fixed;
                   9317: 		top:50%;
                   9318: 		left:50%;
                   9319: 		margin:0;
                   9320: 		padding:0;
                   9321: 		z-index:102;
                   9322: 	}
                   9323: 
                   9324: * html .LCmodal-window {
                   9325: 		position:absolute;
                   9326: }
                   9327: 
                   9328: .LCclose-window {
                   9329: 		position:absolute;
                   9330: 		width:32px;
                   9331: 		height:32px;
                   9332: 		right:8px;
                   9333: 		top:8px;
                   9334: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   9335: 		text-indent:-99999px;
                   9336: 		overflow:hidden;
                   9337: 		cursor:pointer;
                   9338: }
                   9339: 
1.1369    raeburn  9340: .LCisDisabled {
                   9341:   cursor: not-allowed;
                   9342:   opacity: 0.5;
                   9343: }
                   9344: 
                   9345: a[aria-disabled="true"] {
                   9346:   color: currentColor;
                   9347:   display: inline-block;  /* For IE11/ MS Edge bug */
                   9348:   pointer-events: none;
                   9349:   text-decoration: none;
                   9350: }
                   9351: 
1.1335    raeburn  9352: pre.LC_wordwrap {
                   9353:   white-space: pre-wrap;
                   9354:   white-space: -moz-pre-wrap;
                   9355:   white-space: -pre-wrap;
                   9356:   white-space: -o-pre-wrap;
                   9357:   word-wrap: break-word;
                   9358: }
                   9359: 
1.1100    raeburn  9360: /*
1.1231    damieng  9361:   styles used for response display
                   9362: */
1.1464    raeburn  9363: div.LC_radiofoil, div.LC_rankfoil, div.LC_optionfoil, div.LC_matchfoil, div.LC_login_links {
1.1231    damieng  9364:   margin: .5em 0em .5em 0em;
                   9365: }
                   9366: table.LC_itemgroup {
                   9367:   margin-top: 1em;
                   9368: }
                   9369: 
1.1462    raeburn  9370: table.LC_itemgroup tr th {
                   9371:   font-weight: normal;
                   9372: }
                   9373: 
                   9374: fieldset.LC_webbubbles {
                   9375:   margin: 2px 0 0 0;
                   9376:   padding: 0;
                   9377:   border: 0;
                   9378: }
                   9379: 
                   9380: ul.LC_webbubbles {
                   9381:   list-style: none;
                   9382:   padding: 0;
                   9383:   margin: 0;
                   9384:   text-align: left;
                   9385:   float: left;
                   9386: }
                   9387: 
                   9388: ul.LC_webbubbles li {
                   9389:   line-height: 1.8em;
                   9390:   border: 1px solid black;
                   9391:   padding: 0 2px 0 5px;
                   9392:   margin: 0 0 0 -1px;
                   9393:   float: left;
                   9394: }
                   9395: 
1.1231    damieng  9396: /*
1.1100    raeburn  9397:   styles used by TTH when "Default set of options to pass to tth/m
                   9398:   when converting TeX" in course settings has been set
                   9399: 
                   9400:   option passed: -t
                   9401: 
                   9402: */
                   9403: 
                   9404: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   9405: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   9406: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   9407: td div.norm {line-height:normal;}
                   9408: 
                   9409: /*
                   9410:   option passed -y3
                   9411: */
                   9412: 
                   9413: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   9414: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   9415: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   9416: 
1.1230    damieng  9417: /*
                   9418:   sections with roles, for content only
                   9419: */
                   9420: section[class^="role-"] {
                   9421:   padding-left: 10px;
                   9422:   padding-right: 5px;
                   9423:   margin-top: 8px;
                   9424:   margin-bottom: 8px;
                   9425:   border: 1px solid #2A4;
                   9426:   border-radius: 5px;
                   9427:   box-shadow: 0px 1px 1px #BBB;
                   9428: }
                   9429: section[class^="role-"]>h1 {
                   9430:   position: relative;
                   9431:   margin: 0px;
                   9432:   padding-top: 10px;
                   9433:   padding-left: 40px;
                   9434: }
                   9435: section[class^="role-"]>h1:before {
                   9436:   position: absolute;
                   9437:   left: -5px;
                   9438:   top: 5px;
                   9439: }
                   9440: section.role-activity>h1:before {
                   9441:   content:url('/adm/daxe/images/section_icons/activity.png');
                   9442: }
                   9443: section.role-advice>h1:before {
                   9444:   content:url('/adm/daxe/images/section_icons/advice.png');
                   9445: }
                   9446: section.role-bibliography>h1:before {
                   9447:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   9448: }
                   9449: section.role-citation>h1:before {
                   9450:   content:url('/adm/daxe/images/section_icons/citation.png');
                   9451: }
                   9452: section.role-conclusion>h1:before {
                   9453:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   9454: }
                   9455: section.role-definition>h1:before {
                   9456:   content:url('/adm/daxe/images/section_icons/definition.png');
                   9457: }
                   9458: section.role-demonstration>h1:before {
                   9459:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   9460: }
                   9461: section.role-example>h1:before {
                   9462:   content:url('/adm/daxe/images/section_icons/example.png');
                   9463: }
                   9464: section.role-explanation>h1:before {
                   9465:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   9466: }
                   9467: section.role-introduction>h1:before {
                   9468:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   9469: }
                   9470: section.role-method>h1:before {
                   9471:   content:url('/adm/daxe/images/section_icons/method.png');
                   9472: }
                   9473: section.role-more_information>h1:before {
                   9474:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   9475: }
                   9476: section.role-objectives>h1:before {
                   9477:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   9478: }
                   9479: section.role-prerequisites>h1:before {
                   9480:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   9481: }
                   9482: section.role-remark>h1:before {
                   9483:   content:url('/adm/daxe/images/section_icons/remark.png');
                   9484: }
                   9485: section.role-reminder>h1:before {
                   9486:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   9487: }
                   9488: section.role-summary>h1:before {
                   9489:   content:url('/adm/daxe/images/section_icons/summary.png');
                   9490: }
                   9491: section.role-syntax>h1:before {
                   9492:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   9493: }
                   9494: section.role-warning>h1:before {
                   9495:   content:url('/adm/daxe/images/section_icons/warning.png');
                   9496: }
                   9497: 
1.1269    raeburn  9498: #LC_minitab_header {
                   9499:   float:left;
                   9500:   width:100%;
                   9501:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   9502:   font-size:93%;
                   9503:   line-height:normal;
                   9504:   margin: 0.5em 0 0.5em 0;
                   9505: }
                   9506: #LC_minitab_header ul {
                   9507:   margin:0;
                   9508:   padding:10px 10px 0;
                   9509:   list-style:none;
                   9510: }
                   9511: #LC_minitab_header li {
                   9512:   float:left;
                   9513:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   9514:   margin:0;
                   9515:   padding:0 0 0 9px;
                   9516: }
                   9517: #LC_minitab_header a {
                   9518:   display:block;
                   9519:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   9520:   padding:5px 15px 4px 6px;
                   9521: }
                   9522: #LC_minitab_header #LC_current_minitab {
                   9523:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   9524: }
                   9525: #LC_minitab_header #LC_current_minitab a {
                   9526:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   9527:   padding-bottom:5px;
                   9528: }
                   9529: 
                   9530: 
1.343     albertel 9531: END
                   9532: }
                   9533: 
1.306     albertel 9534: =pod
                   9535: 
                   9536: =item * &headtag()
                   9537: 
                   9538: Returns a uniform footer for LON-CAPA web pages.
                   9539: 
1.307     albertel 9540: Inputs: $title - optional title for the head
                   9541:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 9542:         $args - optional arguments
1.319     albertel 9543:             force_register - if is true call registerurl so the remote is 
                   9544:                              informed
1.415     albertel 9545:             redirect       -> array ref of
                   9546:                                    1- seconds before redirect occurs
                   9547:                                    2- url to redirect to
                   9548:                                    3- whether the side effect should occur
1.315     albertel 9549:                            (side effect of setting 
                   9550:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  9551:                                redirected to)
                   9552:                                    4- whether the redirect target should be
                   9553:                                       the opener of the current (pop-up)
                   9554:                                       window (side effect of setting
                   9555:                                       $env{'internal.head.to_opener'} to
                   9556:                                       1, if true.
1.1388    raeburn  9557:                                    5- whether encrypt check should be skipped
1.352     albertel 9558:             domain         -> force to color decorate a page for a specific
                   9559:                                domain
                   9560:             function       -> force usage of a specific rolish color scheme
                   9561:             bgcolor        -> override the default page bgcolor
1.460     albertel 9562:             no_auto_mt_title
                   9563:                            -> prevent &mt()ing the title arg
1.464     albertel 9564: 
1.306     albertel 9565: =cut
                   9566: 
                   9567: sub headtag {
1.313     albertel 9568:     my ($title,$head_extra,$args) = @_;
1.306     albertel 9569:     
1.363     albertel 9570:     my $function = $args->{'function'} || &get_users_function();
                   9571:     my $domain   = $args->{'domain'}   || &determinedomain();
                   9572:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  9573:     my $httphost = $args->{'use_absolute'};
1.418     albertel 9574:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 9575: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 9576: 		   #time(),
1.418     albertel 9577: 		   $env{'environment.color.timestamp'},
1.363     albertel 9578: 		   $function,$domain,$bgcolor);
                   9579: 
1.369     www      9580:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 9581: 
1.308     albertel 9582:     my $result =
                   9583: 	'<head>'.
1.1160    raeburn  9584: 	&font_settings($args);
1.319     albertel 9585: 
1.1188    raeburn  9586:     my $inhibitprint;
                   9587:     if ($args->{'print_suppress'}) {
                   9588:         $inhibitprint = &print_suppression();
                   9589:     }
1.1064    raeburn  9590: 
1.1439    raeburn  9591:     if (!$args->{'frameset'} && !$args->{'switchserver'}) {
1.461     albertel 9592: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   9593:     }
1.962     droeschl 9594:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   9595:         $result .= Apache::lonxml::display_title();
1.319     albertel 9596:     }
1.436     albertel 9597:     if (!$args->{'no_nav_bar'} 
                   9598: 	&& !$args->{'only_body'}
1.1438    raeburn  9599: 	&& !$args->{'frameset'}
                   9600: 	&& !$args->{'switchserver'}) {
1.1154    raeburn  9601: 	$result .= &help_menu_js($httphost);
1.1032    www      9602:         $result.=&modal_window();
1.1038    www      9603:         $result.=&togglebox_script();
1.1034    www      9604:         $result.=&wishlist_window();
1.1041    www      9605:         $result.=&LCprogressbarUpdate_script();
1.1034    www      9606:     } else {
                   9607:         if ($args->{'add_modal'}) {
                   9608:            $result.=&modal_window();
                   9609:         }
                   9610:         if ($args->{'add_wishlist'}) {
                   9611:            $result.=&wishlist_window();
                   9612:         }
1.1038    www      9613:         if ($args->{'add_togglebox'}) {
                   9614:            $result.=&togglebox_script();
                   9615:         }
1.1041    www      9616:         if ($args->{'add_progressbar'}) {
                   9617:            $result.=&LCprogressbarUpdate_script();
                   9618:         }
1.436     albertel 9619:     }
1.314     albertel 9620:     if (ref($args->{'redirect'})) {
1.1388    raeburn  9621: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   9622:         if (!$skip_enc_check) {
                   9623:             $url = &Apache::lonenc::check_encrypt($url);
                   9624:         }
1.414     albertel 9625: 	if (!$inhibit_continue) {
                   9626: 	    $env{'internal.head.redirect'} = $url;
                   9627: 	}
1.1386    raeburn  9628: 	$result.=<<"ADDMETA";
1.313     albertel 9629: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  9630: ADDMETA
                   9631:         if ($to_opener) {
                   9632:             $env{'internal.head.to_opener'} = 1;
                   9633:             my $dest = &js_escape($url);
                   9634:             my $timeout = int($time * 1000);
                   9635:             $result .=<<"ENDJS";
                   9636: <script type="text/javascript">
                   9637: // <![CDATA[
                   9638: function LC_To_Opener() {
                   9639:     var dest = '$dest';
                   9640:     if (dest != '') {
                   9641:         if (window.opener != null && !window.opener.closed) {
                   9642:             window.opener.location.href=dest;
                   9643:             window.close();
                   9644:         } else {
                   9645:             window.location.href=dest;
                   9646:         }
                   9647:     }
                   9648: }
                   9649: \$(document).ready(function () {
                   9650:     setTimeout('LC_To_Opener()',$timeout);
                   9651: });
                   9652: // ]]>
                   9653: </script>
                   9654: ENDJS
                   9655:         } else {
                   9656:             $result.=<<"ADDMETA";
1.344     albertel 9657: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9658: ADDMETA
1.1386    raeburn  9659:         }
1.1210    raeburn  9660:     } else {
                   9661:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9662:             my $requrl = $env{'request.uri'};
                   9663:             if ($requrl eq '') {
                   9664:                 $requrl = $ENV{'REQUEST_URI'};
                   9665:                 $requrl =~ s/\?.+$//;
                   9666:             }
                   9667:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9668:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9669:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9670:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9671:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9672:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9673:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9674:                     my ($offload,$offloadoth);
1.1210    raeburn  9675:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9676:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9677:                             $offload = 1;
1.1353    raeburn  9678:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9679:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9680:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9681:                                     $offloadoth = 1;
                   9682:                                     $dom_in_use = $env{'user.domain'};
                   9683:                                 }
                   9684:                             }
1.1340    raeburn  9685:                         }
                   9686:                     }
                   9687:                     unless ($offload) {
                   9688:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9689:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9690:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9691:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9692:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9693:                                         $offload = 1;
1.1352    raeburn  9694:                                         $offloadoth = 1;
1.1340    raeburn  9695:                                         $dom_in_use = $env{'user.domain'};
                   9696:                                     }
1.1210    raeburn  9697:                                 }
1.1340    raeburn  9698:                             }
                   9699:                         }
                   9700:                     }
                   9701:                     if ($offload) {
1.1358    raeburn  9702:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9703:                         if (($newserver eq '') && ($offloadoth)) {
                   9704:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9705:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9706:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9707:                             }
                   9708:                         }
1.1340    raeburn  9709:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9710:                             my $numsec = 5;
                   9711:                             my $timeout = $numsec * 1000;
                   9712:                             my ($newurl,$locknum,%locks,$msg);
                   9713:                             if ($env{'request.role.adv'}) {
                   9714:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9715:                             }
                   9716:                             my $disable_submit = 0;
                   9717:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9718:                                 $disable_submit = 1;
                   9719:                             }
                   9720:                             if ($locknum) {
                   9721:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9722:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9723:                                        join(", ",sort(values(%locks)))."\n";
                   9724:                                 if (&show_course()) {
                   9725:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9726:                                 } else {
                   9727:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9728:                                 }
1.1340    raeburn  9729:                             } else {
                   9730:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9731:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9732:                                 }
                   9733:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9734:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9735:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9736:                                     $newurl .= '&role='.$env{'request.role'};
                   9737:                                 }
                   9738:                                 if ($env{'request.symb'}) {
                   9739:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9740:                                     if ($shownsymb =~ m{^/enc/}) {
                   9741:                                         my $reqdmajor = 2;
                   9742:                                         my $reqdminor = 11;
                   9743:                                         my $reqdsubminor = 3;
                   9744:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9745:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9746:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9747:                                         if (($major eq '' && $minor eq '') ||
                   9748:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9749:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9750:                                              ($reqdsubminor > $subminor))))) {
                   9751:                                             undef($shownsymb);
                   9752:                                         }
1.1210    raeburn  9753:                                     }
1.1340    raeburn  9754:                                     if ($shownsymb) {
                   9755:                                         &js_escape(\$shownsymb);
                   9756:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9757:                                     }
1.1340    raeburn  9758:                                 } else {
                   9759:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9760:                                     &js_escape(\$shownurl);
                   9761:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9762:                                 }
1.1340    raeburn  9763:                             }
                   9764:                             &js_escape(\$msg);
                   9765:                             $result.=<<OFFLOAD
1.1210    raeburn  9766: <meta http-equiv="pragma" content="no-cache" />
                   9767: <script type="text/javascript">
1.1215    raeburn  9768: // <![CDATA[
1.1210    raeburn  9769: function LC_Offload_Now() {
                   9770:     var dest = "$newurl";
                   9771:     if (dest != '') {
                   9772:         window.location.href="$newurl";
                   9773:     }
                   9774: }
1.1214    raeburn  9775: \$(document).ready(function () {
                   9776:     window.alert('$msg');
                   9777:     if ($disable_submit) {
1.1210    raeburn  9778:         \$(".LC_hwk_submit").prop("disabled", true);
                   9779:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9780:     }
                   9781:     setTimeout('LC_Offload_Now()', $timeout);
                   9782: });
1.1215    raeburn  9783: // ]]>
1.1210    raeburn  9784: </script>
                   9785: OFFLOAD
                   9786:                         }
                   9787:                     }
                   9788:                 }
                   9789:             }
                   9790:         }
1.313     albertel 9791:     }
1.306     albertel 9792:     if (!defined($title)) {
                   9793: 	$title = 'The LearningOnline Network with CAPA';
                   9794:     }
1.460     albertel 9795:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1432    raeburn  9796:     if ($title =~ /^LON-CAPA\s+/) {
                   9797:         $result .= '<title> '.$title.'</title>';
                   9798:     } else {
                   9799:         $result .= '<title> LON-CAPA '.$title.'</title>';
                   9800:     }
                   9801:     $result .= "\n".'<link rel="stylesheet" type="text/css" href="'.$url.'"';
1.1168    raeburn  9802:     if (!$args->{'frameset'}) {
                   9803:         $result .= ' /';
                   9804:     }
                   9805:     $result .= '>' 
1.1064    raeburn  9806:         .$inhibitprint
1.414     albertel 9807: 	.$head_extra;
1.1242    raeburn  9808:     my $clientmobile;
                   9809:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9810:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9811:     } else {
                   9812:         $clientmobile = $env{'browser.mobile'};
                   9813:     }
                   9814:     if ($clientmobile) {
1.1137    raeburn  9815:         $result .= '
1.1435    raeburn  9816: <meta name="viewport" content="width=device-width, initial-scale=1.0">
1.1137    raeburn  9817: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9818:     }
1.1455    raeburn  9819:     $result .= '<meta name="google" content="notranslate"';
                   9820:     if (!$args->{'frameset'}) {
                   9821:         $result .= ' /';
                   9822:     }
                   9823:     $result .= '>'."\n";
1.962     droeschl 9824:     return $result.'</head>';
1.306     albertel 9825: }
                   9826: 
                   9827: =pod
                   9828: 
1.340     albertel 9829: =item * &font_settings()
                   9830: 
                   9831: Returns neccessary <meta> to set the proper encoding
                   9832: 
1.1160    raeburn  9833: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9834: 
                   9835: =cut
                   9836: 
                   9837: sub font_settings {
1.1160    raeburn  9838:     my ($args) = @_;
1.340     albertel 9839:     my $headerstring='';
1.1160    raeburn  9840:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9841:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9842:         $headerstring.=
                   9843:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9844:         if (!$args->{'frameset'}) {
                   9845: 	    $headerstring.= ' /';
                   9846:         }
                   9847: 	$headerstring .= '>'."\n";
1.340     albertel 9848:     }
                   9849:     return $headerstring;
                   9850: }
                   9851: 
1.341     albertel 9852: =pod
                   9853: 
1.1064    raeburn  9854: =item * &print_suppression()
                   9855: 
                   9856: In course context returns css which causes the body to be blank when media="print",
                   9857: if printout generation is unavailable for the current resource.
                   9858: 
                   9859: This could be because:
                   9860: 
                   9861: (a) printstartdate is in the future
                   9862: 
                   9863: (b) printenddate is in the past
                   9864: 
                   9865: (c) there is an active exam block with "printout"
                   9866: functionality blocked
                   9867: 
                   9868: Users with pav, pfo or evb privileges are exempt.
                   9869: 
                   9870: Inputs: none
                   9871: 
                   9872: =cut
                   9873: 
                   9874: 
                   9875: sub print_suppression {
                   9876:     my $noprint;
                   9877:     if ($env{'request.course.id'}) {
                   9878:         my $scope = $env{'request.course.id'};
                   9879:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9880:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9881:             return;
                   9882:         }
                   9883:         if ($env{'request.course.sec'} ne '') {
                   9884:             $scope .= "/$env{'request.course.sec'}";
                   9885:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9886:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9887:                 return;
1.1064    raeburn  9888:             }
                   9889:         }
                   9890:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9891:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9892:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9893:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9894:         if ($blocked) {
                   9895:             my $checkrole = "cm./$cdom/$cnum";
                   9896:             if ($env{'request.course.sec'} ne '') {
                   9897:                 $checkrole .= "/$env{'request.course.sec'}";
                   9898:             }
                   9899:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9900:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9901:                 $noprint = 1;
                   9902:             }
                   9903:         }
                   9904:         unless ($noprint) {
                   9905:             my $symb = &Apache::lonnet::symbread();
                   9906:             if ($symb ne '') {
                   9907:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9908:                 if (ref($navmap)) {
                   9909:                     my $res = $navmap->getBySymb($symb);
                   9910:                     if (ref($res)) {
                   9911:                         if (!$res->resprintable()) {
                   9912:                             $noprint = 1;
                   9913:                         }
                   9914:                     }
                   9915:                 }
                   9916:             }
                   9917:         }
                   9918:         if ($noprint) {
                   9919:             return <<"ENDSTYLE";
                   9920: <style type="text/css" media="print">
                   9921:     body { display:none }
                   9922: </style>
                   9923: ENDSTYLE
                   9924:         }
                   9925:     }
                   9926:     return;
                   9927: }
                   9928: 
                   9929: =pod
                   9930: 
1.341     albertel 9931: =item * &xml_begin()
                   9932: 
                   9933: Returns the needed doctype and <html>
                   9934: 
                   9935: Inputs: none
                   9936: 
                   9937: =cut
                   9938: 
                   9939: sub xml_begin {
1.1168    raeburn  9940:     my ($is_frameset) = @_;
1.341     albertel 9941:     my $output='';
                   9942: 
                   9943:     if ($env{'browser.mathml'}) {
                   9944: 	$output='<?xml version="1.0"?>'
                   9945:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9946: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9947:             
                   9948: #	    .'<!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">] >'
                   9949: 	    .'<!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">'
                   9950:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9951: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9952:     } elsif ($is_frameset) {
                   9953:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
1.1459    raeburn  9954:                 '<html lang="en">'."\n";
1.341     albertel 9955:     } else {
1.1168    raeburn  9956: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9957:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9958:     }
                   9959:     return $output;
                   9960: }
1.340     albertel 9961: 
                   9962: =pod
                   9963: 
1.306     albertel 9964: =item * &start_page()
                   9965: 
                   9966: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9967: 
1.648     raeburn  9968: Inputs:
                   9969: 
                   9970: =over 4
                   9971: 
                   9972: $title - optional title for the page
                   9973: 
                   9974: $head_extra - optional extra HTML to incude inside the <head>
                   9975: 
                   9976: $args - additional optional args supported are:
                   9977: 
                   9978: =over 8
                   9979: 
                   9980:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9981:                                     arg on
1.814     bisitz   9982:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9983:              add_entries    -> additional attributes to add to the  <body>
                   9984:              domain         -> force to color decorate a page for a 
1.317     albertel 9985:                                     specific domain
1.648     raeburn  9986:              function       -> force usage of a specific rolish color
1.317     albertel 9987:                                     scheme
1.648     raeburn  9988:              redirect       -> see &headtag()
                   9989:              bgcolor        -> override the default page bg color
                   9990:              js_ready       -> return a string ready for being used in 
1.317     albertel 9991:                                     a javascript writeln
1.648     raeburn  9992:              html_encode    -> return a string ready for being used in 
1.320     albertel 9993:                                     a html attribute
1.648     raeburn  9994:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9995:                                     $forcereg arg
1.648     raeburn  9996:              frameset       -> if true will start with a <frameset>
1.330     albertel 9997:                                     rather than <body>
1.648     raeburn  9998:              skip_phases    -> hash ref of 
1.338     albertel 9999:                                     head -> skip the <html><head> generation
                   10000:                                     body -> skip all <body> generation
1.648     raeburn  10001:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 10002:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  10003:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1437    raeburn  10004:              bread_crumbs_style -> breadcrumbs are contained within <div id="LC_breadcrumbs">,
                   10005:                                    and &standard_css() contains CSS for #LC_breadcrumbs, if you want
                   10006:                                    to override those values, or add to them, specify the value to
                   10007:                                    include in the style attribute to include in the div tag by using
                   10008:                                    bread_crumbs_style (e.g., overflow: visible)
1.1272    raeburn  10009:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   10010:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  10011:              group          -> includes the current group, if page is for a 
1.1274    raeburn  10012:                                specific group
                   10013:              use_absolute   -> for request for external resource or syllabus, this
                   10014:                                will contain https://<hostname> if server uses
                   10015:                                https (as per hosts.tab), but request is for http
                   10016:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  10017:              links_disabled -> Links in primary and secondary menus are disabled
                   10018:                                (Can enable them once page has loaded - see lonroles.pm
                   10019:                                for an example).
1.1380    raeburn  10020:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 10021: 
1.648     raeburn  10022: =back
1.460     albertel 10023: 
1.648     raeburn  10024: =back
1.562     albertel 10025: 
1.306     albertel 10026: =cut
                   10027: 
                   10028: sub start_page {
1.309     albertel 10029:     my ($title,$head_extra,$args) = @_;
1.318     albertel 10030:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 10031: 
1.315     albertel 10032:     $env{'internal.start_page'}++;
1.1359    raeburn  10033:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 10034: 
1.338     albertel 10035:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  10036:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 10037:     }
1.1316    raeburn  10038: 
                   10039:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  10040:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   10041:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   10042:                 $args->{'no_primary_menu'} = 1;
                   10043:             }
                   10044:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   10045:                 $args->{'no_inline_menu'} = 1;
                   10046:             }
                   10047:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   10048:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   10049:             }
                   10050:         } else {
                   10051:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10052:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   10053:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   10054:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   10055:                     $args->{'no_primary_menu'} = 1;
                   10056:                 }
                   10057:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   10058:                     $args->{'no_inline_menu'} = 1;
                   10059:                 }
                   10060:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   10061:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   10062:                 }
                   10063:             }
                   10064:         }
1.1316    raeburn  10065:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   10066:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   10067:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  10068:     } elsif ($env{'request.course.id'}) {
                   10069:         my $expiretime=600;
                   10070:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   10071:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   10072:         }
                   10073:         my ($deeplinkmenu,$menuref);
                   10074:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   10075:         if ($menucoll) {
                   10076:             if (ref($menuref) eq 'HASH') {
                   10077:                 %menu = %{$menuref};
                   10078:             }
                   10079:             if ($menu{'top'} eq 'n') {
                   10080:                 $args->{'no_primary_menu'} = 1;
                   10081:             }
                   10082:             if ($menu{'inline'} eq 'n') {
                   10083:                 unless (&Apache::lonnet::allowed('opa')) {
                   10084:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10085:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10086:                     my $crstype = &course_type();
                   10087:                     my $now = time;
                   10088:                     my $ccrole;
                   10089:                     if ($crstype eq 'Community') {
                   10090:                         $ccrole = 'co';
                   10091:                     } else {
                   10092:                         $ccrole = 'cc';
                   10093:                     }
                   10094:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   10095:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   10096:                         if ((($start) && ($start<0)) ||
                   10097:                             (($end) && ($end<$now))  ||
                   10098:                             (($start) && ($now<$start))) {
                   10099:                             $args->{'no_inline_menu'} = 1;
                   10100:                         }
                   10101:                     } else {
                   10102:                         $args->{'no_inline_menu'} = 1;
                   10103:                     }
                   10104:                 }
                   10105:             }
                   10106:         }
1.1316    raeburn  10107:     }
1.1359    raeburn  10108: 
1.1385    raeburn  10109:     my $showncrumbs;
1.338     albertel 10110:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   10111: 	if ($args->{'frameset'}) {
                   10112: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   10113: 						$args->{'add_entries'});
                   10114: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   10115:         } else {
                   10116:             $result .=
                   10117:                 &bodytag($title, 
                   10118:                          $args->{'function'},       $args->{'add_entries'},
                   10119:                          $args->{'only_body'},      $args->{'domain'},
                   10120:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  10121:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  10122:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   10123:                          \%menu,\$showncrumbs);
1.831     bisitz   10124:         }
1.330     albertel 10125:     }
1.338     albertel 10126: 
1.315     albertel 10127:     if ($args->{'js_ready'}) {
1.713     kaisler  10128: 		$result = &js_ready($result);
1.315     albertel 10129:     }
1.320     albertel 10130:     if ($args->{'html_encode'}) {
1.713     kaisler  10131: 		$result = &html_encode($result);
                   10132:     }
                   10133: 
1.813     bisitz   10134:     # Preparation for new and consistent functionlist at top of screen
                   10135:     # if ($args->{'functionlist'}) {
                   10136:     #            $result .= &build_functionlist();
                   10137:     #}
                   10138: 
1.964     droeschl 10139:     # Don't add anything more if only_body wanted or in const space
                   10140:     return $result if    $args->{'only_body'} 
                   10141:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   10142: 
                   10143:     #Breadcrumbs
1.758     kaisler  10144:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  10145:         unless ($showncrumbs) {
1.758     kaisler  10146: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   10147: 		#if any br links exists, add them to the breadcrumbs
                   10148: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   10149: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   10150: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   10151: 			}
                   10152: 		}
1.1096    raeburn  10153:                 # if @advtools array contains items add then to the breadcrumbs
                   10154:                 if (@advtools > 0) {
                   10155:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   10156:                 }
1.1272    raeburn  10157:                 my $menulink;
                   10158:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   10159:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  10160:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  10161:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   10162:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   10163:                      (!$env{'request.role.adv'}))) {
                   10164:                     $menulink = 0;
                   10165:                 } else {
                   10166:                     undef($menulink);
                   10167:                 }
1.1385    raeburn  10168:                 my $linkprotout;
                   10169:                 if ($env{'request.deeplink.login'}) {
                   10170:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   10171:                     if ($linkprotout) {
                   10172:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   10173:                     }
                   10174:                 }
1.758     kaisler  10175: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   10176: 		if(exists($args->{'bread_crumbs_component'})){
1.1437    raeburn  10177: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},
                   10178:                                                                        '',$menulink,'',
                   10179:                                                                        $args->{'bread_crumbs_style'});
1.1237    raeburn  10180:                 } else {
1.1437    raeburn  10181: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink,'',
                   10182:                                                                        $args->{'bread_crumbs_style'});
1.758     kaisler  10183: 		}
1.1385    raeburn  10184:         }
1.320     albertel 10185:     }
1.315     albertel 10186:     return $result;
1.306     albertel 10187: }
                   10188: 
                   10189: sub end_page {
1.315     albertel 10190:     my ($args) = @_;
                   10191:     $env{'internal.end_page'}++;
1.330     albertel 10192:     my $result;
1.335     albertel 10193:     if ($args->{'discussion'}) {
                   10194: 	my ($target,$parser);
                   10195: 	if (ref($args->{'discussion'})) {
                   10196: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   10197: 				$args->{'discussion'}{'parser'});
                   10198: 	}
                   10199: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   10200:     }
1.330     albertel 10201:     if ($args->{'frameset'}) {
                   10202: 	$result .= '</frameset>';
                   10203:     } else {
1.635     raeburn  10204: 	$result .= &endbodytag($args);
1.330     albertel 10205:     }
1.1080    raeburn  10206:     unless ($args->{'notbody'}) {
                   10207:         $result .= "\n</html>";
                   10208:     }
1.330     albertel 10209: 
1.315     albertel 10210:     if ($args->{'js_ready'}) {
1.317     albertel 10211: 	$result = &js_ready($result);
1.315     albertel 10212:     }
1.335     albertel 10213: 
1.320     albertel 10214:     if ($args->{'html_encode'}) {
                   10215: 	$result = &html_encode($result);
                   10216:     }
1.335     albertel 10217: 
1.315     albertel 10218:     return $result;
                   10219: }
                   10220: 
1.1359    raeburn  10221: sub menucoll_in_effect {
                   10222:     my ($menucoll,$deeplinkmenu,%menu);
                   10223:     if ($env{'request.course.id'}) {
                   10224:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  10225:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  10226:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  10227:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10228:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10229:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   10230:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   10231:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10232:                     if (ref($navmap)) {
                   10233:                         $deeplink = $navmap->get_mapparam(undef,
                   10234:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   10235:                                                           '0.deeplink');
1.1370    raeburn  10236:                     } else {
                   10237:                         $check_login_symb = 1;
1.1362    raeburn  10238:                     }
                   10239:                 } else {
1.1370    raeburn  10240:                     my $symb = &Apache::lonnet::symbread();
                   10241:                     if ($symb) {
                   10242:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   10243:                     } else {
                   10244:                         $check_login_symb = 1;
                   10245:                     }
1.1362    raeburn  10246:                 }
                   10247:             } else {
1.1370    raeburn  10248:                 $check_login_symb = 1;
                   10249:             }
                   10250:             if ($check_login_symb) {
1.1362    raeburn  10251:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   10252:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   10253:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   10254:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10255:                     if (ref($navmap)) {
                   10256:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   10257:                     }
                   10258:                 } else {
                   10259:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   10260:                 }
                   10261:             }
1.1359    raeburn  10262:             if ($deeplink ne '') {
1.1378    raeburn  10263:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  10264:                 if ($display =~ /^\d+$/) {
                   10265:                     $deeplinkmenu = 1;
                   10266:                     $menucoll = $display;
                   10267:                 }
                   10268:             }
                   10269:         }
                   10270:         if ($menucoll) {
                   10271:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   10272:         }
                   10273:     }
                   10274:     return ($menucoll,$deeplinkmenu,\%menu);
                   10275: }
                   10276: 
1.1362    raeburn  10277: sub deeplink_login_symb {
                   10278:     my ($cnum,$cdom) = @_;
                   10279:     my $login_symb;
                   10280:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  10281:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   10282:     }
                   10283:     return $login_symb;
                   10284: }
                   10285: 
                   10286: sub symb_from_tinyurl {
                   10287:     my ($url,$cnum,$cdom) = @_;
                   10288:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   10289:         my $key = $1;
                   10290:         my ($tinyurl,$login);
                   10291:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   10292:         if (defined($cached)) {
                   10293:             $tinyurl = $result;
                   10294:         } else {
                   10295:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   10296:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   10297:             if ($currtiny{$key} ne '') {
                   10298:                 $tinyurl = $currtiny{$key};
                   10299:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  10300:             }
1.1364    raeburn  10301:         }
                   10302:         if ($tinyurl ne '') {
                   10303:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   10304:             if (wantarray) {
                   10305:                 return ($cnumreq,$symb);
                   10306:             } elsif ($cnumreq eq $cnum) {
                   10307:                 return $symb;
1.1362    raeburn  10308:             }
                   10309:         }
                   10310:     }
1.1364    raeburn  10311:     if (wantarray) {
                   10312:         return ();
                   10313:     } else {
                   10314:         return;
                   10315:     }
1.1362    raeburn  10316: }
                   10317: 
1.1405    raeburn  10318: sub usable_exttools {
                   10319:     my %tooltypes;
                   10320:     if ($env{'request.course.id'}) {
                   10321:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   10322:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   10323:                %tooltypes = (
                   10324:                              crs => 1,
                   10325:                              dom => 1,
                   10326:                             );
                   10327:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   10328:                $tooltypes{'crs'} = 1;
                   10329:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   10330:                $tooltypes{'dom'} = 1;
                   10331:            }
                   10332:         } else {
                   10333:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10334:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10335:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   10336:             if ($crstype eq '') {
                   10337:                 $crstype = 'course';
                   10338:             }
                   10339:             if ($crstype eq 'course') {
                   10340:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   10341:                     $crstype = 'official';
                   10342:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   10343:                     $crstype = 'textbook';
                   10344:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   10345:                     $crstype = 'lti';
                   10346:                 } else {
                   10347:                     $crstype = 'unofficial';
                   10348:                 }
                   10349:             }
                   10350:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   10351:             if ($domdefaults{$crstype.'domexttool'}) {
                   10352:                 $tooltypes{'dom'} = 1;
                   10353:             }
                   10354:             if ($domdefaults{$crstype.'exttool'}) {
                   10355:                 $tooltypes{'crs'} = 1;
                   10356:             }
                   10357:         }
                   10358:     }
                   10359:     return %tooltypes;
                   10360: }
                   10361: 
1.1034    www      10362: sub wishlist_window {
                   10363:     return(<<'ENDWISHLIST');
1.1046    raeburn  10364: <script type="text/javascript">
1.1034    www      10365: // <![CDATA[
                   10366: // <!-- BEGIN LON-CAPA Internal
                   10367: function set_wishlistlink(title, path) {
                   10368:     if (!title) {
                   10369:         title = document.title;
                   10370:         title = title.replace(/^LON-CAPA /,'');
                   10371:     }
1.1175    raeburn  10372:     title = encodeURIComponent(title);
1.1203    raeburn  10373:     title = title.replace("'","\\\'");
1.1034    www      10374:     if (!path) {
                   10375:         path = location.pathname;
                   10376:     }
1.1175    raeburn  10377:     path = encodeURIComponent(path);
1.1203    raeburn  10378:     path = path.replace("'","\\\'");
1.1034    www      10379:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   10380:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   10381: }
                   10382: // END LON-CAPA Internal -->
                   10383: // ]]>
                   10384: </script>
                   10385: ENDWISHLIST
                   10386: }
                   10387: 
1.1030    www      10388: sub modal_window {
                   10389:     return(<<'ENDMODAL');
1.1046    raeburn  10390: <script type="text/javascript">
1.1030    www      10391: // <![CDATA[
                   10392: // <!-- BEGIN LON-CAPA Internal
                   10393: var modalWindow = {
                   10394: 	parent:"body",
                   10395: 	windowId:null,
                   10396: 	content:null,
                   10397: 	width:null,
                   10398: 	height:null,
                   10399: 	close:function()
                   10400: 	{
                   10401: 	        $(".LCmodal-window").remove();
                   10402: 	        $(".LCmodal-overlay").remove();
                   10403: 	},
                   10404: 	open:function()
                   10405: 	{
                   10406: 		var modal = "";
                   10407: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   10408: 		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;\">";
                   10409: 		modal += this.content;
                   10410: 		modal += "</div>";	
                   10411: 
                   10412: 		$(this.parent).append(modal);
                   10413: 
                   10414: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   10415: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   10416: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   10417: 	}
                   10418: };
1.1140    raeburn  10419: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      10420: 	{
1.1266    raeburn  10421:                 source = source.replace(/'/g,"&#39;");
1.1030    www      10422: 		modalWindow.windowId = "myModal";
                   10423: 		modalWindow.width = width;
                   10424: 		modalWindow.height = height;
1.1196    raeburn  10425: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      10426: 		modalWindow.open();
1.1208    raeburn  10427: 	};
1.1030    www      10428: // END LON-CAPA Internal -->
                   10429: // ]]>
                   10430: </script>
                   10431: ENDMODAL
                   10432: }
                   10433: 
                   10434: sub modal_link {
1.1140    raeburn  10435:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      10436:     unless ($width) { $width=480; }
                   10437:     unless ($height) { $height=400; }
1.1031    www      10438:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  10439:     unless ($transparency) { $transparency='true'; }
                   10440: 
1.1074    raeburn  10441:     my $target_attr;
                   10442:     if (defined($target)) {
                   10443:         $target_attr = 'target="'.$target.'"';
                   10444:     }
                   10445:     return <<"ENDLINK";
1.1336    raeburn  10446: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  10447: ENDLINK
1.1030    www      10448: }
                   10449: 
1.1032    www      10450: sub modal_adhoc_script {
1.1365    raeburn  10451:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   10452:     my $mathjax;
                   10453:     if ($possmathjax) {
                   10454:         $mathjax = <<'ENDJAX';
                   10455:                if (typeof MathJax == 'object') {
                   10456:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   10457:                }
                   10458: ENDJAX
                   10459:     }
1.1032    www      10460:     return (<<ENDADHOC);
1.1046    raeburn  10461: <script type="text/javascript">
1.1032    www      10462: // <![CDATA[
                   10463:         var $funcname = function()
                   10464:         {
                   10465:                 modalWindow.windowId = "myModal";
                   10466:                 modalWindow.width = $width;
                   10467:                 modalWindow.height = $height;
                   10468:                 modalWindow.content = '$content';
                   10469:                 modalWindow.open();
1.1365    raeburn  10470:                 $mathjax
1.1032    www      10471:         };  
                   10472: // ]]>
                   10473: </script>
                   10474: ENDADHOC
                   10475: }
                   10476: 
1.1041    www      10477: sub modal_adhoc_inner {
1.1365    raeburn  10478:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      10479:     my $innerwidth=$width-20;
                   10480:     $content=&js_ready(
1.1140    raeburn  10481:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   10482:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   10483:                  $content.
1.1041    www      10484:                  &end_scrollbox().
1.1140    raeburn  10485:                  &end_page()
1.1041    www      10486:              );
1.1365    raeburn  10487:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      10488: }
                   10489: 
                   10490: sub modal_adhoc_window {
1.1365    raeburn  10491:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   10492:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      10493:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   10494: }
                   10495: 
                   10496: sub modal_adhoc_launch {
                   10497:     my ($funcname,$width,$height,$content)=@_;
                   10498:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   10499: <script type="text/javascript">
                   10500: // <![CDATA[
                   10501: $funcname();
                   10502: // ]]>
                   10503: </script>
                   10504: ENDLAUNCH
                   10505: }
                   10506: 
                   10507: sub modal_adhoc_close {
                   10508:     return (<<ENDCLOSE);
                   10509: <script type="text/javascript">
                   10510: // <![CDATA[
                   10511: modalWindow.close();
                   10512: // ]]>
                   10513: </script>
                   10514: ENDCLOSE
                   10515: }
                   10516: 
1.1038    www      10517: sub togglebox_script {
                   10518:    return(<<ENDTOGGLE);
                   10519: <script type="text/javascript"> 
                   10520: // <![CDATA[
                   10521: function LCtoggleDisplay(id,hidetext,showtext) {
                   10522:    link = document.getElementById(id + "link").childNodes[0];
                   10523:    with (document.getElementById(id).style) {
                   10524:       if (display == "none" ) {
                   10525:           display = "inline";
                   10526:           link.nodeValue = hidetext;
                   10527:         } else {
                   10528:           display = "none";
                   10529:           link.nodeValue = showtext;
                   10530:        }
                   10531:    }
                   10532: }
                   10533: // ]]>
                   10534: </script>
                   10535: ENDTOGGLE
                   10536: }
                   10537: 
1.1039    www      10538: sub start_togglebox {
                   10539:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   10540:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   10541:     unless ($showtext) { $showtext=&mt('show'); }
                   10542:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   10543:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   10544:     return &start_data_table().
                   10545:            &start_data_table_header_row().
                   10546:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   10547:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   10548:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   10549:            &end_data_table_header_row().
                   10550:            '<tr id="'.$id.'" style="display:none""><td>';
                   10551: }
                   10552: 
                   10553: sub end_togglebox {
                   10554:     return '</td></tr>'.&end_data_table();
                   10555: }
                   10556: 
1.1041    www      10557: sub LCprogressbar_script {
1.1302    raeburn  10558:    my ($id,$number_to_do)=@_;
                   10559:    if ($number_to_do) {
                   10560:        return(<<ENDPROGRESS);
1.1041    www      10561: <script type="text/javascript">
                   10562: // <![CDATA[
1.1045    www      10563: \$('#progressbar$id').progressbar({
1.1041    www      10564:   value: 0,
                   10565:   change: function(event, ui) {
                   10566:     var newVal = \$(this).progressbar('option', 'value');
                   10567:     \$('.pblabel', this).text(LCprogressTxt);
                   10568:   }
                   10569: });
                   10570: // ]]>
                   10571: </script>
                   10572: ENDPROGRESS
1.1302    raeburn  10573:    } else {
                   10574:        return(<<ENDPROGRESS);
                   10575: <script type="text/javascript">
                   10576: // <![CDATA[
                   10577: \$('#progressbar$id').progressbar({
                   10578:   value: false,
                   10579:   create: function(event, ui) {
                   10580:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   10581:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   10582:   }
                   10583: });
                   10584: // ]]>
                   10585: </script>
                   10586: ENDPROGRESS
                   10587:    }
1.1041    www      10588: }
                   10589: 
                   10590: sub LCprogressbarUpdate_script {
                   10591:    return(<<ENDPROGRESSUPDATE);
                   10592: <style type="text/css">
                   10593: .ui-progressbar { position:relative; }
1.1302    raeburn  10594: .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      10595: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   10596: </style>
                   10597: <script type="text/javascript">
                   10598: // <![CDATA[
1.1045    www      10599: var LCprogressTxt='---';
                   10600: 
1.1302    raeburn  10601: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      10602:    LCprogressTxt=progresstext;
1.1302    raeburn  10603:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   10604:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   10605:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  10606:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   10607:    } else {
                   10608:        \$('#progressbar'+id).progressbar('value',percent);
                   10609:    }
1.1041    www      10610: }
                   10611: // ]]>
                   10612: </script>
                   10613: ENDPROGRESSUPDATE
                   10614: }
                   10615: 
1.1042    www      10616: my $LClastpercent;
1.1045    www      10617: my $LCidcnt;
                   10618: my $LCcurrentid;
1.1042    www      10619: 
1.1041    www      10620: sub LCprogressbar {
1.1302    raeburn  10621:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      10622:     $LClastpercent=0;
1.1045    www      10623:     $LCidcnt++;
                   10624:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  10625:     my ($starting,$content);
                   10626:     if ($number_to_do) {
                   10627:         $starting=&mt('Starting');
                   10628:         $content=(<<ENDPROGBAR);
                   10629: $preamble
1.1045    www      10630:   <div id="progressbar$LCcurrentid">
1.1041    www      10631:     <span class="pblabel">$starting</span>
                   10632:   </div>
                   10633: ENDPROGBAR
1.1302    raeburn  10634:     } else {
                   10635:         $starting=&mt('Loading...');
                   10636:         $LClastpercent='false';
                   10637:         $content=(<<ENDPROGBAR);
                   10638: $preamble
                   10639:   <div id="progressbar$LCcurrentid">
                   10640:       <div class="progress-label">$starting</div>
                   10641:   </div>
                   10642: ENDPROGBAR
                   10643:     }
                   10644:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      10645: }
                   10646: 
                   10647: sub LCprogressbarUpdate {
1.1302    raeburn  10648:     my ($r,$val,$text,$number_to_do)=@_;
                   10649:     if ($number_to_do) {
                   10650:         unless ($val) { 
                   10651:             if ($LClastpercent) {
                   10652:                 $val=$LClastpercent;
                   10653:             } else {
                   10654:                 $val=0;
                   10655:             }
                   10656:         }
                   10657:         if ($val<0) { $val=0; }
                   10658:         if ($val>100) { $val=0; }
                   10659:         $LClastpercent=$val;
                   10660:         unless ($text) { $text=$val.'%'; }
                   10661:     } else {
                   10662:         $val = 'false';
1.1042    www      10663:     }
1.1041    www      10664:     $text=&js_ready($text);
1.1044    www      10665:     &r_print($r,<<ENDUPDATE);
1.1041    www      10666: <script type="text/javascript">
                   10667: // <![CDATA[
1.1302    raeburn  10668: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10669: // ]]>
                   10670: </script>
                   10671: ENDUPDATE
1.1035    www      10672: }
                   10673: 
1.1042    www      10674: sub LCprogressbarClose {
                   10675:     my ($r)=@_;
                   10676:     $LClastpercent=0;
1.1044    www      10677:     &r_print($r,<<ENDCLOSE);
1.1042    www      10678: <script type="text/javascript">
                   10679: // <![CDATA[
1.1045    www      10680: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10681: // ]]>
                   10682: </script>
                   10683: ENDCLOSE
1.1044    www      10684: }
                   10685: 
                   10686: sub r_print {
                   10687:     my ($r,$to_print)=@_;
                   10688:     if ($r) {
                   10689:       $r->print($to_print);
                   10690:       $r->rflush();
                   10691:     } else {
                   10692:       print($to_print);
                   10693:     }
1.1042    www      10694: }
                   10695: 
1.320     albertel 10696: sub html_encode {
                   10697:     my ($result) = @_;
                   10698: 
1.322     albertel 10699:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10700:     
                   10701:     return $result;
                   10702: }
1.1044    www      10703: 
1.317     albertel 10704: sub js_ready {
                   10705:     my ($result) = @_;
                   10706: 
1.323     albertel 10707:     $result =~ s/[\n\r]/ /xmsg;
                   10708:     $result =~ s/\\/\\\\/xmsg;
                   10709:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10710:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10711:     
                   10712:     return $result;
                   10713: }
                   10714: 
1.315     albertel 10715: sub validate_page {
                   10716:     if (  exists($env{'internal.start_page'})
1.316     albertel 10717: 	  &&     $env{'internal.start_page'} > 1) {
                   10718: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10719: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10720: 				 $ENV{'request.filename'});
1.315     albertel 10721:     }
                   10722:     if (  exists($env{'internal.end_page'})
1.316     albertel 10723: 	  &&     $env{'internal.end_page'} > 1) {
                   10724: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10725: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10726: 				 $env{'request.filename'});
1.315     albertel 10727:     }
                   10728:     if (     exists($env{'internal.start_page'})
                   10729: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10730: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10731: 				 $env{'request.filename'});
1.315     albertel 10732:     }
                   10733:     if (   ! exists($env{'internal.start_page'})
                   10734: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10735: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10736: 				 $env{'request.filename'});
1.315     albertel 10737:     }
1.306     albertel 10738: }
1.315     albertel 10739: 
1.996     www      10740: 
                   10741: sub start_scrollbox {
1.1140    raeburn  10742:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10743:     unless ($outerwidth) { $outerwidth='520px'; }
                   10744:     unless ($width) { $width='500px'; }
                   10745:     unless ($height) { $height='200px'; }
1.1075    raeburn  10746:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10747:     if ($id ne '') {
1.1140    raeburn  10748:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10749:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10750:     }
1.1075    raeburn  10751:     if ($bgcolor ne '') {
                   10752:         $tdcol = "background-color: $bgcolor;";
                   10753:     }
1.1137    raeburn  10754:     my $nicescroll_js;
                   10755:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10756:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10757:     }
                   10758:     return <<"END";
                   10759: $nicescroll_js
                   10760: 
                   10761: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10762: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10763: END
                   10764: }
                   10765: 
                   10766: sub end_scrollbox {
                   10767:     return '</div></td></tr></table>';
                   10768: }
                   10769: 
                   10770: sub nicescroll_javascript {
                   10771:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10772:     my %options;
                   10773:     if (ref($cursor) eq 'HASH') {
                   10774:         %options = %{$cursor};
                   10775:     }
                   10776:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10777:         $options{'railalign'} = 'left';
                   10778:     }
                   10779:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10780:         my $function  = &get_users_function();
                   10781:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10782:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10783:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10784:         }
1.1140    raeburn  10785:     }
                   10786:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10787:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10788:             $options{'cursoropacity'}='1.0';
                   10789:         }
1.1140    raeburn  10790:     } else {
                   10791:         $options{'cursoropacity'}='1.0';
                   10792:     }
                   10793:     if ($options{'cursorfixedheight'} eq 'none') {
                   10794:         delete($options{'cursorfixedheight'});
                   10795:     } else {
                   10796:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10797:     }
                   10798:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10799:         delete($options{'railoffset'});
                   10800:     }
                   10801:     my @niceoptions;
                   10802:     while (my($key,$value) = each(%options)) {
                   10803:         if ($value =~ /^\{.+\}$/) {
                   10804:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10805:         } else {
1.1140    raeburn  10806:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10807:         }
1.1140    raeburn  10808:     }
                   10809:     my $nicescroll_js = '
1.1137    raeburn  10810: $(document).ready(
1.1140    raeburn  10811:       function() {
                   10812:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10813:       }
1.1137    raeburn  10814: );
                   10815: ';
1.1140    raeburn  10816:     if ($framecheck) {
                   10817:         $nicescroll_js .= '
                   10818: function expand_div(caller) {
                   10819:     if (top === self) {
                   10820:         document.getElementById("'.$id.'").style.width = "auto";
                   10821:         document.getElementById("'.$id.'").style.height = "auto";
                   10822:     } else {
                   10823:         try {
                   10824:             if (parent.frames) {
                   10825:                 if (parent.frames.length > 1) {
                   10826:                     var framesrc = parent.frames[1].location.href;
                   10827:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10828:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10829:                         document.getElementById("'.$id.'").style.width = "auto";
                   10830:                         document.getElementById("'.$id.'").style.height = "auto";
                   10831:                     }
                   10832:                 }
                   10833:             }
                   10834:         } catch (e) {
                   10835:             return;
                   10836:         }
1.1137    raeburn  10837:     }
1.1140    raeburn  10838:     return;
1.996     www      10839: }
1.1140    raeburn  10840: ';
                   10841:     }
                   10842:     if ($needjsready) {
                   10843:         $nicescroll_js = '
                   10844: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10845:     } else {
                   10846:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10847:     }
                   10848:     return $nicescroll_js;
1.996     www      10849: }
                   10850: 
1.318     albertel 10851: sub simple_error_page {
1.1150    bisitz   10852:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10853:     my %displayargs;
1.1151    raeburn  10854:     if (ref($args) eq 'HASH') {
                   10855:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10856:         if ($args->{'only_body'}) {
                   10857:             $displayargs{'only_body'} = 1;
                   10858:         }
                   10859:         if ($args->{'no_nav_bar'}) {
                   10860:             $displayargs{'no_nav_bar'} = 1;
                   10861:         }
1.1151    raeburn  10862:     } else {
                   10863:         $msg = &mt($msg);
                   10864:     }
1.1150    bisitz   10865: 
1.318     albertel 10866:     my $page =
1.1459    raeburn  10867: 	&Apache::loncommon::start_page($title,'',\%displayargs)."\n".
1.1460    raeburn  10868:         '<div class="LC_landmark" style="clear:both" role="main">'.
1.1150    bisitz   10869: 	'<p class="LC_error">'.$msg.'</p>'.
1.1459    raeburn  10870:         '</div>'.
1.318     albertel 10871: 	&Apache::loncommon::end_page();
                   10872:     if (ref($r)) {
                   10873: 	$r->print($page);
1.327     albertel 10874: 	return;
1.318     albertel 10875:     }
                   10876:     return $page;
                   10877: }
1.347     albertel 10878: 
                   10879: {
1.610     albertel 10880:     my @row_count;
1.961     onken    10881: 
                   10882:     sub start_data_table_count {
                   10883:         unshift(@row_count, 0);
                   10884:         return;
                   10885:     }
                   10886: 
                   10887:     sub end_data_table_count {
                   10888:         shift(@row_count);
                   10889:         return;
                   10890:     }
                   10891: 
1.347     albertel 10892:     sub start_data_table {
1.1018    raeburn  10893: 	my ($add_class,$id) = @_;
1.422     albertel 10894: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10895:         my $table_id;
                   10896:         if (defined($id)) {
                   10897:             $table_id = ' id="'.$id.'"';
                   10898:         }
1.961     onken    10899: 	&start_data_table_count();
1.1018    raeburn  10900: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10901:     }
                   10902: 
                   10903:     sub end_data_table {
1.961     onken    10904: 	&end_data_table_count();
1.389     albertel 10905: 	return '</table>'."\n";;
1.347     albertel 10906:     }
                   10907: 
                   10908:     sub start_data_table_row {
1.974     wenzelju 10909: 	my ($add_class, $id) = @_;
1.610     albertel 10910: 	$row_count[0]++;
                   10911: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10912: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10913:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10914:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10915:     }
1.471     banghart 10916:     
                   10917:     sub continue_data_table_row {
1.974     wenzelju 10918: 	my ($add_class, $id) = @_;
1.610     albertel 10919: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10920: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10921:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10922:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10923:     }
1.347     albertel 10924: 
                   10925:     sub end_data_table_row {
1.389     albertel 10926: 	return '</tr>'."\n";;
1.347     albertel 10927:     }
1.367     www      10928: 
1.421     albertel 10929:     sub start_data_table_empty_row {
1.707     bisitz   10930: #	$row_count[0]++;
1.421     albertel 10931: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10932:     }
                   10933: 
                   10934:     sub end_data_table_empty_row {
                   10935: 	return '</tr>'."\n";;
                   10936:     }
                   10937: 
1.367     www      10938:     sub start_data_table_header_row {
1.1465  ! raeburn  10939: 	my ($add_class,$id) = @_;
        !          10940: 	my $css_class = 'LC_header_row';
        !          10941: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
        !          10942: 	$id = (' id="'.$id.'"') unless ($id eq '');
        !          10943: 	return '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.367     www      10944:     }
                   10945: 
                   10946:     sub end_data_table_header_row {
1.389     albertel 10947: 	return '</tr>'."\n";;
1.367     www      10948:     }
1.890     droeschl 10949: 
                   10950:     sub data_table_caption {
                   10951:         my $caption = shift;
                   10952:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10953:     }
1.347     albertel 10954: }
                   10955: 
1.548     albertel 10956: =pod
                   10957: 
                   10958: =item * &inhibit_menu_check($arg)
                   10959: 
                   10960: Checks for a inhibitmenu state and generates output to preserve it
                   10961: 
                   10962: Inputs:         $arg - can be any of
                   10963:                      - undef - in which case the return value is a string 
                   10964:                                to add  into arguments list of a uri
                   10965:                      - 'input' - in which case the return value is a HTML
                   10966:                                  <form> <input> field of type hidden to
                   10967:                                  preserve the value
                   10968:                      - a url - in which case the return value is the url with
                   10969:                                the neccesary cgi args added to preserve the
                   10970:                                inhibitmenu state
                   10971:                      - a ref to a url - no return value, but the string is
                   10972:                                         updated to include the neccessary cgi
                   10973:                                         args to preserve the inhibitmenu state
                   10974: 
                   10975: =cut
                   10976: 
                   10977: sub inhibit_menu_check {
                   10978:     my ($arg) = @_;
                   10979:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10980:     if ($arg eq 'input') {
                   10981: 	if ($env{'form.inhibitmenu'}) {
                   10982: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10983: 	} else {
                   10984: 	    return
                   10985: 	}
                   10986:     }
                   10987:     if ($env{'form.inhibitmenu'}) {
                   10988: 	if (ref($arg)) {
                   10989: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10990: 	} elsif ($arg eq '') {
                   10991: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10992: 	} else {
                   10993: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10994: 	}
                   10995:     }
                   10996:     if (!ref($arg)) {
                   10997: 	return $arg;
                   10998:     }
                   10999: }
                   11000: 
1.251     albertel 11001: ###############################################
1.182     matthew  11002: 
                   11003: =pod
                   11004: 
1.549     albertel 11005: =back
                   11006: 
                   11007: =head1 User Information Routines
                   11008: 
                   11009: =over 4
                   11010: 
1.405     albertel 11011: =item * &get_users_function()
1.182     matthew  11012: 
                   11013: Used by &bodytag to determine the current users primary role.
                   11014: Returns either 'student','coordinator','admin', or 'author'.
                   11015: 
                   11016: =cut
                   11017: 
                   11018: ###############################################
                   11019: sub get_users_function {
1.815     tempelho 11020:     my $function = 'norole';
1.818     tempelho 11021:     if ($env{'request.role'}=~/^(st)/) {
                   11022:         $function='student';
                   11023:     }
1.907     raeburn  11024:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  11025:         $function='coordinator';
                   11026:     }
1.258     albertel 11027:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  11028:         $function='admin';
                   11029:     }
1.826     bisitz   11030:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  11031:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  11032:         $function='author';
                   11033:     }
                   11034:     return $function;
1.54      www      11035: }
1.99      www      11036: 
                   11037: ###############################################
                   11038: 
1.233     raeburn  11039: =pod
                   11040: 
1.821     raeburn  11041: =item * &show_course()
                   11042: 
                   11043: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   11044: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   11045: 
                   11046: Inputs:
                   11047: None
                   11048: 
                   11049: Outputs:
                   11050: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   11051: 
                   11052: =cut
                   11053: 
                   11054: ###############################################
                   11055: sub show_course {
1.1408    raeburn  11056:     my ($udom,$uname) = @_;
                   11057:     if (($udom ne '') && ($uname ne '')) {
                   11058:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
1.1410    raeburn  11059:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
1.1408    raeburn  11060:                 return 0;
                   11061:             } else {
                   11062:                 return 1;
                   11063:             }
                   11064:         }
                   11065:     }
1.821     raeburn  11066:     my $course = !$env{'user.adv'};
                   11067:     if (!$env{'user.adv'}) {
                   11068:         foreach my $env (keys(%env)) {
                   11069:             next if ($env !~ m/^user\.priv\./);
                   11070:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   11071:                 $course = 0;
                   11072:                 last;
                   11073:             }
                   11074:         }
                   11075:     }
                   11076:     return $course;
                   11077: }
                   11078: 
                   11079: ###############################################
                   11080: 
                   11081: =pod
                   11082: 
1.542     raeburn  11083: =item * &check_user_status()
1.274     raeburn  11084: 
                   11085: Determines current status of supplied role for a
                   11086: specific user. Roles can be active, previous or future.
                   11087: 
                   11088: Inputs: 
                   11089: user's domain, user's username, course's domain,
1.375     raeburn  11090: course's number, optional section ID.
1.274     raeburn  11091: 
                   11092: Outputs:
                   11093: role status: active, previous or future. 
                   11094: 
                   11095: =cut
                   11096: 
                   11097: sub check_user_status {
1.412     raeburn  11098:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  11099:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  11100:     my @uroles = keys(%userinfo);
1.274     raeburn  11101:     my $srchstr;
                   11102:     my $active_chk = 'none';
1.412     raeburn  11103:     my $now = time;
1.274     raeburn  11104:     if (@uroles > 0) {
1.908     raeburn  11105:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  11106:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   11107:         } else {
1.412     raeburn  11108:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   11109:         }
                   11110:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  11111:             my $role_end = 0;
                   11112:             my $role_start = 0;
                   11113:             $active_chk = 'active';
1.412     raeburn  11114:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   11115:                 $role_end = $1;
                   11116:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   11117:                     $role_start = $1;
1.274     raeburn  11118:                 }
                   11119:             }
                   11120:             if ($role_start > 0) {
1.412     raeburn  11121:                 if ($now < $role_start) {
1.274     raeburn  11122:                     $active_chk = 'future';
                   11123:                 }
                   11124:             }
                   11125:             if ($role_end > 0) {
1.412     raeburn  11126:                 if ($now > $role_end) {
1.274     raeburn  11127:                     $active_chk = 'previous';
                   11128:                 }
                   11129:             }
                   11130:         }
                   11131:     }
                   11132:     return $active_chk;
                   11133: }
                   11134: 
                   11135: ###############################################
                   11136: 
                   11137: =pod
                   11138: 
1.405     albertel 11139: =item * &get_sections()
1.233     raeburn  11140: 
                   11141: Determines all the sections for a course including
                   11142: sections with students and sections containing other roles.
1.419     raeburn  11143: Incoming parameters: 
                   11144: 
                   11145: 1. domain
                   11146: 2. course number 
                   11147: 3. reference to array containing roles for which sections should 
                   11148: be gathered (optional).
                   11149: 4. reference to array containing status types for which sections 
                   11150: should be gathered (optional).
                   11151: 
                   11152: If the third argument is undefined, sections are gathered for any role. 
                   11153: If the fourth argument is undefined, sections are gathered for any status.
                   11154: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  11155:  
1.374     raeburn  11156: Returns section hash (keys are section IDs, values are
                   11157: number of users in each section), subject to the
1.419     raeburn  11158: optional roles filter, optional status filter 
1.233     raeburn  11159: 
                   11160: =cut
                   11161: 
                   11162: ###############################################
                   11163: sub get_sections {
1.419     raeburn  11164:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 11165:     if (!defined($cdom) || !defined($cnum)) {
                   11166:         my $cid =  $env{'request.course.id'};
                   11167: 
                   11168: 	return if (!defined($cid));
                   11169: 
                   11170:         $cdom = $env{'course.'.$cid.'.domain'};
                   11171:         $cnum = $env{'course.'.$cid.'.num'};
                   11172:     }
                   11173: 
                   11174:     my %sectioncount;
1.419     raeburn  11175:     my $now = time;
1.240     albertel 11176: 
1.1118    raeburn  11177:     my $check_students = 1;
                   11178:     my $only_students = 0;
                   11179:     if (ref($possible_roles) eq 'ARRAY') {
                   11180:         if (grep(/^st$/,@{$possible_roles})) {
                   11181:             if (@{$possible_roles} == 1) {
                   11182:                 $only_students = 1;
                   11183:             }
                   11184:         } else {
                   11185:             $check_students = 0;
                   11186:         }
                   11187:     }
                   11188: 
                   11189:     if ($check_students) { 
1.276     albertel 11190: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 11191: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   11192: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  11193:         my $start_index = &Apache::loncoursedata::CL_START();
                   11194:         my $end_index = &Apache::loncoursedata::CL_END();
                   11195:         my $status;
1.366     albertel 11196: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  11197: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   11198: 				                     $data->[$status_index],
                   11199:                                                      $data->[$start_index],
                   11200:                                                      $data->[$end_index]);
                   11201:             if ($stu_status eq 'Active') {
                   11202:                 $status = 'active';
                   11203:             } elsif ($end < $now) {
                   11204:                 $status = 'previous';
                   11205:             } elsif ($start > $now) {
                   11206:                 $status = 'future';
                   11207:             } 
                   11208: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   11209:                 if ((!defined($possible_status)) || (($status ne '') && 
                   11210:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   11211: 		    $sectioncount{$section}++;
                   11212:                 }
1.240     albertel 11213: 	    }
                   11214: 	}
                   11215:     }
1.1118    raeburn  11216:     if ($only_students) {
                   11217:         return %sectioncount;
                   11218:     }
1.240     albertel 11219:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11220:     foreach my $user (sort(keys(%courseroles))) {
                   11221: 	if ($user !~ /^(\w{2})/) { next; }
                   11222: 	my ($role) = ($user =~ /^(\w{2})/);
                   11223: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  11224: 	my ($section,$status);
1.240     albertel 11225: 	if ($role eq 'cr' &&
                   11226: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   11227: 	    $section=$1;
                   11228: 	}
                   11229: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   11230: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  11231:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   11232:         if ($end == -1 && $start == -1) {
                   11233:             next; #deleted role
                   11234:         }
                   11235:         if (!defined($possible_status)) { 
                   11236:             $sectioncount{$section}++;
                   11237:         } else {
                   11238:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   11239:                 $status = 'active';
                   11240:             } elsif ($end < $now) {
                   11241:                 $status = 'future';
                   11242:             } elsif ($start > $now) {
                   11243:                 $status = 'previous';
                   11244:             }
                   11245:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   11246:                 $sectioncount{$section}++;
                   11247:             }
                   11248:         }
1.233     raeburn  11249:     }
1.366     albertel 11250:     return %sectioncount;
1.233     raeburn  11251: }
                   11252: 
1.274     raeburn  11253: ###############################################
1.294     raeburn  11254: 
                   11255: =pod
1.405     albertel 11256: 
                   11257: =item * &get_course_users()
                   11258: 
1.275     raeburn  11259: Retrieves usernames:domains for users in the specified course
                   11260: with specific role(s), and access status. 
                   11261: 
                   11262: Incoming parameters:
1.277     albertel 11263: 1. course domain
                   11264: 2. course number
                   11265: 3. access status: users must have - either active, 
1.275     raeburn  11266: previous, future, or all.
1.277     albertel 11267: 4. reference to array of permissible roles
1.288     raeburn  11268: 5. reference to array of section restrictions (optional)
                   11269: 6. reference to results object (hash of hashes).
                   11270: 7. reference to optional userdata hash
1.609     raeburn  11271: 8. reference to optional statushash
1.630     raeburn  11272: 9. flag if privileged users (except those set to unhide in
                   11273:    course settings) should be excluded    
1.609     raeburn  11274: Keys of top level results hash are roles.
1.275     raeburn  11275: Keys of inner hashes are username:domain, with 
                   11276: values set to access type.
1.288     raeburn  11277: Optional userdata hash returns an array with arguments in the 
                   11278: same order as loncoursedata::get_classlist() for student data.
                   11279: 
1.609     raeburn  11280: Optional statushash returns
                   11281: 
1.288     raeburn  11282: Entries for end, start, section and status are blank because
                   11283: of the possibility of multiple values for non-student roles.
                   11284: 
1.275     raeburn  11285: =cut
1.405     albertel 11286: 
1.275     raeburn  11287: ###############################################
1.405     albertel 11288: 
1.275     raeburn  11289: sub get_course_users {
1.630     raeburn  11290:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  11291:     my %idx = ();
1.419     raeburn  11292:     my %seclists;
1.288     raeburn  11293: 
                   11294:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   11295:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   11296:     $idx{end} = &Apache::loncoursedata::CL_END();
                   11297:     $idx{start} = &Apache::loncoursedata::CL_START();
                   11298:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   11299:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   11300:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   11301:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   11302: 
1.290     albertel 11303:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 11304:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  11305:         my $now = time;
1.277     albertel 11306:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  11307:             my $match = 0;
1.412     raeburn  11308:             my $secmatch = 0;
1.419     raeburn  11309:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  11310:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  11311:             if ($section eq '') {
                   11312:                 $section = 'none';
                   11313:             }
1.291     albertel 11314:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11315:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11316:                     $secmatch = 1;
                   11317:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 11318:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11319:                         $secmatch = 1;
                   11320:                     }
                   11321:                 } else {  
1.419     raeburn  11322: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  11323: 		        $secmatch = 1;
                   11324:                     }
1.290     albertel 11325: 		}
1.412     raeburn  11326:                 if (!$secmatch) {
                   11327:                     next;
                   11328:                 }
1.419     raeburn  11329:             }
1.275     raeburn  11330:             if (defined($$types{'active'})) {
1.288     raeburn  11331:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  11332:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  11333:                     $match = 1;
1.275     raeburn  11334:                 }
                   11335:             }
                   11336:             if (defined($$types{'previous'})) {
1.609     raeburn  11337:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  11338:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  11339:                     $match = 1;
1.275     raeburn  11340:                 }
                   11341:             }
                   11342:             if (defined($$types{'future'})) {
1.609     raeburn  11343:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  11344:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  11345:                     $match = 1;
1.275     raeburn  11346:                 }
                   11347:             }
1.609     raeburn  11348:             if ($match) {
                   11349:                 push(@{$seclists{$student}},$section);
                   11350:                 if (ref($userdata) eq 'HASH') {
                   11351:                     $$userdata{$student} = $$classlist{$student};
                   11352:                 }
                   11353:                 if (ref($statushash) eq 'HASH') {
                   11354:                     $statushash->{$student}{'st'}{$section} = $status;
                   11355:                 }
1.288     raeburn  11356:             }
1.275     raeburn  11357:         }
                   11358:     }
1.412     raeburn  11359:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  11360:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11361:         my $now = time;
1.609     raeburn  11362:         my %displaystatus = ( previous => 'Expired',
                   11363:                               active   => 'Active',
                   11364:                               future   => 'Future',
                   11365:                             );
1.1121    raeburn  11366:         my (%nothide,@possdoms);
1.630     raeburn  11367:         if ($hidepriv) {
                   11368:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   11369:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   11370:                 if ($user !~ /:/) {
                   11371:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   11372:                 } else {
                   11373:                     $nothide{$user} = 1;
                   11374:                 }
                   11375:             }
1.1121    raeburn  11376:             my @possdoms = ($cdom);
                   11377:             if ($coursehash{'checkforpriv'}) {
                   11378:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   11379:             }
1.630     raeburn  11380:         }
1.439     raeburn  11381:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  11382:             my $match = 0;
1.412     raeburn  11383:             my $secmatch = 0;
1.439     raeburn  11384:             my $status;
1.412     raeburn  11385:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  11386:             $user =~ s/:$//;
1.439     raeburn  11387:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   11388:             if ($end == -1 || $start == -1) {
                   11389:                 next;
                   11390:             }
                   11391:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   11392:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  11393:                 my ($uname,$udom) = split(/:/,$user);
                   11394:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11395:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11396:                         $secmatch = 1;
                   11397:                     } elsif ($usec eq '') {
1.420     albertel 11398:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11399:                             $secmatch = 1;
                   11400:                         }
                   11401:                     } else {
                   11402:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   11403:                             $secmatch = 1;
                   11404:                         }
                   11405:                     }
                   11406:                     if (!$secmatch) {
                   11407:                         next;
                   11408:                     }
1.288     raeburn  11409:                 }
1.419     raeburn  11410:                 if ($usec eq '') {
                   11411:                     $usec = 'none';
                   11412:                 }
1.275     raeburn  11413:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  11414:                     if ($hidepriv) {
1.1121    raeburn  11415:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  11416:                             (!$nothide{$uname.':'.$udom})) {
                   11417:                             next;
                   11418:                         }
                   11419:                     }
1.503     raeburn  11420:                     if ($end > 0 && $end < $now) {
1.439     raeburn  11421:                         $status = 'previous';
                   11422:                     } elsif ($start > $now) {
                   11423:                         $status = 'future';
                   11424:                     } else {
                   11425:                         $status = 'active';
                   11426:                     }
1.277     albertel 11427:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  11428:                         if ($status eq $type) {
1.420     albertel 11429:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  11430:                                 push(@{$$users{$role}{$user}},$type);
                   11431:                             }
1.288     raeburn  11432:                             $match = 1;
                   11433:                         }
                   11434:                     }
1.419     raeburn  11435:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   11436:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   11437: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   11438:                         }
1.420     albertel 11439:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  11440:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   11441:                         }
1.609     raeburn  11442:                         if (ref($statushash) eq 'HASH') {
                   11443:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   11444:                         }
1.275     raeburn  11445:                     }
                   11446:                 }
                   11447:             }
                   11448:         }
1.290     albertel 11449:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  11450:             if ((defined($cdom)) && (defined($cnum))) {
                   11451:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   11452:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   11453:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  11454:                     next if ($owner eq '');
                   11455:                     my ($ownername,$ownerdom);
                   11456:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   11457:                         $ownername = $1;
                   11458:                         $ownerdom = $2;
                   11459:                     } else {
                   11460:                         $ownername = $owner;
                   11461:                         $ownerdom = $cdom;
                   11462:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  11463:                     }
                   11464:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 11465:                     if (defined($userdata) && 
1.609     raeburn  11466: 			!exists($$userdata{$owner})) {
                   11467: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   11468:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   11469:                             push(@{$seclists{$owner}},'none');
                   11470:                         }
                   11471:                         if (ref($statushash) eq 'HASH') {
                   11472:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  11473:                         }
1.290     albertel 11474: 		    }
1.279     raeburn  11475:                 }
                   11476:             }
                   11477:         }
1.419     raeburn  11478:         foreach my $user (keys(%seclists)) {
                   11479:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   11480:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   11481:         }
1.275     raeburn  11482:     }
                   11483:     return;
                   11484: }
                   11485: 
1.288     raeburn  11486: sub get_user_info {
                   11487:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 11488:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   11489: 	&plainname($uname,$udom,'lastname');
1.291     albertel 11490:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  11491:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  11492:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   11493:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  11494:     return;
                   11495: }
1.275     raeburn  11496: 
1.472     raeburn  11497: ###############################################
                   11498: 
                   11499: =pod
                   11500: 
                   11501: =item * &get_user_quota()
                   11502: 
1.1134    raeburn  11503: Retrieves quota assigned for storage of user files.
                   11504: Default is to report quota for portfolio files.
1.472     raeburn  11505: 
                   11506: Incoming parameters:
                   11507: 1. user's username
                   11508: 2. user's domain
1.1134    raeburn  11509: 3. quota name - portfolio, author, or course
1.1136    raeburn  11510:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  11511: 4. crstype - official, unofficial, textbook, placement or community, 
                   11512:    if quota name is course
1.472     raeburn  11513: 
                   11514: Returns:
1.1163    raeburn  11515: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  11516: 2. (Optional) Type of setting: custom or default
                   11517:    (individually assigned or default for user's 
                   11518:    institutional status).
                   11519: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   11520:    or student - types as defined in localenroll::inst_usertypes 
                   11521:    for user's domain, which determines default quota for user.
                   11522: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  11523: 
                   11524: If a value has been stored in the user's environment, 
1.536     raeburn  11525: it will return that, otherwise it returns the maximal default
1.1134    raeburn  11526: defined for the user's institutional status(es) in the domain.
1.472     raeburn  11527: 
                   11528: =cut
                   11529: 
                   11530: ###############################################
                   11531: 
                   11532: 
                   11533: sub get_user_quota {
1.1136    raeburn  11534:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  11535:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  11536:     if (!defined($udom)) {
                   11537:         $udom = $env{'user.domain'};
                   11538:     }
                   11539:     if (!defined($uname)) {
                   11540:         $uname = $env{'user.name'};
                   11541:     }
                   11542:     if (($udom eq '' || $uname eq '') ||
                   11543:         ($udom eq 'public') && ($uname eq 'public')) {
                   11544:         $quota = 0;
1.536     raeburn  11545:         $quotatype = 'default';
                   11546:         $defquota = 0; 
1.472     raeburn  11547:     } else {
1.536     raeburn  11548:         my $inststatus;
1.1134    raeburn  11549:         if ($quotaname eq 'course') {
                   11550:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   11551:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   11552:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   11553:             } else {
                   11554:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   11555:                 $quota = $cenv{'internal.uploadquota'};
                   11556:             }
1.536     raeburn  11557:         } else {
1.1134    raeburn  11558:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   11559:                 if ($quotaname eq 'author') {
                   11560:                     $quota = $env{'environment.authorquota'};
                   11561:                 } else {
                   11562:                     $quota = $env{'environment.portfolioquota'};
                   11563:                 }
                   11564:                 $inststatus = $env{'environment.inststatus'};
                   11565:             } else {
                   11566:                 my %userenv = 
                   11567:                     &Apache::lonnet::get('environment',['portfolioquota',
                   11568:                                          'authorquota','inststatus'],$udom,$uname);
                   11569:                 my ($tmp) = keys(%userenv);
                   11570:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   11571:                     if ($quotaname eq 'author') {
                   11572:                         $quota = $userenv{'authorquota'};
                   11573:                     } else {
                   11574:                         $quota = $userenv{'portfolioquota'};
                   11575:                     }
                   11576:                     $inststatus = $userenv{'inststatus'};
                   11577:                 } else {
                   11578:                     undef(%userenv);
                   11579:                 }
                   11580:             }
                   11581:         }
                   11582:         if ($quota eq '' || wantarray) {
                   11583:             if ($quotaname eq 'course') {
                   11584:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  11585:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  11586:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   11587:                     ($crstype eq 'placement')) { 
1.1136    raeburn  11588:                     $defquota = $domdefs{$crstype.'quota'};
                   11589:                 }
                   11590:                 if ($defquota eq '') {
                   11591:                     $defquota = 500;
                   11592:                 }
1.1134    raeburn  11593:             } else {
                   11594:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   11595:             }
                   11596:             if ($quota eq '') {
                   11597:                 $quota = $defquota;
                   11598:                 $quotatype = 'default';
                   11599:             } else {
                   11600:                 $quotatype = 'custom';
                   11601:             }
1.472     raeburn  11602:         }
                   11603:     }
1.536     raeburn  11604:     if (wantarray) {
                   11605:         return ($quota,$quotatype,$settingstatus,$defquota);
                   11606:     } else {
                   11607:         return $quota;
                   11608:     }
1.472     raeburn  11609: }
                   11610: 
                   11611: ###############################################
                   11612: 
                   11613: =pod
                   11614: 
                   11615: =item * &default_quota()
                   11616: 
1.536     raeburn  11617: Retrieves default quota assigned for storage of user portfolio files,
                   11618: given an (optional) user's institutional status.
1.472     raeburn  11619: 
                   11620: Incoming parameters:
1.1142    raeburn  11621: 
1.472     raeburn  11622: 1. domain
1.536     raeburn  11623: 2. (Optional) institutional status(es).  This is a : separated list of 
                   11624:    status types (e.g., faculty, staff, student etc.)
                   11625:    which apply to the user for whom the default is being retrieved.
                   11626:    If the institutional status string in undefined, the domain
1.1134    raeburn  11627:    default quota will be returned.
                   11628: 3.  quota name - portfolio, author, or course
                   11629:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  11630: 
                   11631: Returns:
1.1142    raeburn  11632: 
1.1163    raeburn  11633: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  11634: 2. (Optional) institutional type which determined the value of the
                   11635:    default quota.
1.472     raeburn  11636: 
                   11637: If a value has been stored in the domain's configuration db,
                   11638: it will return that, otherwise it returns 20 (for backwards 
                   11639: compatibility with domains which have not set up a configuration
1.1163    raeburn  11640: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  11641: 
1.536     raeburn  11642: If the user's status includes multiple types (e.g., staff and student),
                   11643: the largest default quota which applies to the user determines the
                   11644: default quota returned.
                   11645: 
1.472     raeburn  11646: =cut
                   11647: 
                   11648: ###############################################
                   11649: 
                   11650: 
                   11651: sub default_quota {
1.1134    raeburn  11652:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  11653:     my ($defquota,$settingstatus);
                   11654:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  11655:                                             ['quotas'],$udom);
1.1134    raeburn  11656:     my $key = 'defaultquota';
                   11657:     if ($quotaname eq 'author') {
                   11658:         $key = 'authorquota';
                   11659:     }
1.622     raeburn  11660:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  11661:         if ($inststatus ne '') {
1.765     raeburn  11662:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  11663:             foreach my $item (@statuses) {
1.1134    raeburn  11664:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11665:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  11666:                         if ($defquota eq '') {
1.1134    raeburn  11667:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11668:                             $settingstatus = $item;
1.1134    raeburn  11669:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11670:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11671:                             $settingstatus = $item;
                   11672:                         }
                   11673:                     }
1.1134    raeburn  11674:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11675:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11676:                         if ($defquota eq '') {
                   11677:                             $defquota = $quotahash{'quotas'}{$item};
                   11678:                             $settingstatus = $item;
                   11679:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11680:                             $defquota = $quotahash{'quotas'}{$item};
                   11681:                             $settingstatus = $item;
                   11682:                         }
1.536     raeburn  11683:                     }
                   11684:                 }
                   11685:             }
                   11686:         }
                   11687:         if ($defquota eq '') {
1.1134    raeburn  11688:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11689:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11690:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11691:                 $defquota = $quotahash{'quotas'}{'default'};
                   11692:             }
1.536     raeburn  11693:             $settingstatus = 'default';
1.1139    raeburn  11694:             if ($defquota eq '') {
                   11695:                 if ($quotaname eq 'author') {
                   11696:                     $defquota = 500;
                   11697:                 }
                   11698:             }
1.536     raeburn  11699:         }
                   11700:     } else {
                   11701:         $settingstatus = 'default';
1.1134    raeburn  11702:         if ($quotaname eq 'author') {
                   11703:             $defquota = 500;
                   11704:         } else {
                   11705:             $defquota = 20;
                   11706:         }
1.536     raeburn  11707:     }
                   11708:     if (wantarray) {
                   11709:         return ($defquota,$settingstatus);
1.472     raeburn  11710:     } else {
1.536     raeburn  11711:         return $defquota;
1.472     raeburn  11712:     }
                   11713: }
                   11714: 
1.1135    raeburn  11715: ###############################################
                   11716: 
                   11717: =pod
                   11718: 
1.1136    raeburn  11719: =item * &excess_filesize_warning()
1.1135    raeburn  11720: 
                   11721: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  11722: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  11723: space to be exceeded.
1.1136    raeburn  11724: 
                   11725: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  11726: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  11727: 
1.1165    raeburn  11728: Inputs: 7 
1.1136    raeburn  11729: 1. username or coursenum
1.1135    raeburn  11730: 2. domain
1.1136    raeburn  11731: 3. context ('author' or 'course')
1.1135    raeburn  11732: 4. filename of file for which action is being requested
                   11733: 5. filesize (kB) of file
                   11734: 6. action being taken: copy or upload.
1.1237    raeburn  11735: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  11736: 
                   11737: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  11738:          otherwise return null.
                   11739: 
                   11740: =back
1.1135    raeburn  11741: 
                   11742: =cut
                   11743: 
1.1136    raeburn  11744: sub excess_filesize_warning {
1.1165    raeburn  11745:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  11746:     my $current_disk_usage = 0;
1.1165    raeburn  11747:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  11748:     if ($context eq 'author') {
                   11749:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11750:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11751:     } else {
                   11752:         foreach my $subdir ('docs','supplemental') {
                   11753:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11754:         }
                   11755:     }
1.1135    raeburn  11756:     $disk_quota = int($disk_quota * 1000);
                   11757:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11758:         return '<p class="LC_warning">'.
1.1135    raeburn  11759:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11760:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11761:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11762:                             $disk_quota,$current_disk_usage).
                   11763:                '</p>';
                   11764:     }
                   11765:     return;
                   11766: }
                   11767: 
                   11768: ###############################################
                   11769: 
                   11770: 
1.1136    raeburn  11771: 
                   11772: 
1.384     raeburn  11773: sub get_secgrprole_info {
                   11774:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11775:     my %sections_count = &get_sections($cdom,$cnum);
                   11776:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11777:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11778:     my @groups = sort(keys(%curr_groups));
                   11779:     my $allroles = [];
                   11780:     my $rolehash;
                   11781:     my $accesshash = {
                   11782:                      active => 'Currently has access',
                   11783:                      future => 'Will have future access',
                   11784:                      previous => 'Previously had access',
                   11785:                   };
                   11786:     if ($needroles) {
                   11787:         $rolehash = {'all' => 'all'};
1.385     albertel 11788:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11789: 	if (&Apache::lonnet::error(%user_roles)) {
                   11790: 	    undef(%user_roles);
                   11791: 	}
                   11792:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11793:             my ($role)=split(/\:/,$item,2);
                   11794:             if ($role eq 'cr') { next; }
                   11795:             if ($role =~ /^cr/) {
                   11796:                 $$rolehash{$role} = (split('/',$role))[3];
                   11797:             } else {
                   11798:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11799:             }
                   11800:         }
                   11801:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11802:             push(@{$allroles},$key);
                   11803:         }
                   11804:         push (@{$allroles},'st');
                   11805:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11806:     }
                   11807:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11808: }
                   11809: 
1.555     raeburn  11810: sub user_picker {
1.1279    raeburn  11811:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11812:     my $currdom = $dom;
1.1253    raeburn  11813:     my @alldoms = &Apache::lonnet::all_domains();
                   11814:     if (@alldoms == 1) {
                   11815:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11816:                                                ['directorysrch'],$alldoms[0]);
                   11817:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11818:         my $showdom = $domdesc;
                   11819:         if ($showdom eq '') {
                   11820:             $showdom = $dom;
                   11821:         }
                   11822:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11823:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11824:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11825:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11826:             }
                   11827:         }
                   11828:     }
1.555     raeburn  11829:     my %curr_selected = (
                   11830:                         srchin => 'dom',
1.580     raeburn  11831:                         srchby => 'lastname',
1.555     raeburn  11832:                       );
                   11833:     my $srchterm;
1.625     raeburn  11834:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11835:         if ($srch->{'srchby'} ne '') {
                   11836:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11837:         }
                   11838:         if ($srch->{'srchin'} ne '') {
                   11839:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11840:         }
                   11841:         if ($srch->{'srchtype'} ne '') {
                   11842:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11843:         }
                   11844:         if ($srch->{'srchdomain'} ne '') {
                   11845:             $currdom = $srch->{'srchdomain'};
                   11846:         }
                   11847:         $srchterm = $srch->{'srchterm'};
                   11848:     }
1.1222    damieng  11849:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11850:                     'usr'       => 'Search criteria',
1.563     raeburn  11851:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11852:                     'uname'     => 'username',
                   11853:                     'lastname'  => 'last name',
1.555     raeburn  11854:                     'lastfirst' => 'last name, first name',
1.558     albertel 11855:                     'crs'       => 'in this course',
1.576     raeburn  11856:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11857:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11858:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11859:                     'exact'     => 'is',
                   11860:                     'contains'  => 'contains',
1.569     raeburn  11861:                     'begins'    => 'begins with',
1.1222    damieng  11862:                                        );
                   11863:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11864:                     'youm'      => "You must include some text to search for.",
                   11865:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11866:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11867:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11868:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11869:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11870:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11871:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11872:                                        );
1.1222    damieng  11873:     &html_escape(\%html_lt);
                   11874:     &js_escape(\%js_lt);
1.1255    raeburn  11875:     my $domform;
1.1277    raeburn  11876:     my $allow_blank = 1;
1.1255    raeburn  11877:     if ($fixeddom) {
1.1277    raeburn  11878:         $allow_blank = 0;
                   11879:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11880:     } else {
1.1287    raeburn  11881:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11882:         my ($trusted,$untrusted);
1.1287    raeburn  11883:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11884:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11885:         } elsif ($context eq 'author') {
1.1288    raeburn  11886:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11887:         } elsif ($context eq 'domain') {
1.1288    raeburn  11888:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11889:         }
1.1288    raeburn  11890:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11891:     }
1.563     raeburn  11892:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11893: 
                   11894:     my @srchins = ('crs','dom','alc','instd');
                   11895: 
                   11896:     foreach my $option (@srchins) {
                   11897:         # FIXME 'alc' option unavailable until 
                   11898:         #       loncreateuser::print_user_query_page()
                   11899:         #       has been completed.
                   11900:         next if ($option eq 'alc');
1.880     raeburn  11901:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11902:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11903:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11904:         if ($curr_selected{'srchin'} eq $option) {
                   11905:             $srchinsel .= ' 
1.1222    damieng  11906:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11907:         } else {
                   11908:             $srchinsel .= '
1.1222    damieng  11909:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11910:         }
1.555     raeburn  11911:     }
1.563     raeburn  11912:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11913: 
                   11914:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11915:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11916:         if ($curr_selected{'srchby'} eq $option) {
                   11917:             $srchbysel .= '
1.1222    damieng  11918:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11919:         } else {
                   11920:             $srchbysel .= '
1.1222    damieng  11921:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11922:          }
                   11923:     }
                   11924:     $srchbysel .= "\n  </select>\n";
                   11925: 
                   11926:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11927:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11928:         if ($curr_selected{'srchtype'} eq $option) {
                   11929:             $srchtypesel .= '
1.1222    damieng  11930:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11931:         } else {
                   11932:             $srchtypesel .= '
1.1222    damieng  11933:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11934:         }
                   11935:     }
                   11936:     $srchtypesel .= "\n  </select>\n";
                   11937: 
1.558     albertel 11938:     my ($newuserscript,$new_user_create);
1.994     raeburn  11939:     my $context_dom = $env{'request.role.domain'};
                   11940:     if ($context eq 'requestcrs') {
                   11941:         if ($env{'form.coursedom'} ne '') { 
                   11942:             $context_dom = $env{'form.coursedom'};
                   11943:         }
                   11944:     }
1.556     raeburn  11945:     if ($forcenewuser) {
1.576     raeburn  11946:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11947:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11948:                 if ($cancreate) {
                   11949:                     $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>';
                   11950:                 } else {
1.799     bisitz   11951:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11952:                     my %usertypetext = (
                   11953:                         official   => 'institutional',
                   11954:                         unofficial => 'non-institutional',
                   11955:                     );
1.799     bisitz   11956:                     $new_user_create = '<p class="LC_warning">'
                   11957:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11958:                                       .' '
                   11959:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11960:                                           ,'<a href="'.$helplink.'">','</a>')
                   11961:                                       .'</p><br />';
1.627     raeburn  11962:                 }
1.576     raeburn  11963:             }
                   11964:         }
                   11965: 
1.556     raeburn  11966:         $newuserscript = <<"ENDSCRIPT";
                   11967: 
1.570     raeburn  11968: function setSearch(createnew,callingForm) {
1.556     raeburn  11969:     if (createnew == 1) {
1.570     raeburn  11970:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11971:             if (callingForm.srchby.options[i].value == 'uname') {
                   11972:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11973:             }
                   11974:         }
1.570     raeburn  11975:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11976:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11977: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11978:             }
                   11979:         }
1.570     raeburn  11980:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11981:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11982:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11983:             }
                   11984:         }
1.570     raeburn  11985:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11986:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11987:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11988:             }
                   11989:         }
                   11990:     }
                   11991: }
                   11992: ENDSCRIPT
1.558     albertel 11993: 
1.556     raeburn  11994:     }
                   11995: 
1.555     raeburn  11996:     my $output = <<"END_BLOCK";
1.556     raeburn  11997: <script type="text/javascript">
1.824     bisitz   11998: // <![CDATA[
1.570     raeburn  11999: function validateEntry(callingForm) {
1.558     albertel 12000: 
1.556     raeburn  12001:     var checkok = 1;
1.558     albertel 12002:     var srchin;
1.570     raeburn  12003:     for (var i=0; i<callingForm.srchin.length; i++) {
                   12004: 	if ( callingForm.srchin[i].checked ) {
                   12005: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 12006: 	}
                   12007:     }
                   12008: 
1.570     raeburn  12009:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   12010:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   12011:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   12012:     var srchterm =  callingForm.srchterm.value;
                   12013:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  12014:     var msg = "";
                   12015: 
                   12016:     if (srchterm == "") {
                   12017:         checkok = 0;
1.1222    damieng  12018:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  12019:     }
                   12020: 
1.569     raeburn  12021:     if (srchtype== 'begins') {
                   12022:         if (srchterm.length < 2) {
                   12023:             checkok = 0;
1.1222    damieng  12024:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  12025:         }
                   12026:     }
                   12027: 
1.556     raeburn  12028:     if (srchtype== 'contains') {
                   12029:         if (srchterm.length < 3) {
                   12030:             checkok = 0;
1.1222    damieng  12031:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  12032:         }
                   12033:     }
                   12034:     if (srchin == 'instd') {
                   12035:         if (srchdomain == '') {
                   12036:             checkok = 0;
1.1222    damieng  12037:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  12038:         }
                   12039:     }
                   12040:     if (srchin == 'dom') {
                   12041:         if (srchdomain == '') {
                   12042:             checkok = 0;
1.1222    damieng  12043:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  12044:         }
                   12045:     }
                   12046:     if (srchby == 'lastfirst') {
                   12047:         if (srchterm.indexOf(",") == -1) {
                   12048:             checkok = 0;
1.1222    damieng  12049:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  12050:         }
                   12051:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   12052:             checkok = 0;
1.1222    damieng  12053:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  12054:         }
                   12055:     }
                   12056:     if (checkok == 0) {
1.1222    damieng  12057:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  12058:         return;
                   12059:     }
                   12060:     if (checkok == 1) {
1.570     raeburn  12061:         callingForm.submit();
1.556     raeburn  12062:     }
                   12063: }
                   12064: 
                   12065: $newuserscript
                   12066: 
1.824     bisitz   12067: // ]]>
1.556     raeburn  12068: </script>
1.558     albertel 12069: 
                   12070: $new_user_create
                   12071: 
1.555     raeburn  12072: END_BLOCK
1.558     albertel 12073: 
1.876     raeburn  12074:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  12075:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  12076:                $domform.
                   12077:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  12078:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  12079:                $srchbysel.
                   12080:                $srchtypesel. 
                   12081:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   12082:                $srchinsel.
                   12083:                &Apache::lonhtmlcommon::row_closure(1). 
                   12084:                &Apache::lonhtmlcommon::end_pick_box().
                   12085:                '<br />';
1.1253    raeburn  12086:     return ($output,1);
1.555     raeburn  12087: }
                   12088: 
1.612     raeburn  12089: sub user_rule_check {
1.615     raeburn  12090:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  12091:     my ($response,%inst_response);
1.612     raeburn  12092:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  12093:         if (keys(%{$usershash}) > 1) {
                   12094:             my (%by_username,%by_id,%userdoms);
                   12095:             my $checkid; 
                   12096:             if (ref($checks) eq 'HASH') {
                   12097:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   12098:                     $checkid = 1;
                   12099:                 }
                   12100:             }
                   12101:             foreach my $user (keys(%{$usershash})) {
                   12102:                 my ($uname,$udom) = split(/:/,$user);
                   12103:                 if ($checkid) {
                   12104:                     if (ref($usershash->{$user}) eq 'HASH') {
                   12105:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  12106:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  12107:                             $userdoms{$udom} = 1;
1.1227    raeburn  12108:                             if (ref($inst_results) eq 'HASH') {
                   12109:                                 $inst_results->{$uname.':'.$udom} = {};
                   12110:                             }
1.1226    raeburn  12111:                         }
                   12112:                     }
                   12113:                 } else {
                   12114:                     $by_username{$udom}{$uname} = 1;
                   12115:                     $userdoms{$udom} = 1;
1.1227    raeburn  12116:                     if (ref($inst_results) eq 'HASH') {
                   12117:                         $inst_results->{$uname.':'.$udom} = {};
                   12118:                     }
1.1226    raeburn  12119:                 }
                   12120:             }
                   12121:             foreach my $udom (keys(%userdoms)) {
                   12122:                 if (!$got_rules->{$udom}) {
                   12123:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12124:                                                              ['usercreation'],$udom);
                   12125:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12126:                         foreach my $item ('username','id') {
                   12127:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  12128:                                 $$curr_rules{$udom}{$item} =
                   12129:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  12130:                             }
                   12131:                         }
                   12132:                     }
                   12133:                     $got_rules->{$udom} = 1;
                   12134:                 }
1.612     raeburn  12135:             }
1.1226    raeburn  12136:             if ($checkid) {
                   12137:                 foreach my $udom (keys(%by_id)) {
                   12138:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   12139:                     if ($outcome eq 'ok') {
1.1227    raeburn  12140:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   12141:                             my $uname = $by_id{$udom}{$id};
                   12142:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12143:                         }
1.1226    raeburn  12144:                         if (ref($results) eq 'HASH') {
                   12145:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  12146:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   12147:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   12148:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12149:                                 }
1.1226    raeburn  12150:                             }
                   12151:                         }
                   12152:                     }
1.612     raeburn  12153:                 }
1.615     raeburn  12154:             } else {
1.1226    raeburn  12155:                 foreach my $udom (keys(%by_username)) {
                   12156:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   12157:                     if ($outcome eq 'ok') {
1.1227    raeburn  12158:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   12159:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12160:                         }
1.1226    raeburn  12161:                         if (ref($results) eq 'HASH') {
                   12162:                             foreach my $uname (keys(%{$results})) {
                   12163:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12164:                             }
                   12165:                         }
                   12166:                     }
                   12167:                 }
1.612     raeburn  12168:             }
1.1226    raeburn  12169:         } elsif (keys(%{$usershash}) == 1) {
                   12170:             my $user = (keys(%{$usershash}))[0];
                   12171:             my ($uname,$udom) = split(/:/,$user);
                   12172:             if (($udom ne '') && ($uname ne '')) {
                   12173:                 if (ref($usershash->{$user}) eq 'HASH') {
                   12174:                     if (ref($checks) eq 'HASH') {
                   12175:                         if (defined($checks->{'username'})) {
                   12176:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   12177:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   12178:                         } elsif (defined($checks->{'id'})) {
                   12179:                             if ($usershash->{$user}->{'id'} ne '') {
                   12180:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12181:                                     &Apache::lonnet::get_instuser($udom,undef,
                   12182:                                                                   $usershash->{$user}->{'id'});
                   12183:                             } else {
                   12184:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12185:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   12186:                             }
1.585     raeburn  12187:                         }
1.1226    raeburn  12188:                     } else {
                   12189:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   12190:                             &Apache::lonnet::get_instuser($udom,$uname);
                   12191:                        return;
                   12192:                     }
                   12193:                     if (!$got_rules->{$udom}) {
                   12194:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12195:                                                                  ['usercreation'],$udom);
                   12196:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12197:                             foreach my $item ('username','id') {
                   12198:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   12199:                                    $$curr_rules{$udom}{$item} = 
                   12200:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   12201:                                 }
                   12202:                             }
                   12203:                         }
                   12204:                         $got_rules->{$udom} = 1;
1.585     raeburn  12205:                     }
                   12206:                 }
1.1226    raeburn  12207:             } else {
                   12208:                 return;
                   12209:             }
                   12210:         } else {
                   12211:             return;
                   12212:         }
                   12213:         foreach my $user (keys(%{$usershash})) {
                   12214:             my ($uname,$udom) = split(/:/,$user);
                   12215:             next if (($udom eq '') || ($uname eq ''));
                   12216:             my $id;
1.1227    raeburn  12217:             if (ref($inst_results) eq 'HASH') {
                   12218:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   12219:                     $id = $inst_results->{$user}->{'id'};
                   12220:                 }
                   12221:             }
                   12222:             if ($id eq '') { 
                   12223:                 if (ref($usershash->{$user})) {
                   12224:                     $id = $usershash->{$user}->{'id'};
                   12225:                 }
1.585     raeburn  12226:             }
1.612     raeburn  12227:             foreach my $item (keys(%{$checks})) {
                   12228:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   12229:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   12230:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  12231:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   12232:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  12233:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   12234:                                 if ($rule_check{$rule}) {
                   12235:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  12236:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  12237:                                         if (ref($inst_results) eq 'HASH') {
                   12238:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   12239:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   12240:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  12241:                                                 } elsif ($item eq 'id') {
                   12242:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   12243:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   12244:                                                     }
1.615     raeburn  12245:                                                 }
1.612     raeburn  12246:                                             }
                   12247:                                         }
1.615     raeburn  12248:                                     }
                   12249:                                     last;
1.585     raeburn  12250:                                 }
                   12251:                             }
                   12252:                         }
                   12253:                     }
                   12254:                 }
                   12255:             }
                   12256:         }
                   12257:     }
1.612     raeburn  12258:     return;
                   12259: }
                   12260: 
                   12261: sub user_rule_formats {
                   12262:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   12263:     my %text = ( 
                   12264:                  'username' => 'Usernames',
                   12265:                  'id'       => 'IDs',
                   12266:                );
                   12267:     my $output;
                   12268:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   12269:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   12270:         if (@{$ruleorder} > 0) {
1.1102    raeburn  12271:             $output = '<br />'.
                   12272:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   12273:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   12274:                       ' <ul>';
1.612     raeburn  12275:             foreach my $rule (@{$ruleorder}) {
                   12276:                 if (ref($curr_rules) eq 'ARRAY') {
                   12277:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   12278:                         if (ref($rules->{$rule}) eq 'HASH') {
                   12279:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   12280:                                         $rules->{$rule}{'desc'}.'</li>';
                   12281:                         }
                   12282:                     }
                   12283:                 }
                   12284:             }
                   12285:             $output .= '</ul>';
                   12286:         }
                   12287:     }
                   12288:     return $output;
                   12289: }
                   12290: 
                   12291: sub instrule_disallow_msg {
1.615     raeburn  12292:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  12293:     my $response;
                   12294:     my %text = (
                   12295:                   item   => 'username',
                   12296:                   items  => 'usernames',
                   12297:                   match  => 'matches',
                   12298:                   do     => 'does',
                   12299:                   action => 'a username',
                   12300:                   one    => 'one',
                   12301:                );
                   12302:     if ($count > 1) {
                   12303:         $text{'item'} = 'usernames';
                   12304:         $text{'match'} ='match';
                   12305:         $text{'do'} = 'do';
                   12306:         $text{'action'} = 'usernames',
                   12307:         $text{'one'} = 'ones';
                   12308:     }
                   12309:     if ($checkitem eq 'id') {
                   12310:         $text{'items'} = 'IDs';
                   12311:         $text{'item'} = 'ID';
                   12312:         $text{'action'} = 'an ID';
1.615     raeburn  12313:         if ($count > 1) {
                   12314:             $text{'item'} = 'IDs';
                   12315:             $text{'action'} = 'IDs';
                   12316:         }
1.612     raeburn  12317:     }
1.674     bisitz   12318:     $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  12319:     if ($mode eq 'upload') {
                   12320:         if ($checkitem eq 'username') {
                   12321:             $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'}.");
                   12322:         } elsif ($checkitem eq 'id') {
1.674     bisitz   12323:             $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  12324:         }
1.669     raeburn  12325:     } elsif ($mode eq 'selfcreate') {
                   12326:         if ($checkitem eq 'id') {
                   12327:             $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.");
                   12328:         }
1.615     raeburn  12329:     } else {
                   12330:         if ($checkitem eq 'username') {
                   12331:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   12332:         } elsif ($checkitem eq 'id') {
                   12333:             $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.");
                   12334:         }
1.612     raeburn  12335:     }
                   12336:     return $response;
1.585     raeburn  12337: }
                   12338: 
1.624     raeburn  12339: sub personal_data_fieldtitles {
                   12340:     my %fieldtitles = &Apache::lonlocal::texthash (
                   12341:                         id => 'Student/Employee ID',
                   12342:                         permanentemail => 'E-mail address',
                   12343:                         lastname => 'Last Name',
                   12344:                         firstname => 'First Name',
                   12345:                         middlename => 'Middle Name',
                   12346:                         generation => 'Generation',
                   12347:                         gen => 'Generation',
1.765     raeburn  12348:                         inststatus => 'Affiliation',
1.624     raeburn  12349:                    );
                   12350:     return %fieldtitles;
                   12351: }
                   12352: 
1.642     raeburn  12353: sub sorted_inst_types {
                   12354:     my ($dom) = @_;
1.1185    raeburn  12355:     my ($usertypes,$order);
                   12356:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   12357:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   12358:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   12359:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   12360:     } else {
                   12361:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   12362:     }
1.642     raeburn  12363:     my $othertitle = &mt('All users');
                   12364:     if ($env{'request.course.id'}) {
1.668     raeburn  12365:         $othertitle  = &mt('Any users');
1.642     raeburn  12366:     }
                   12367:     my @types;
                   12368:     if (ref($order) eq 'ARRAY') {
                   12369:         @types = @{$order};
                   12370:     }
                   12371:     if (@types == 0) {
                   12372:         if (ref($usertypes) eq 'HASH') {
                   12373:             @types = sort(keys(%{$usertypes}));
                   12374:         }
                   12375:     }
                   12376:     if (keys(%{$usertypes}) > 0) {
                   12377:         $othertitle = &mt('Other users');
                   12378:     }
                   12379:     return ($othertitle,$usertypes,\@types);
                   12380: }
                   12381: 
1.645     raeburn  12382: sub get_institutional_codes {
1.1361    raeburn  12383:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  12384: # Get complete list of course sections to update
                   12385:     my @currsections = ();
                   12386:     my @currxlists = ();
1.1361    raeburn  12387:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  12388:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  12389:     my $crskey = $crs.':'.$coursecode;
                   12390:     @{$unclutteredsec{$crskey}} = ();
                   12391:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  12392: 
                   12393:     if ($$settings{'internal.sectionnums'} ne '') {
                   12394:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   12395:     }
                   12396: 
                   12397:     if ($$settings{'internal.crosslistings'} ne '') {
                   12398:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   12399:     }
                   12400: 
                   12401:     if (@currxlists > 0) {
1.1361    raeburn  12402:         foreach my $xl (@currxlists) {
                   12403:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  12404:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  12405:                     push(@{$allcourses},$1);
1.645     raeburn  12406:                     $$LC_code{$1} = $2;
                   12407:                 }
                   12408:             }
                   12409:         }
                   12410:     }
1.1361    raeburn  12411: 
1.645     raeburn  12412:     if (@currsections > 0) {
1.1361    raeburn  12413:         foreach my $sec (@currsections) {
                   12414:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   12415:                 my $instsec = $1;
1.645     raeburn  12416:                 my $lc_sec = $2;
1.1361    raeburn  12417:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   12418:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   12419:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   12420:                 }
                   12421:             }
                   12422:         }
                   12423:     }
                   12424: 
                   12425:     if (@{$unclutteredsec{$crskey}} > 0) {
                   12426:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   12427:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   12428:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   12429:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   12430:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  12431:                     push(@{$allcourses},$sec);
1.1361    raeburn  12432:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  12433:                 }
                   12434:             }
                   12435:         }
                   12436:     }
                   12437:     return;
                   12438: }
                   12439: 
1.971     raeburn  12440: sub get_standard_codeitems {
                   12441:     return ('Year','Semester','Department','Number','Section');
                   12442: }
                   12443: 
1.112     bowersj2 12444: =pod
                   12445: 
1.780     raeburn  12446: =head1 Slot Helpers
                   12447: 
                   12448: =over 4
                   12449: 
                   12450: =item * sorted_slots()
                   12451: 
1.1040    raeburn  12452: Sorts an array of slot names in order of an optional sort key,
                   12453: default sort is by slot start time (earliest first). 
1.780     raeburn  12454: 
                   12455: Inputs:
                   12456: 
                   12457: =over 4
                   12458: 
                   12459: slotsarr  - Reference to array of unsorted slot names.
                   12460: 
                   12461: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   12462: 
1.1040    raeburn  12463: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   12464: 
1.549     albertel 12465: =back
                   12466: 
1.780     raeburn  12467: Returns:
                   12468: 
                   12469: =over 4
                   12470: 
1.1040    raeburn  12471: sorted   - An array of slot names sorted by a specified sort key 
                   12472:            (default sort key is start time of the slot).
1.780     raeburn  12473: 
                   12474: =back
                   12475: 
                   12476: =cut
                   12477: 
                   12478: 
                   12479: sub sorted_slots {
1.1040    raeburn  12480:     my ($slotsarr,$slots,$sortkey) = @_;
                   12481:     if ($sortkey eq '') {
                   12482:         $sortkey = 'starttime';
                   12483:     }
1.780     raeburn  12484:     my @sorted;
                   12485:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   12486:         @sorted =
                   12487:             sort {
                   12488:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  12489:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  12490:                      }
                   12491:                      if (ref($slots->{$a})) { return -1;}
                   12492:                      if (ref($slots->{$b})) { return 1;}
                   12493:                      return 0;
                   12494:                  } @{$slotsarr};
                   12495:     }
                   12496:     return @sorted;
                   12497: }
                   12498: 
1.1040    raeburn  12499: =pod
                   12500: 
                   12501: =item * get_future_slots()
                   12502: 
                   12503: Inputs:
                   12504: 
                   12505: =over 4
                   12506: 
                   12507: cnum - course number
                   12508: 
                   12509: cdom - course domain
                   12510: 
                   12511: now - current UNIX time
                   12512: 
                   12513: symb - optional symb
                   12514: 
                   12515: =back
                   12516: 
                   12517: Returns:
                   12518: 
                   12519: =over 4
                   12520: 
                   12521: sorted_reservable - ref to array of student_schedulable slots currently 
                   12522:                     reservable, ordered by end date of reservation period.
                   12523: 
                   12524: reservable_now - ref to hash of student_schedulable slots currently
                   12525:                  reservable.
                   12526: 
                   12527:     Keys in inner hash are:
                   12528:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12529:     (b) endreserve: end date of reservation period.
                   12530:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12531:         selected.
1.1040    raeburn  12532: 
                   12533: sorted_future - ref to array of student_schedulable slots reservable in
                   12534:                 the future, ordered by start date of reservation period.
                   12535: 
                   12536: future_reservable - ref to hash of student_schedulable slots reservable
                   12537:                     in the future.
                   12538: 
                   12539:     Keys in inner hash are:
                   12540:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12541:     (b) startreserve: start date of reservation period.
                   12542:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12543:         selected.
1.1040    raeburn  12544: 
                   12545: =back
                   12546: 
                   12547: =cut
                   12548: 
                   12549: sub get_future_slots {
                   12550:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  12551:     my $map;
                   12552:     if ($symb) {
                   12553:         ($map) = &Apache::lonnet::decode_symb($symb);
                   12554:     }
1.1040    raeburn  12555:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   12556:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   12557:     foreach my $slot (keys(%slots)) {
                   12558:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   12559:         if ($symb) {
1.1229    raeburn  12560:             if ($slots{$slot}->{'symb'} ne '') {
                   12561:                 my $canuse;
                   12562:                 my %oksymbs;
                   12563:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   12564:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   12565:                 if ($oksymbs{$symb}) {
                   12566:                     $canuse = 1;
                   12567:                 } else {
                   12568:                     foreach my $item (@slotsymbs) {
                   12569:                         if ($item =~ /\.(page|sequence)$/) {
                   12570:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   12571:                             if (($map ne '') && ($map eq $sloturl)) {
                   12572:                                 $canuse = 1;
                   12573:                                 last;
                   12574:                             }
                   12575:                         }
                   12576:                     }
                   12577:                 }
                   12578:                 next unless ($canuse);
                   12579:             }
1.1040    raeburn  12580:         }
                   12581:         if (($slots{$slot}->{'starttime'} > $now) &&
                   12582:             ($slots{$slot}->{'endtime'} > $now)) {
                   12583:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   12584:                 my $userallowed = 0;
                   12585:                 if ($slots{$slot}->{'allowedsections'}) {
                   12586:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   12587:                     if (!defined($env{'request.role.sec'})
                   12588:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   12589:                         $userallowed=1;
                   12590:                     } else {
                   12591:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   12592:                             $userallowed=1;
                   12593:                         }
                   12594:                     }
                   12595:                     unless ($userallowed) {
                   12596:                         if (defined($env{'request.course.groups'})) {
                   12597:                             my @groups = split(/:/,$env{'request.course.groups'});
                   12598:                             foreach my $group (@groups) {
                   12599:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   12600:                                     $userallowed=1;
                   12601:                                     last;
                   12602:                                 }
                   12603:                             }
                   12604:                         }
                   12605:                     }
                   12606:                 }
                   12607:                 if ($slots{$slot}->{'allowedusers'}) {
                   12608:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   12609:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   12610:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   12611:                         $userallowed = 1;
                   12612:                     }
                   12613:                 }
                   12614:                 next unless($userallowed);
                   12615:             }
                   12616:             my $startreserve = $slots{$slot}->{'startreserve'};
                   12617:             my $endreserve = $slots{$slot}->{'endreserve'};
                   12618:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  12619:             my $uniqueperiod;
                   12620:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   12621:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   12622:             }
1.1040    raeburn  12623:             if (($startreserve < $now) &&
                   12624:                 (!$endreserve || $endreserve > $now)) {
                   12625:                 my $lastres = $endreserve;
                   12626:                 if (!$lastres) {
                   12627:                     $lastres = $slots{$slot}->{'starttime'};
                   12628:                 }
                   12629:                 $reservable_now{$slot} = {
                   12630:                                            symb       => $symb,
1.1250    raeburn  12631:                                            endreserve => $lastres,
                   12632:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  12633:                                          };
                   12634:             } elsif (($startreserve > $now) &&
                   12635:                      (!$endreserve || $endreserve > $startreserve)) {
                   12636:                 $future_reservable{$slot} = {
                   12637:                                               symb         => $symb,
1.1250    raeburn  12638:                                               startreserve => $startreserve,
                   12639:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  12640:                                             };
                   12641:             }
                   12642:         }
                   12643:     }
                   12644:     my @unsorted_reservable = keys(%reservable_now);
                   12645:     if (@unsorted_reservable > 0) {
                   12646:         @sorted_reservable = 
                   12647:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   12648:     }
                   12649:     my @unsorted_future = keys(%future_reservable);
                   12650:     if (@unsorted_future > 0) {
                   12651:         @sorted_future =
                   12652:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   12653:     }
                   12654:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   12655: }
1.780     raeburn  12656: 
                   12657: =pod
                   12658: 
1.1057    foxr     12659: =back
                   12660: 
1.549     albertel 12661: =head1 HTTP Helpers
                   12662: 
                   12663: =over 4
                   12664: 
1.648     raeburn  12665: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 12666: 
1.258     albertel 12667: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 12668: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 12669: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 12670: 
                   12671: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   12672: $possible_names is an ref to an array of form element names.  As an example:
                   12673: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 12674: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 12675: 
                   12676: =cut
1.1       albertel 12677: 
1.6       albertel 12678: sub get_unprocessed_cgi {
1.25      albertel 12679:   my ($query,$possible_names)= @_;
1.26      matthew  12680:   # $Apache::lonxml::debug=1;
1.356     albertel 12681:   foreach my $pair (split(/&/,$query)) {
                   12682:     my ($name, $value) = split(/=/,$pair);
1.369     www      12683:     $name = &unescape($name);
1.25      albertel 12684:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   12685:       $value =~ tr/+/ /;
                   12686:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 12687:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 12688:     }
1.16      harris41 12689:   }
1.6       albertel 12690: }
                   12691: 
1.112     bowersj2 12692: =pod
                   12693: 
1.648     raeburn  12694: =item * &cacheheader() 
1.112     bowersj2 12695: 
                   12696: returns cache-controlling header code
                   12697: 
                   12698: =cut
                   12699: 
1.7       albertel 12700: sub cacheheader {
1.258     albertel 12701:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12702:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12703:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12704:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12705:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12706:     return $output;
1.7       albertel 12707: }
                   12708: 
1.112     bowersj2 12709: =pod
                   12710: 
1.648     raeburn  12711: =item * &no_cache($r) 
1.112     bowersj2 12712: 
                   12713: specifies header code to not have cache
                   12714: 
                   12715: =cut
                   12716: 
1.9       albertel 12717: sub no_cache {
1.216     albertel 12718:     my ($r) = @_;
                   12719:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12720: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12721:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12722:     $r->no_cache(1);
                   12723:     $r->header_out("Expires" => $date);
                   12724:     $r->header_out("Pragma" => "no-cache");
1.123     www      12725: }
                   12726: 
                   12727: sub content_type {
1.181     albertel 12728:     my ($r,$type,$charset) = @_;
1.299     foxr     12729:     if ($r) {
                   12730: 	#  Note that printout.pl calls this with undef for $r.
                   12731: 	&no_cache($r);
                   12732:     }
1.258     albertel 12733:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12734:     unless ($charset) {
                   12735: 	$charset=&Apache::lonlocal::current_encoding;
                   12736:     }
                   12737:     if ($charset) { $type.='; charset='.$charset; }
                   12738:     if ($r) {
                   12739: 	$r->content_type($type);
                   12740:     } else {
                   12741: 	print("Content-type: $type\n\n");
                   12742:     }
1.9       albertel 12743: }
1.25      albertel 12744: 
1.112     bowersj2 12745: =pod
                   12746: 
1.648     raeburn  12747: =item * &add_to_env($name,$value) 
1.112     bowersj2 12748: 
1.258     albertel 12749: adds $name to the %env hash with value
1.112     bowersj2 12750: $value, if $name already exists, the entry is converted to an array
                   12751: reference and $value is added to the array.
                   12752: 
                   12753: =cut
                   12754: 
1.25      albertel 12755: sub add_to_env {
                   12756:   my ($name,$value)=@_;
1.258     albertel 12757:   if (defined($env{$name})) {
                   12758:     if (ref($env{$name})) {
1.25      albertel 12759:       #already have multiple values
1.258     albertel 12760:       push(@{ $env{$name} },$value);
1.25      albertel 12761:     } else {
                   12762:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12763:       my $first=$env{$name};
                   12764:       undef($env{$name});
                   12765:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12766:     }
                   12767:   } else {
1.258     albertel 12768:     $env{$name}=$value;
1.25      albertel 12769:   }
1.31      albertel 12770: }
1.149     albertel 12771: 
                   12772: =pod
                   12773: 
1.648     raeburn  12774: =item * &get_env_multiple($name) 
1.149     albertel 12775: 
1.258     albertel 12776: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12777: values may be defined and end up as an array ref.
                   12778: 
                   12779: returns an array of values
                   12780: 
                   12781: =cut
                   12782: 
                   12783: sub get_env_multiple {
                   12784:     my ($name) = @_;
                   12785:     my @values;
1.258     albertel 12786:     if (defined($env{$name})) {
1.149     albertel 12787:         # exists is it an array
1.258     albertel 12788:         if (ref($env{$name})) {
                   12789:             @values=@{ $env{$name} };
1.149     albertel 12790:         } else {
1.258     albertel 12791:             $values[0]=$env{$name};
1.149     albertel 12792:         }
                   12793:     }
                   12794:     return(@values);
                   12795: }
                   12796: 
1.1249    damieng  12797: # Looks at given dependencies, and returns something depending on the context.
                   12798: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12799: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12800: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12801: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12802: # $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.
                   12803: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12804: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12805: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12806: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12807: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12808: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12809: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12810: # @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)
                   12811: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12812: sub ask_for_embedded_content {
1.1249    damieng  12813:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12814:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12815:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12816:         %currsubfile,%unused,$rem);
1.1071    raeburn  12817:     my $counter = 0;
                   12818:     my $numnew = 0;
1.987     raeburn  12819:     my $numremref = 0;
                   12820:     my $numinvalid = 0;
                   12821:     my $numpathchg = 0;
                   12822:     my $numexisting = 0;
1.1071    raeburn  12823:     my $numunused = 0;
                   12824:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12825:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12826:     my $heading = &mt('Upload embedded files');
                   12827:     my $buttontext = &mt('Upload');
                   12828: 
1.1249    damieng  12829:     # fills these variables based on the context:
                   12830:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12831:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12832:     if ($env{'request.course.id'}) {
1.1123    raeburn  12833:         if ($actionurl eq '/adm/dependencies') {
                   12834:             $navmap = Apache::lonnavmaps::navmap->new();
                   12835:         }
                   12836:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12837:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12838:     }
1.1123    raeburn  12839:     if (($actionurl eq '/adm/portfolio') || 
                   12840:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12841:         my $current_path='/';
                   12842:         if ($env{'form.currentpath'}) {
                   12843:             $current_path = $env{'form.currentpath'};
                   12844:         }
                   12845:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12846:             $udom = $cdom;
                   12847:             $uname = $cnum;
1.984     raeburn  12848:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12849:         } else {
                   12850:             $udom = $env{'user.domain'};
                   12851:             $uname = $env{'user.name'};
                   12852:             $url = '/userfiles/portfolio';
                   12853:         }
1.987     raeburn  12854:         $toplevel = $url.'/';
1.984     raeburn  12855:         $url .= $current_path;
                   12856:         $getpropath = 1;
1.987     raeburn  12857:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12858:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12859:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12860:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12861:         $toplevel = $url;
1.984     raeburn  12862:         if ($rest ne '') {
1.987     raeburn  12863:             $url .= $rest;
                   12864:         }
                   12865:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12866:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12867:             $url = $args->{'docs_url'};
                   12868:             $toplevel = $url;
1.1084    raeburn  12869:             if ($args->{'context'} eq 'paste') {
                   12870:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12871:                 ($path) = 
                   12872:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12873:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12874:                 $fileloc =~ s{^/}{};
                   12875:             }
1.1071    raeburn  12876:         }
1.1084    raeburn  12877:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12878:         if ($env{'request.course.id'} ne '') {
                   12879:             if (ref($args) eq 'HASH') {
                   12880:                 $url = $args->{'docs_url'};
                   12881:                 $title = $args->{'docs_title'};
1.1126    raeburn  12882:                 $toplevel = $url; 
                   12883:                 unless ($toplevel =~ m{^/}) {
                   12884:                     $toplevel = "/$url";
                   12885:                 }
1.1085    raeburn  12886:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12887:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12888:                     $path = $1;
                   12889:                 } else {
                   12890:                     ($path) =
                   12891:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12892:                 }
1.1195    raeburn  12893:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12894:                     $fileloc = $toplevel;
                   12895:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12896:                     my ($udom,$uname,$fname) =
                   12897:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12898:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12899:                 } else {
                   12900:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12901:                 }
1.1071    raeburn  12902:                 $fileloc =~ s{^/}{};
                   12903:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12904:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12905:             }
1.987     raeburn  12906:         }
1.1123    raeburn  12907:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12908:         $udom = $cdom;
                   12909:         $uname = $cnum;
                   12910:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12911:         $toplevel = $url;
                   12912:         $path = $url;
                   12913:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12914:         $fileloc =~ s{^/}{};
1.987     raeburn  12915:     }
1.1249    damieng  12916:     
                   12917:     # parses the dependency paths to get some info
                   12918:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12919:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12920:     # (will be completed later)
                   12921:     # $mapping:
                   12922:     #   for external URLs: external URL -> external URL
                   12923:     #   for relative paths: clean path -> original path
                   12924:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12925:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12926:     foreach my $file (keys(%{$allfiles})) {
                   12927:         my $embed_file;
                   12928:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12929:             $embed_file = $1;
                   12930:         } else {
                   12931:             $embed_file = $file;
                   12932:         }
1.1158    raeburn  12933:         my ($absolutepath,$cleaned_file);
                   12934:         if ($embed_file =~ m{^\w+://}) {
                   12935:             $cleaned_file = $embed_file;
1.1147    raeburn  12936:             $newfiles{$cleaned_file} = 1;
                   12937:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12938:         } else {
1.1158    raeburn  12939:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12940:             if ($embed_file =~ m{^/}) {
                   12941:                 $absolutepath = $embed_file;
                   12942:             }
1.1147    raeburn  12943:             if ($cleaned_file =~ m{/}) {
                   12944:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12945:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12946:                 my $item = $fname;
                   12947:                 if ($path ne '') {
                   12948:                     $item = $path.'/'.$fname;
                   12949:                     $subdependencies{$path}{$fname} = 1;
                   12950:                 } else {
                   12951:                     $dependencies{$item} = 1;
                   12952:                 }
                   12953:                 if ($absolutepath) {
                   12954:                     $mapping{$item} = $absolutepath;
                   12955:                 } else {
                   12956:                     $mapping{$item} = $embed_file;
                   12957:                 }
                   12958:             } else {
                   12959:                 $dependencies{$embed_file} = 1;
                   12960:                 if ($absolutepath) {
1.1147    raeburn  12961:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12962:                 } else {
1.1147    raeburn  12963:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12964:                 }
                   12965:             }
1.984     raeburn  12966:         }
                   12967:     }
1.1249    damieng  12968:     
                   12969:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12970:     # and lists
                   12971:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12972:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12973:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12974:     #                                    the path had to be cleaned up
                   12975:     # $existing: hash clean path -> 1 if the file exists
                   12976:     # $numexisting: number of keys in $existing
                   12977:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12978:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12979:     #                                      dependency subdirectories that are
                   12980:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12981:     my $dirptr = 16384;
1.984     raeburn  12982:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12983:         $currsubfile{$path} = {};
1.1123    raeburn  12984:         if (($actionurl eq '/adm/portfolio') || 
                   12985:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12986:             my ($sublistref,$listerror) =
                   12987:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12988:             if (ref($sublistref) eq 'ARRAY') {
                   12989:                 foreach my $line (@{$sublistref}) {
                   12990:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12991:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12992:                 }
1.984     raeburn  12993:             }
1.987     raeburn  12994:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12995:             if (opendir(my $dir,$url.'/'.$path)) {
                   12996:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12997:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12998:             }
1.1084    raeburn  12999:         } elsif (($actionurl eq '/adm/dependencies') ||
                   13000:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  13001:                   ($args->{'context'} eq 'paste')) ||
                   13002:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  13003:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  13004:                 my $dir;
                   13005:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   13006:                     $dir = $fileloc;
                   13007:                 } else {
                   13008:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   13009:                 }
1.1071    raeburn  13010:                 if ($dir ne '') {
                   13011:                     my ($sublistref,$listerror) =
                   13012:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   13013:                     if (ref($sublistref) eq 'ARRAY') {
                   13014:                         foreach my $line (@{$sublistref}) {
                   13015:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   13016:                                 undef,$mtime)=split(/\&/,$line,12);
                   13017:                             unless (($testdir&$dirptr) ||
                   13018:                                     ($file_name =~ /^\.\.?$/)) {
                   13019:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   13020:                             }
                   13021:                         }
                   13022:                     }
                   13023:                 }
1.984     raeburn  13024:             }
                   13025:         }
                   13026:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  13027:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  13028:                 my $item = $path.'/'.$file;
                   13029:                 unless ($mapping{$item} eq $item) {
                   13030:                     $pathchanges{$item} = 1;
                   13031:                 }
                   13032:                 $existing{$item} = 1;
                   13033:                 $numexisting ++;
                   13034:             } else {
                   13035:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  13036:             }
                   13037:         }
1.1071    raeburn  13038:         if ($actionurl eq '/adm/dependencies') {
                   13039:             foreach my $path (keys(%currsubfile)) {
                   13040:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   13041:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   13042:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  13043:                              next if (($rem ne '') &&
                   13044:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   13045:                                        (ref($navmap) &&
                   13046:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   13047:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   13048:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  13049:                              $unused{$path.'/'.$file} = 1; 
                   13050:                          }
                   13051:                     }
                   13052:                 }
                   13053:             }
                   13054:         }
1.984     raeburn  13055:     }
1.1249    damieng  13056:     
                   13057:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   13058:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  13059:     my %currfile;
1.1123    raeburn  13060:     if (($actionurl eq '/adm/portfolio') ||
                   13061:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  13062:         my ($dirlistref,$listerror) =
                   13063:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   13064:         if (ref($dirlistref) eq 'ARRAY') {
                   13065:             foreach my $line (@{$dirlistref}) {
                   13066:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   13067:                 $currfile{$file_name} = 1;
                   13068:             }
1.984     raeburn  13069:         }
1.987     raeburn  13070:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  13071:         if (opendir(my $dir,$url)) {
1.987     raeburn  13072:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  13073:             map {$currfile{$_} = 1;} @dir_list;
                   13074:         }
1.1084    raeburn  13075:     } elsif (($actionurl eq '/adm/dependencies') ||
                   13076:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  13077:               ($args->{'context'} eq 'paste')) ||
                   13078:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  13079:         if ($env{'request.course.id'} ne '') {
                   13080:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   13081:             if ($dir ne '') {
                   13082:                 my ($dirlistref,$listerror) =
                   13083:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   13084:                 if (ref($dirlistref) eq 'ARRAY') {
                   13085:                     foreach my $line (@{$dirlistref}) {
                   13086:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   13087:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   13088:                         unless (($testdir&$dirptr) ||
                   13089:                                 ($file_name =~ /^\.\.?$/)) {
                   13090:                             $currfile{$file_name} = [$size,$mtime];
                   13091:                         }
                   13092:                     }
                   13093:                 }
                   13094:             }
                   13095:         }
1.984     raeburn  13096:     }
1.1249    damieng  13097:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   13098:     # are not in subdirectories, using $currfile
1.984     raeburn  13099:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  13100:         if (exists($currfile{$file})) {
1.987     raeburn  13101:             unless ($mapping{$file} eq $file) {
                   13102:                 $pathchanges{$file} = 1;
                   13103:             }
                   13104:             $existing{$file} = 1;
                   13105:             $numexisting ++;
                   13106:         } else {
1.984     raeburn  13107:             $newfiles{$file} = 1;
                   13108:         }
                   13109:     }
1.1071    raeburn  13110:     foreach my $file (keys(%currfile)) {
                   13111:         unless (($file eq $filename) ||
                   13112:                 ($file eq $filename.'.bak') ||
                   13113:                 ($dependencies{$file})) {
1.1085    raeburn  13114:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  13115:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   13116:                     next if (($rem ne '') &&
                   13117:                              (($env{"httpref.$rem".$file} ne '') ||
                   13118:                               (ref($navmap) &&
                   13119:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   13120:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   13121:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   13122:                 }
1.1085    raeburn  13123:             }
1.1071    raeburn  13124:             $unused{$file} = 1;
                   13125:         }
                   13126:     }
1.1249    damieng  13127:     
                   13128:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  13129:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   13130:         ($args->{'context'} eq 'paste')) {
                   13131:         $counter = scalar(keys(%existing));
                   13132:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  13133:         return ($output,$counter,$numpathchg,\%existing);
                   13134:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   13135:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   13136:         $counter = scalar(keys(%existing));
                   13137:         $numpathchg = scalar(keys(%pathchanges));
                   13138:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  13139:     }
1.1249    damieng  13140:     
                   13141:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   13142:     
                   13143:     # $upload_output: missing dependencies (with upload form)
                   13144:     # $modify_output: uploaded dependencies (in use)
                   13145:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  13146:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  13147:         if ($actionurl eq '/adm/dependencies') {
                   13148:             next if ($embed_file =~ m{^\w+://});
                   13149:         }
1.660     raeburn  13150:         $upload_output .= &start_data_table_row().
1.1123    raeburn  13151:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  13152:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  13153:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  13154:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   13155:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  13156:         }
1.1123    raeburn  13157:         $upload_output .= '</td>';
1.1071    raeburn  13158:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  13159:             $upload_output.='<td align="right">'.
                   13160:                             '<span class="LC_info LC_fontsize_medium">'.
                   13161:                             &mt("URL points to web address").'</span>';
1.987     raeburn  13162:             $numremref++;
1.660     raeburn  13163:         } elsif ($args->{'error_on_invalid_names'}
                   13164:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  13165:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   13166:                             &mt('Invalid characters').'</span>';
1.987     raeburn  13167:             $numinvalid++;
1.660     raeburn  13168:         } else {
1.1123    raeburn  13169:             $upload_output .= '<td>'.
                   13170:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  13171:                                                      $embed_file,\%mapping,
1.1071    raeburn  13172:                                                      $allfiles,$codebase,'upload');
                   13173:             $counter ++;
                   13174:             $numnew ++;
1.987     raeburn  13175:         }
                   13176:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   13177:     }
                   13178:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  13179:         if ($actionurl eq '/adm/dependencies') {
                   13180:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   13181:             $modify_output .= &start_data_table_row().
                   13182:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   13183:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   13184:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   13185:                               '<td>'.$size.'</td>'.
                   13186:                               '<td>'.$mtime.'</td>'.
                   13187:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   13188:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   13189:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   13190:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   13191:                               &embedded_file_element('upload_embedded',$counter,
                   13192:                                                      $embed_file,\%mapping,
                   13193:                                                      $allfiles,$codebase,'modify').
                   13194:                               '</div></td>'.
                   13195:                               &end_data_table_row()."\n";
                   13196:             $counter ++;
                   13197:         } else {
                   13198:             $upload_output .= &start_data_table_row().
1.1123    raeburn  13199:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   13200:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   13201:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  13202:                               &Apache::loncommon::end_data_table_row()."\n";
                   13203:         }
                   13204:     }
                   13205:     my $delidx = $counter;
                   13206:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   13207:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   13208:         $delete_output .= &start_data_table_row().
                   13209:                           '<td><img src="'.&icon($oldfile).'" />'.
                   13210:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   13211:                           '<td>'.$size.'</td>'.
                   13212:                           '<td>'.$mtime.'</td>'.
                   13213:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   13214:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   13215:                           &embedded_file_element('upload_embedded',$delidx,
                   13216:                                                  $oldfile,\%mapping,$allfiles,
                   13217:                                                  $codebase,'delete').'</td>'.
                   13218:                           &end_data_table_row()."\n"; 
                   13219:         $numunused ++;
                   13220:         $delidx ++;
1.987     raeburn  13221:     }
                   13222:     if ($upload_output) {
                   13223:         $upload_output = &start_data_table().
                   13224:                          $upload_output.
                   13225:                          &end_data_table()."\n";
                   13226:     }
1.1071    raeburn  13227:     if ($modify_output) {
                   13228:         $modify_output = &start_data_table().
                   13229:                          &start_data_table_header_row().
                   13230:                          '<th>'.&mt('File').'</th>'.
                   13231:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13232:                          '<th>'.&mt('Modified').'</th>'.
                   13233:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   13234:                          &end_data_table_header_row().
                   13235:                          $modify_output.
                   13236:                          &end_data_table()."\n";
                   13237:     }
                   13238:     if ($delete_output) {
                   13239:         $delete_output = &start_data_table().
                   13240:                          &start_data_table_header_row().
                   13241:                          '<th>'.&mt('File').'</th>'.
                   13242:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13243:                          '<th>'.&mt('Modified').'</th>'.
                   13244:                          '<th>'.&mt('Delete?').'</th>'.
                   13245:                          &end_data_table_header_row().
                   13246:                          $delete_output.
                   13247:                          &end_data_table()."\n";
                   13248:     }
1.987     raeburn  13249:     my $applies = 0;
                   13250:     if ($numremref) {
                   13251:         $applies ++;
                   13252:     }
                   13253:     if ($numinvalid) {
                   13254:         $applies ++;
                   13255:     }
                   13256:     if ($numexisting) {
                   13257:         $applies ++;
                   13258:     }
1.1071    raeburn  13259:     if ($counter || $numunused) {
1.987     raeburn  13260:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   13261:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  13262:                   $state.'<h3>'.$heading.'</h3>'; 
                   13263:         if ($actionurl eq '/adm/dependencies') {
                   13264:             if ($numnew) {
                   13265:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   13266:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   13267:                            $upload_output.'<br />'."\n";
                   13268:             }
                   13269:             if ($numexisting) {
                   13270:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   13271:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   13272:                            $modify_output.'<br />'."\n";
                   13273:                            $buttontext = &mt('Save changes');
                   13274:             }
                   13275:             if ($numunused) {
                   13276:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   13277:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   13278:                            $delete_output.'<br />'."\n";
                   13279:                            $buttontext = &mt('Save changes');
                   13280:             }
                   13281:         } else {
                   13282:             $output .= $upload_output.'<br />'."\n";
                   13283:         }
                   13284:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   13285:                    $counter.'" />'."\n";
                   13286:         if ($actionurl eq '/adm/dependencies') { 
                   13287:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   13288:                        $numnew.'" />'."\n";
                   13289:         } elsif ($actionurl eq '') {
1.987     raeburn  13290:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   13291:         }
                   13292:     } elsif ($applies) {
                   13293:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   13294:         if ($applies > 1) {
                   13295:             $output .=  
1.1123    raeburn  13296:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  13297:             if ($numremref) {
                   13298:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   13299:             }
                   13300:             if ($numinvalid) {
                   13301:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   13302:             }
                   13303:             if ($numexisting) {
                   13304:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   13305:             }
                   13306:             $output .= '</ul><br />';
                   13307:         } elsif ($numremref) {
                   13308:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   13309:         } elsif ($numinvalid) {
                   13310:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   13311:         } elsif ($numexisting) {
                   13312:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   13313:         }
                   13314:         $output .= $upload_output.'<br />';
                   13315:     }
                   13316:     my ($pathchange_output,$chgcount);
1.1071    raeburn  13317:     $chgcount = $counter;
1.987     raeburn  13318:     if (keys(%pathchanges) > 0) {
                   13319:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  13320:             if ($counter) {
1.987     raeburn  13321:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   13322:                                                   $embed_file,\%mapping,
1.1071    raeburn  13323:                                                   $allfiles,$codebase,'change');
1.987     raeburn  13324:             } else {
                   13325:                 $pathchange_output .= 
                   13326:                     &start_data_table_row().
                   13327:                     '<td><input type ="checkbox" name="namechange" value="'.
                   13328:                     $chgcount.'" checked="checked" /></td>'.
                   13329:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   13330:                     '<td>'.$embed_file.
                   13331:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  13332:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  13333:                     '</td>'.&end_data_table_row();
1.660     raeburn  13334:             }
1.987     raeburn  13335:             $numpathchg ++;
                   13336:             $chgcount ++;
1.660     raeburn  13337:         }
                   13338:     }
1.1127    raeburn  13339:     if (($counter) || ($numunused)) {
1.987     raeburn  13340:         if ($numpathchg) {
                   13341:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   13342:                        $numpathchg.'" />'."\n";
                   13343:         }
                   13344:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   13345:             ($actionurl eq '/adm/imsimport')) {
                   13346:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   13347:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   13348:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  13349:         } elsif ($actionurl eq '/adm/dependencies') {
                   13350:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  13351:         }
1.1123    raeburn  13352:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  13353:     } elsif ($numpathchg) {
                   13354:         my %pathchange = ();
                   13355:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   13356:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13357:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  13358:         }
1.987     raeburn  13359:     }
1.1071    raeburn  13360:     return ($output,$counter,$numpathchg);
1.987     raeburn  13361: }
                   13362: 
1.1147    raeburn  13363: =pod
                   13364: 
                   13365: =item * clean_path($name)
                   13366: 
                   13367: Performs clean-up of directories, subdirectories and filename in an
                   13368: embedded object, referenced in an HTML file which is being uploaded
                   13369: to a course or portfolio, where 
                   13370: "Upload embedded images/multimedia files if HTML file" checkbox was
                   13371: checked.
                   13372: 
                   13373: Clean-up is similar to replacements in lonnet::clean_filename()
                   13374: except each / between sub-directory and next level is preserved.
                   13375: 
                   13376: =cut
                   13377: 
                   13378: sub clean_path {
                   13379:     my ($embed_file) = @_;
                   13380:     $embed_file =~s{^/+}{};
                   13381:     my @contents;
                   13382:     if ($embed_file =~ m{/}) {
                   13383:         @contents = split(/\//,$embed_file);
                   13384:     } else {
                   13385:         @contents = ($embed_file);
                   13386:     }
                   13387:     my $lastidx = scalar(@contents)-1;
                   13388:     for (my $i=0; $i<=$lastidx; $i++) { 
                   13389:         $contents[$i]=~s{\\}{/}g;
                   13390:         $contents[$i]=~s/\s+/\_/g;
                   13391:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   13392:         if ($i == $lastidx) {
                   13393:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   13394:         }
                   13395:     }
                   13396:     if ($lastidx > 0) {
                   13397:         return join('/',@contents);
                   13398:     } else {
                   13399:         return $contents[0];
                   13400:     }
                   13401: }
                   13402: 
1.987     raeburn  13403: sub embedded_file_element {
1.1071    raeburn  13404:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  13405:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   13406:                    (ref($codebase) eq 'HASH'));
                   13407:     my $output;
1.1071    raeburn  13408:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  13409:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   13410:     }
                   13411:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   13412:                &escape($embed_file).'" />';
                   13413:     unless (($context eq 'upload_embedded') && 
                   13414:             ($mapping->{$embed_file} eq $embed_file)) {
                   13415:         $output .='
                   13416:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   13417:     }
                   13418:     my $attrib;
                   13419:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   13420:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   13421:     }
                   13422:     $output .=
                   13423:         "\n\t\t".
                   13424:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   13425:         $attrib.'" />';
                   13426:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   13427:         $output .=
                   13428:             "\n\t\t".
                   13429:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   13430:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  13431:     }
1.987     raeburn  13432:     return $output;
1.660     raeburn  13433: }
                   13434: 
1.1071    raeburn  13435: sub get_dependency_details {
                   13436:     my ($currfile,$currsubfile,$embed_file) = @_;
                   13437:     my ($size,$mtime,$showsize,$showmtime);
                   13438:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   13439:         if ($embed_file =~ m{/}) {
                   13440:             my ($path,$fname) = split(/\//,$embed_file);
                   13441:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   13442:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   13443:             }
                   13444:         } else {
                   13445:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   13446:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   13447:             }
                   13448:         }
                   13449:         $showsize = $size/1024.0;
                   13450:         $showsize = sprintf("%.1f",$showsize);
                   13451:         if ($mtime > 0) {
                   13452:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   13453:         }
                   13454:     }
                   13455:     return ($showsize,$showmtime);
                   13456: }
                   13457: 
                   13458: sub ask_embedded_js {
                   13459:     return <<"END";
                   13460: <script type="text/javascript"">
                   13461: // <![CDATA[
                   13462: function toggleBrowse(counter) {
                   13463:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   13464:     var fileid = document.getElementById('embedded_item_'+counter);
                   13465:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   13466:     if (chkboxid.checked == true) {
                   13467:         uploaddivid.style.display='block';
                   13468:     } else {
                   13469:         uploaddivid.style.display='none';
                   13470:         fileid.value = '';
                   13471:     }
                   13472: }
                   13473: // ]]>
                   13474: </script>
                   13475: 
                   13476: END
                   13477: }
                   13478: 
1.661     raeburn  13479: sub upload_embedded {
                   13480:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  13481:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   13482:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  13483:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   13484:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   13485:         my $orig_uploaded_filename =
                   13486:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  13487:         foreach my $type ('orig','ref','attrib','codebase') {
                   13488:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   13489:                 $env{'form.embedded_'.$type.'_'.$i} =
                   13490:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   13491:             }
                   13492:         }
1.661     raeburn  13493:         my ($path,$fname) =
                   13494:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   13495:         # no path, whole string is fname
                   13496:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   13497:         $fname = &Apache::lonnet::clean_filename($fname);
                   13498:         # See if there is anything left
                   13499:         next if ($fname eq '');
                   13500: 
                   13501:         # Check if file already exists as a file or directory.
                   13502:         my ($state,$msg);
                   13503:         if ($context eq 'portfolio') {
                   13504:             my $port_path = $dirpath;
                   13505:             if ($group ne '') {
                   13506:                 $port_path = "groups/$group/$port_path";
                   13507:             }
1.987     raeburn  13508:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   13509:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  13510:                                               $dir_root,$port_path,$disk_quota,
                   13511:                                               $current_disk_usage,$uname,$udom);
                   13512:             if ($state eq 'will_exceed_quota'
1.984     raeburn  13513:                 || $state eq 'file_locked') {
1.661     raeburn  13514:                 $output .= $msg;
                   13515:                 next;
                   13516:             }
                   13517:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   13518:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   13519:             if ($state eq 'exists') {
                   13520:                 $output .= $msg;
                   13521:                 next;
                   13522:             }
                   13523:         }
                   13524:         # Check if extension is valid
                   13525:         if (($fname =~ /\.(\w+)$/) &&
                   13526:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   13527:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   13528:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  13529:             next;
                   13530:         } elsif (($fname =~ /\.(\w+)$/) &&
                   13531:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  13532:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  13533:             next;
                   13534:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   13535:             $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  13536:             next;
                   13537:         }
                   13538:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  13539:         my $subdir = $path;
                   13540:         $subdir =~ s{/+$}{};
1.661     raeburn  13541:         if ($context eq 'portfolio') {
1.984     raeburn  13542:             my $result;
                   13543:             if ($state eq 'existingfile') {
                   13544:                 $result=
                   13545:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  13546:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  13547:             } else {
1.984     raeburn  13548:                 $result=
                   13549:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  13550:                                                     $dirpath.
1.1123    raeburn  13551:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  13552:                 if ($result !~ m|^/uploaded/|) {
                   13553:                     $output .= '<span class="LC_error">'
                   13554:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13555:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13556:                                .'</span><br />';
                   13557:                     next;
                   13558:                 } else {
1.987     raeburn  13559:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13560:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  13561:                 }
1.661     raeburn  13562:             }
1.1123    raeburn  13563:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  13564:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   13565:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  13566:             my $result =
1.1126    raeburn  13567:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  13568:             if ($result !~ m|^/uploaded/|) {
                   13569:                 $output .= '<span class="LC_error">'
                   13570:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13571:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13572:                            .'</span><br />';
                   13573:                     next;
                   13574:             } else {
                   13575:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13576:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  13577:                 if ($context eq 'syllabus') {
                   13578:                     &Apache::lonnet::make_public_indefinitely($result);
                   13579:                 }
1.987     raeburn  13580:             }
1.661     raeburn  13581:         } else {
                   13582: # Save the file
                   13583:             my $target = $env{'form.embedded_item_'.$i};
                   13584:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   13585:             my $dest = $fullpath.$fname;
                   13586:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  13587:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  13588:             my $count;
                   13589:             my $filepath = $dir_root;
1.1027    raeburn  13590:             foreach my $subdir (@parts) {
                   13591:                 $filepath .= "/$subdir";
                   13592:                 if (!-e $filepath) {
1.661     raeburn  13593:                     mkdir($filepath,0770);
                   13594:                 }
                   13595:             }
                   13596:             my $fh;
                   13597:             if (!open($fh,'>'.$dest)) {
                   13598:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   13599:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  13600:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   13601:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13602:                            '</span><br />';
                   13603:             } else {
                   13604:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   13605:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   13606:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  13607:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   13608:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13609:                               '</span><br />';
                   13610:                 } else {
1.987     raeburn  13611:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13612:                                $url.'</span>').'<br />';
                   13613:                     unless ($context eq 'testbank') {
                   13614:                         $footer .= &mt('View embedded file: [_1]',
                   13615:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   13616:                     }
                   13617:                 }
                   13618:                 close($fh);
                   13619:             }
                   13620:         }
                   13621:         if ($env{'form.embedded_ref_'.$i}) {
                   13622:             $pathchange{$i} = 1;
                   13623:         }
                   13624:     }
                   13625:     if ($output) {
                   13626:         $output = '<p>'.$output.'</p>';
                   13627:     }
                   13628:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   13629:     $returnflag = 'ok';
1.1071    raeburn  13630:     my $numpathchgs = scalar(keys(%pathchange));
                   13631:     if ($numpathchgs > 0) {
1.987     raeburn  13632:         if ($context eq 'portfolio') {
                   13633:             $output .= '<p>'.&mt('or').'</p>';
                   13634:         } elsif ($context eq 'testbank') {
1.1071    raeburn  13635:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   13636:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  13637:             $returnflag = 'modify_orightml';
                   13638:         }
                   13639:     }
1.1071    raeburn  13640:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  13641: }
                   13642: 
                   13643: sub modify_html_form {
                   13644:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   13645:     my $end = 0;
                   13646:     my $modifyform;
                   13647:     if ($context eq 'upload_embedded') {
                   13648:         return unless (ref($pathchange) eq 'HASH');
                   13649:         if ($env{'form.number_embedded_items'}) {
                   13650:             $end += $env{'form.number_embedded_items'};
                   13651:         }
                   13652:         if ($env{'form.number_pathchange_items'}) {
                   13653:             $end += $env{'form.number_pathchange_items'};
                   13654:         }
                   13655:         if ($end) {
                   13656:             for (my $i=0; $i<$end; $i++) {
                   13657:                 if ($i < $env{'form.number_embedded_items'}) {
                   13658:                     next unless($pathchange->{$i});
                   13659:                 }
                   13660:                 $modifyform .=
                   13661:                     &start_data_table_row().
                   13662:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   13663:                     'checked="checked" /></td>'.
                   13664:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   13665:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   13666:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   13667:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   13668:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   13669:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   13670:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   13671:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   13672:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   13673:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   13674:                     &end_data_table_row();
1.1071    raeburn  13675:             }
1.987     raeburn  13676:         }
                   13677:     } else {
                   13678:         $modifyform = $pathchgtable;
                   13679:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   13680:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   13681:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13682:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   13683:         }
                   13684:     }
                   13685:     if ($modifyform) {
1.1071    raeburn  13686:         if ($actionurl eq '/adm/dependencies') {
                   13687:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   13688:         }
1.987     raeburn  13689:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   13690:                '<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".
                   13691:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   13692:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   13693:                '</ol></p>'."\n".'<p>'.
                   13694:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   13695:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   13696:                &start_data_table()."\n".
                   13697:                &start_data_table_header_row().
                   13698:                '<th>'.&mt('Change?').'</th>'.
                   13699:                '<th>'.&mt('Current reference').'</th>'.
                   13700:                '<th>'.&mt('Required reference').'</th>'.
                   13701:                &end_data_table_header_row()."\n".
                   13702:                $modifyform.
                   13703:                &end_data_table().'<br />'."\n".$hiddenstate.
                   13704:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   13705:                '</form>'."\n";
                   13706:     }
                   13707:     return;
                   13708: }
                   13709: 
                   13710: sub modify_html_refs {
1.1123    raeburn  13711:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  13712:     my $container;
                   13713:     if ($context eq 'portfolio') {
                   13714:         $container = $env{'form.container'};
                   13715:     } elsif ($context eq 'coursedoc') {
                   13716:         $container = $env{'form.primaryurl'};
1.1071    raeburn  13717:     } elsif ($context eq 'manage_dependencies') {
                   13718:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   13719:         $container = "/$container";
1.1123    raeburn  13720:     } elsif ($context eq 'syllabus') {
                   13721:         $container = $url;
1.987     raeburn  13722:     } else {
1.1027    raeburn  13723:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  13724:     }
                   13725:     my (%allfiles,%codebase,$output,$content);
                   13726:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  13727:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  13728:         if (wantarray) {
                   13729:             return ('',0,0); 
                   13730:         } else {
                   13731:             return;
                   13732:         }
                   13733:     }
                   13734:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13735:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  13736:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   13737:             if (wantarray) {
                   13738:                 return ('',0,0);
                   13739:             } else {
                   13740:                 return;
                   13741:             }
                   13742:         } 
1.987     raeburn  13743:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  13744:         if ($content eq '-1') {
                   13745:             if (wantarray) {
                   13746:                 return ('',0,0);
                   13747:             } else {
                   13748:                 return;
                   13749:             }
                   13750:         }
1.987     raeburn  13751:     } else {
1.1071    raeburn  13752:         unless ($container =~ /^\Q$dir_root\E/) {
                   13753:             if (wantarray) {
                   13754:                 return ('',0,0);
                   13755:             } else {
                   13756:                 return;
                   13757:             }
                   13758:         } 
1.1317    raeburn  13759:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13760:             $content = join('', <$fh>);
                   13761:             close($fh);
                   13762:         } else {
1.1071    raeburn  13763:             if (wantarray) {
                   13764:                 return ('',0,0);
                   13765:             } else {
                   13766:                 return;
                   13767:             }
1.987     raeburn  13768:         }
                   13769:     }
                   13770:     my ($count,$codebasecount) = (0,0);
                   13771:     my $mm = new File::MMagic;
                   13772:     my $mime_type = $mm->checktype_contents($content);
                   13773:     if ($mime_type eq 'text/html') {
                   13774:         my $parse_result = 
                   13775:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13776:                                                     \%codebase,\$content);
                   13777:         if ($parse_result eq 'ok') {
                   13778:             foreach my $i (@changes) {
                   13779:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13780:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13781:                 if ($allfiles{$ref}) {
                   13782:                     my $newname =  $orig;
                   13783:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13784:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13785:                     if ($attrib_regexp =~ /:/) {
                   13786:                         $attrib_regexp =~ s/\:/|/g;
                   13787:                     }
                   13788:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13789:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13790:                         $count += $numchg;
1.1123    raeburn  13791:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13792:                         delete($allfiles{$ref});
1.987     raeburn  13793:                     }
                   13794:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13795:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13796:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13797:                         $codebasecount ++;
                   13798:                     }
                   13799:                 }
                   13800:             }
1.1123    raeburn  13801:             my $skiprewrites;
1.987     raeburn  13802:             if ($count || $codebasecount) {
                   13803:                 my $saveresult;
1.1071    raeburn  13804:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13805:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13806:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13807:                     if ($url eq $container) {
                   13808:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13809:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13810:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13811:                                             $fname.'</span>').'</p>';
1.987     raeburn  13812:                     } else {
                   13813:                          $output = '<p class="LC_error">'.
                   13814:                                    &mt('Error: update failed for: [_1].',
                   13815:                                    '<span class="LC_filename">'.
                   13816:                                    $container.'</span>').'</p>';
                   13817:                     }
1.1123    raeburn  13818:                     if ($context eq 'syllabus') {
                   13819:                         unless ($saveresult eq 'ok') {
                   13820:                             $skiprewrites = 1;
                   13821:                         }
                   13822:                     }
1.987     raeburn  13823:                 } else {
1.1317    raeburn  13824:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13825:                         print $fh $content;
                   13826:                         close($fh);
                   13827:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13828:                                   $count,'<span class="LC_filename">'.
                   13829:                                   $container.'</span>').'</p>';
1.661     raeburn  13830:                     } else {
1.987     raeburn  13831:                          $output = '<p class="LC_error">'.
                   13832:                                    &mt('Error: could not update [_1].',
                   13833:                                    '<span class="LC_filename">'.
                   13834:                                    $container.'</span>').'</p>';
1.661     raeburn  13835:                     }
                   13836:                 }
                   13837:             }
1.1123    raeburn  13838:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13839:                 my ($actionurl,$state);
                   13840:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13841:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13842:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13843:                                               \%codebase,
                   13844:                                               {'context' => 'rewrites',
                   13845:                                                'ignore_remote_references' => 1,});
                   13846:                 if (ref($mapping) eq 'HASH') {
                   13847:                     my $rewrites = 0;
                   13848:                     foreach my $key (keys(%{$mapping})) {
                   13849:                         next if ($key =~ m{^https?://});
                   13850:                         my $ref = $mapping->{$key};
                   13851:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13852:                         my $attrib;
                   13853:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13854:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13855:                         }
                   13856:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13857:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13858:                             $rewrites += $numchg;
                   13859:                         }
                   13860:                     }
                   13861:                     if ($rewrites) {
                   13862:                         my $saveresult; 
                   13863:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13864:                         if ($url eq $container) {
                   13865:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13866:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13867:                                             $count,'<span class="LC_filename">'.
                   13868:                                             $fname.'</span>').'</p>';
                   13869:                         } else {
                   13870:                             $output .= '<p class="LC_error">'.
                   13871:                                        &mt('Error: could not update links in [_1].',
                   13872:                                        '<span class="LC_filename">'.
                   13873:                                        $container.'</span>').'</p>';
                   13874: 
                   13875:                         }
                   13876:                     }
                   13877:                 }
                   13878:             }
1.987     raeburn  13879:         } else {
                   13880:             &logthis('Failed to parse '.$container.
                   13881:                      ' to modify references: '.$parse_result);
1.661     raeburn  13882:         }
                   13883:     }
1.1071    raeburn  13884:     if (wantarray) {
                   13885:         return ($output,$count,$codebasecount);
                   13886:     } else {
                   13887:         return $output;
                   13888:     }
1.661     raeburn  13889: }
                   13890: 
                   13891: sub check_for_existing {
                   13892:     my ($path,$fname,$element) = @_;
                   13893:     my ($state,$msg);
                   13894:     if (-d $path.'/'.$fname) {
                   13895:         $state = 'exists';
                   13896:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13897:     } elsif (-e $path.'/'.$fname) {
                   13898:         $state = 'exists';
                   13899:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13900:     }
                   13901:     if ($state eq 'exists') {
                   13902:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13903:     }
                   13904:     return ($state,$msg);
                   13905: }
                   13906: 
                   13907: sub check_for_upload {
                   13908:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13909:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13910:     my $filesize = length($env{'form.'.$element});
                   13911:     if (!$filesize) {
                   13912:         my $msg = '<span class="LC_error">'.
                   13913:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13914:                       '<span class="LC_filename">'.$fname.'</span>',
                   13915:                       $filesize).'<br />'.
1.1007    raeburn  13916:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13917:                   '</span>';
                   13918:         return ('zero_bytes',$msg);
                   13919:     }
                   13920:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13921:     my $getpropath = 1;
1.1021    raeburn  13922:     my ($dirlistref,$listerror) =
                   13923:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13924:     my $found_file = 0;
                   13925:     my $locked_file = 0;
1.991     raeburn  13926:     my @lockers;
                   13927:     my $navmap;
                   13928:     if ($env{'request.course.id'}) {
                   13929:         $navmap = Apache::lonnavmaps::navmap->new();
                   13930:     }
1.1021    raeburn  13931:     if (ref($dirlistref) eq 'ARRAY') {
                   13932:         foreach my $line (@{$dirlistref}) {
                   13933:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13934:             if ($file_name eq $fname){
                   13935:                 $file_name = $path.$file_name;
                   13936:                 if ($group ne '') {
                   13937:                     $file_name = $group.$file_name;
                   13938:                 }
                   13939:                 $found_file = 1;
                   13940:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13941:                     foreach my $lock (@lockers) {
                   13942:                         if (ref($lock) eq 'ARRAY') {
                   13943:                             my ($symb,$crsid) = @{$lock};
                   13944:                             if ($crsid eq $env{'request.course.id'}) {
                   13945:                                 if (ref($navmap)) {
                   13946:                                     my $res = $navmap->getBySymb($symb);
                   13947:                                     foreach my $part (@{$res->parts()}) { 
                   13948:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13949:                                         unless (($slot_status == $res->RESERVED) ||
                   13950:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13951:                                             $locked_file = 1;
                   13952:                                         }
1.991     raeburn  13953:                                     }
1.1021    raeburn  13954:                                 } else {
                   13955:                                     $locked_file = 1;
1.991     raeburn  13956:                                 }
                   13957:                             } else {
                   13958:                                 $locked_file = 1;
                   13959:                             }
                   13960:                         }
1.1021    raeburn  13961:                    }
                   13962:                 } else {
                   13963:                     my @info = split(/\&/,$rest);
                   13964:                     my $currsize = $info[6]/1000;
                   13965:                     if ($currsize < $filesize) {
                   13966:                         my $extra = $filesize - $currsize;
                   13967:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13968:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13969:                                       &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   13970:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13971:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13972:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13973:                             return ('will_exceed_quota',$msg);
                   13974:                         }
1.984     raeburn  13975:                     }
                   13976:                 }
1.661     raeburn  13977:             }
                   13978:         }
                   13979:     }
                   13980:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13981:         my $msg = '<p class="LC_warning">'.
                   13982:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13983:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13984:         return ('will_exceed_quota',$msg);
                   13985:     } elsif ($found_file) {
                   13986:         if ($locked_file) {
1.1179    bisitz   13987:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13988:             $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   13989:             $msg .= '</p>';
1.661     raeburn  13990:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13991:             return ('file_locked',$msg);
                   13992:         } else {
1.1179    bisitz   13993:             my $msg = '<p class="LC_error">';
1.984     raeburn  13994:             $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   13995:             $msg .= '</p>';
1.984     raeburn  13996:             return ('existingfile',$msg);
1.661     raeburn  13997:         }
                   13998:     }
                   13999: }
                   14000: 
1.987     raeburn  14001: sub check_for_traversal {
                   14002:     my ($path,$url,$toplevel) = @_;
                   14003:     my @parts=split(/\//,$path);
                   14004:     my $cleanpath;
                   14005:     my $fullpath = $url;
                   14006:     for (my $i=0;$i<@parts;$i++) {
                   14007:         next if ($parts[$i] eq '.');
                   14008:         if ($parts[$i] eq '..') {
                   14009:             $fullpath =~ s{([^/]+/)$}{};
                   14010:         } else {
                   14011:             $fullpath .= $parts[$i].'/';
                   14012:         }
                   14013:     }
                   14014:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   14015:         $cleanpath = $1;
                   14016:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   14017:         my $curr_toprel = $1;
                   14018:         my @parts = split(/\//,$curr_toprel);
                   14019:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   14020:         my @urlparts = split(/\//,$url_toprel);
                   14021:         my $doubledots;
                   14022:         my $startdiff = -1;
                   14023:         for (my $i=0; $i<@urlparts; $i++) {
                   14024:             if ($startdiff == -1) {
                   14025:                 unless ($urlparts[$i] eq $parts[$i]) {
                   14026:                     $startdiff = $i;
                   14027:                     $doubledots .= '../';
                   14028:                 }
                   14029:             } else {
                   14030:                 $doubledots .= '../';
                   14031:             }
                   14032:         }
                   14033:         if ($startdiff > -1) {
                   14034:             $cleanpath = $doubledots;
                   14035:             for (my $i=$startdiff; $i<@parts; $i++) {
                   14036:                 $cleanpath .= $parts[$i].'/';
                   14037:             }
                   14038:         }
                   14039:     }
                   14040:     $cleanpath =~ s{(/)$}{};
                   14041:     return $cleanpath;
                   14042: }
1.31      albertel 14043: 
1.1053    raeburn  14044: sub is_archive_file {
                   14045:     my ($mimetype) = @_;
                   14046:     if (($mimetype eq 'application/octet-stream') ||
                   14047:         ($mimetype eq 'application/x-stuffit') ||
                   14048:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   14049:         return 1;
                   14050:     }
                   14051:     return;
                   14052: }
                   14053: 
                   14054: sub decompress_form {
1.1065    raeburn  14055:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  14056:     my %lt = &Apache::lonlocal::texthash (
                   14057:         this => 'This file is an archive file.',
1.1067    raeburn  14058:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  14059:         itsc => 'Its contents are as follows:',
1.1053    raeburn  14060:         youm => 'You may wish to extract its contents.',
                   14061:         extr => 'Extract contents',
1.1067    raeburn  14062:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   14063:         proa => 'Process automatically?',
1.1053    raeburn  14064:         yes  => 'Yes',
                   14065:         no   => 'No',
1.1067    raeburn  14066:         fold => 'Title for folder containing movie',
                   14067:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  14068:     );
1.1065    raeburn  14069:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  14070:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  14071:     my $info = &list_archive_contents($fileloc,\@paths);
                   14072:     if (@paths) {
                   14073:         foreach my $path (@paths) {
                   14074:             $path =~ s{^/}{};
1.1067    raeburn  14075:             if ($path =~ m{^([^/]+)/$}) {
                   14076:                 $topdir = $1;
                   14077:             }
1.1065    raeburn  14078:             if ($path =~ m{^([^/]+)/}) {
                   14079:                 $toplevel{$1} = $path;
                   14080:             } else {
                   14081:                 $toplevel{$path} = $path;
                   14082:             }
                   14083:         }
                   14084:     }
1.1067    raeburn  14085:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  14086:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  14087:                         "$topdir/media/",
                   14088:                         "$topdir/media/$topdir.mp4",
                   14089:                         "$topdir/media/FirstFrame.png",
                   14090:                         "$topdir/media/player.swf",
                   14091:                         "$topdir/media/swfobject.js",
                   14092:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  14093:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  14094:                          "$topdir/$topdir.mp4",
                   14095:                          "$topdir/$topdir\_config.xml",
                   14096:                          "$topdir/$topdir\_controller.swf",
                   14097:                          "$topdir/$topdir\_embed.css",
                   14098:                          "$topdir/$topdir\_First_Frame.png",
                   14099:                          "$topdir/$topdir\_player.html",
                   14100:                          "$topdir/$topdir\_Thumbnails.png",
                   14101:                          "$topdir/playerProductInstall.swf",
                   14102:                          "$topdir/scripts/",
                   14103:                          "$topdir/scripts/config_xml.js",
                   14104:                          "$topdir/scripts/handlebars.js",
                   14105:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   14106:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   14107:                          "$topdir/scripts/modernizr.js",
                   14108:                          "$topdir/scripts/player-min.js",
                   14109:                          "$topdir/scripts/swfobject.js",
                   14110:                          "$topdir/skins/",
                   14111:                          "$topdir/skins/configuration_express.xml",
                   14112:                          "$topdir/skins/express_show/",
                   14113:                          "$topdir/skins/express_show/player-min.css",
                   14114:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  14115:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   14116:                          "$topdir/$topdir.mp4",
                   14117:                          "$topdir/$topdir\_config.xml",
                   14118:                          "$topdir/$topdir\_controller.swf",
                   14119:                          "$topdir/$topdir\_embed.css",
                   14120:                          "$topdir/$topdir\_First_Frame.png",
                   14121:                          "$topdir/$topdir\_player.html",
                   14122:                          "$topdir/$topdir\_Thumbnails.png",
                   14123:                          "$topdir/playerProductInstall.swf",
                   14124:                          "$topdir/scripts/",
                   14125:                          "$topdir/scripts/config_xml.js",
                   14126:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   14127:                          "$topdir/skins/",
                   14128:                          "$topdir/skins/configuration_express.xml",
                   14129:                          "$topdir/skins/express_show/",
                   14130:                          "$topdir/skins/express_show/spritesheet.min.css",
                   14131:                          "$topdir/skins/express_show/spritesheet.png",
                   14132:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  14133:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  14134:         if (@diffs == 0) {
1.1164    raeburn  14135:             $is_camtasia = 6;
                   14136:         } else {
1.1197    raeburn  14137:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  14138:             if (@diffs == 0) {
                   14139:                 $is_camtasia = 8;
1.1197    raeburn  14140:             } else {
                   14141:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   14142:                 if (@diffs == 0) {
                   14143:                     $is_camtasia = 8;
                   14144:                 }
1.1164    raeburn  14145:             }
1.1067    raeburn  14146:         }
                   14147:     }
                   14148:     my $output;
                   14149:     if ($is_camtasia) {
                   14150:         $output = <<"ENDCAM";
                   14151: <script type="text/javascript" language="Javascript">
                   14152: // <![CDATA[
                   14153: 
                   14154: function camtasiaToggle() {
                   14155:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   14156:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  14157:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  14158:                 document.getElementById('camtasia_titles').style.display='block';
                   14159:             } else {
                   14160:                 document.getElementById('camtasia_titles').style.display='none';
                   14161:             }
                   14162:         }
                   14163:     }
                   14164:     return;
                   14165: }
                   14166: 
                   14167: // ]]>
                   14168: </script>
                   14169: <p>$lt{'camt'}</p>
                   14170: ENDCAM
1.1065    raeburn  14171:     } else {
1.1067    raeburn  14172:         $output = '<p>'.$lt{'this'};
                   14173:         if ($info eq '') {
                   14174:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   14175:         } else {
                   14176:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   14177:                        '<div><pre>'.$info.'</pre></div>';
                   14178:         }
1.1065    raeburn  14179:     }
1.1067    raeburn  14180:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  14181:     my $duplicates;
                   14182:     my $num = 0;
                   14183:     if (ref($dirlist) eq 'ARRAY') {
                   14184:         foreach my $item (@{$dirlist}) {
                   14185:             if (ref($item) eq 'ARRAY') {
                   14186:                 if (exists($toplevel{$item->[0]})) {
                   14187:                     $duplicates .= 
                   14188:                         &start_data_table_row().
                   14189:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14190:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   14191:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14192:                         'value="1" />'.&mt('Yes').'</label>'.
                   14193:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   14194:                         '<td>'.$item->[0].'</td>';
                   14195:                     if ($item->[2]) {
                   14196:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   14197:                     } else {
                   14198:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   14199:                     }
                   14200:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   14201:                                    '<td>'.
                   14202:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   14203:                                    '</td>'.
                   14204:                                    &end_data_table_row();
                   14205:                     $num ++;
                   14206:                 }
                   14207:             }
                   14208:         }
                   14209:     }
                   14210:     my $itemcount;
                   14211:     if (@paths > 0) {
                   14212:         $itemcount = scalar(@paths);
                   14213:     } else {
                   14214:         $itemcount = 1;
                   14215:     }
1.1067    raeburn  14216:     if ($is_camtasia) {
                   14217:         $output .= $lt{'auto'}.'<br />'.
                   14218:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  14219:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  14220:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   14221:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   14222:                    $lt{'no'}.'</label></span><br />'.
                   14223:                    '<div id="camtasia_titles" style="display:block">'.
                   14224:                    &Apache::lonhtmlcommon::start_pick_box().
                   14225:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   14226:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   14227:                    &Apache::lonhtmlcommon::row_closure().
                   14228:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   14229:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   14230:                    &Apache::lonhtmlcommon::row_closure(1).
                   14231:                    &Apache::lonhtmlcommon::end_pick_box().
                   14232:                    '</div>';
                   14233:     }
1.1065    raeburn  14234:     $output .= 
                   14235:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  14236:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   14237:         "\n";
1.1065    raeburn  14238:     if ($duplicates ne '') {
                   14239:         $output .= '<p><span class="LC_warning">'.
                   14240:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   14241:                    &start_data_table().
                   14242:                    &start_data_table_header_row().
                   14243:                    '<th>'.&mt('Overwrite?').'</th>'.
                   14244:                    '<th>'.&mt('Name').'</th>'.
                   14245:                    '<th>'.&mt('Type').'</th>'.
                   14246:                    '<th>'.&mt('Size').'</th>'.
                   14247:                    '<th>'.&mt('Last modified').'</th>'.
                   14248:                    &end_data_table_header_row().
                   14249:                    $duplicates.
                   14250:                    &end_data_table().
                   14251:                    '</p>';
                   14252:     }
1.1067    raeburn  14253:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  14254:     if (ref($hiddenelements) eq 'HASH') {
                   14255:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   14256:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   14257:         }
                   14258:     }
                   14259:     $output .= <<"END";
1.1067    raeburn  14260: <br />
1.1053    raeburn  14261: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   14262: </form>
                   14263: $noextract
                   14264: END
                   14265:     return $output;
                   14266: }
                   14267: 
1.1065    raeburn  14268: sub decompression_utility {
                   14269:     my ($program) = @_;
                   14270:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   14271:     my $location;
                   14272:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   14273:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   14274:                          '/usr/sbin/') {
                   14275:             if (-x $dir.$program) {
                   14276:                 $location = $dir.$program;
                   14277:                 last;
                   14278:             }
                   14279:         }
                   14280:     }
                   14281:     return $location;
                   14282: }
                   14283: 
                   14284: sub list_archive_contents {
                   14285:     my ($file,$pathsref) = @_;
                   14286:     my (@cmd,$output);
                   14287:     my $needsregexp;
                   14288:     if ($file =~ /\.zip$/) {
                   14289:         @cmd = (&decompression_utility('unzip'),"-l");
                   14290:         $needsregexp = 1;
                   14291:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   14292:              ($file =~ /\.tgz$/)) {
                   14293:         @cmd = (&decompression_utility('tar'),"-ztf");
                   14294:     } elsif ($file =~ /\.tar\.bz2$/) {
                   14295:         @cmd = (&decompression_utility('tar'),"-jtf");
                   14296:     } elsif ($file =~ m|\.tar$|) {
                   14297:         @cmd = (&decompression_utility('tar'),"-tf");
                   14298:     }
                   14299:     if (@cmd) {
                   14300:         undef($!);
                   14301:         undef($@);
                   14302:         if (open(my $fh,"-|", @cmd, $file)) {
                   14303:             while (my $line = <$fh>) {
                   14304:                 $output .= $line;
                   14305:                 chomp($line);
                   14306:                 my $item;
                   14307:                 if ($needsregexp) {
                   14308:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   14309:                 } else {
                   14310:                     $item = $line;
                   14311:                 }
                   14312:                 if ($item ne '') {
                   14313:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   14314:                         push(@{$pathsref},$item);
                   14315:                     } 
                   14316:                 }
                   14317:             }
                   14318:             close($fh);
                   14319:         }
                   14320:     }
                   14321:     return $output;
                   14322: }
                   14323: 
1.1053    raeburn  14324: sub decompress_uploaded_file {
                   14325:     my ($file,$dir) = @_;
                   14326:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   14327:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   14328:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   14329:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   14330:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   14331:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   14332:     my $decompressed = $env{'cgi.decompressed'};
                   14333:     &Apache::lonnet::delenv('cgi.file');
                   14334:     &Apache::lonnet::delenv('cgi.dir');
                   14335:     &Apache::lonnet::delenv('cgi.decompressed');
                   14336:     return ($decompressed,$result);
                   14337: }
                   14338: 
1.1055    raeburn  14339: sub process_decompression {
                   14340:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  14341:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   14342:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14343:                &mt('Unexpected file path.').'</p>'."\n";
                   14344:     }
                   14345:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   14346:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14347:                &mt('Unexpected course context.').'</p>'."\n";
                   14348:     }
1.1293    raeburn  14349:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  14350:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14351:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   14352:     }
1.1055    raeburn  14353:     my ($dir,$error,$warning,$output);
1.1180    raeburn  14354:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   14355:         $error = &mt('Filename not a supported archive file type.').
                   14356:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  14357:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   14358:     } else {
                   14359:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14360:         if ($docuhome eq 'no_host') {
                   14361:             $error = &mt('Could not determine home server for course.');
                   14362:         } else {
                   14363:             my @ids=&Apache::lonnet::current_machine_ids();
                   14364:             my $currdir = "$dir_root/$destination";
                   14365:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14366:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   14367:                        "$dir_root/$destination";
                   14368:             } else {
                   14369:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   14370:                        "$dir_root/$docudom/$docuname/$destination";
                   14371:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   14372:                     $error = &mt('Archive file not found.');
                   14373:                 }
                   14374:             }
1.1065    raeburn  14375:             my (@to_overwrite,@to_skip);
                   14376:             if ($env{'form.archive_overwrite_total'} > 0) {
                   14377:                 my $total = $env{'form.archive_overwrite_total'};
                   14378:                 for (my $i=0; $i<$total; $i++) {
                   14379:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   14380:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   14381:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   14382:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   14383:                     }
                   14384:                 }
                   14385:             }
                   14386:             my $numskip = scalar(@to_skip);
1.1292    raeburn  14387:             my $numoverwrite = scalar(@to_overwrite);
                   14388:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  14389:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   14390:             } elsif ($dir eq '') {
1.1055    raeburn  14391:                 $error = &mt('Directory containing archive file unavailable.');
                   14392:             } elsif (!$error) {
1.1065    raeburn  14393:                 my ($decompressed,$display);
1.1292    raeburn  14394:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  14395:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   14396:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  14397:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   14398:                         ($decompressed,$display) = 
                   14399:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   14400:                         foreach my $item (@to_skip) {
                   14401:                             if (($item ne '') && ($item !~ /\.\./)) {
                   14402:                                 if (-f "$dir/$tempdir/$item") { 
                   14403:                                     unlink("$dir/$tempdir/$item");
                   14404:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  14405:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  14406:                                 }
                   14407:                             }
                   14408:                         }
                   14409:                         foreach my $item (@to_overwrite) {
                   14410:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   14411:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   14412:                                     if (-f "$dir/$item") {
                   14413:                                         unlink("$dir/$item");
                   14414:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  14415:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  14416:                                     }
                   14417:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   14418:                                 }
1.1065    raeburn  14419:                             }
                   14420:                         }
1.1292    raeburn  14421:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  14422:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  14423:                         }
1.1065    raeburn  14424:                     }
                   14425:                 } else {
                   14426:                     ($decompressed,$display) = 
                   14427:                         &decompress_uploaded_file($file,$dir);
                   14428:                 }
1.1055    raeburn  14429:                 if ($decompressed eq 'ok') {
1.1065    raeburn  14430:                     $output = '<p class="LC_info">'.
                   14431:                               &mt('Files extracted successfully from archive.').
                   14432:                               '</p>'."\n";
1.1055    raeburn  14433:                     my ($warning,$result,@contents);
                   14434:                     my ($newdirlistref,$newlisterror) =
                   14435:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   14436:                                                  $docuname,1);
                   14437:                     my (%is_dir,%changes,@newitems);
                   14438:                     my $dirptr = 16384;
1.1065    raeburn  14439:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  14440:                         foreach my $dir_line (@{$newdirlistref}) {
                   14441:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  14442:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  14443:                                 push(@newitems,$item);
                   14444:                                 if ($dirptr&$testdir) {
                   14445:                                     $is_dir{$item} = 1;
                   14446:                                 }
                   14447:                                 $changes{$item} = 1;
                   14448:                             }
                   14449:                         }
                   14450:                     }
                   14451:                     if (keys(%changes) > 0) {
                   14452:                         foreach my $item (sort(@newitems)) {
                   14453:                             if ($changes{$item}) {
                   14454:                                 push(@contents,$item);
                   14455:                             }
                   14456:                         }
                   14457:                     }
                   14458:                     if (@contents > 0) {
1.1067    raeburn  14459:                         my $wantform;
                   14460:                         unless ($env{'form.autoextract_camtasia'}) {
                   14461:                             $wantform = 1;
                   14462:                         }
1.1056    raeburn  14463:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  14464:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   14465:                                                                 $currdir,\%is_dir,
                   14466:                                                                 \%children,\%parent,
1.1056    raeburn  14467:                                                                 \@contents,\%dirorder,
                   14468:                                                                 \%titles,$wantform);
1.1055    raeburn  14469:                         if ($datatable ne '') {
                   14470:                             $output .= &archive_options_form('decompressed',$datatable,
                   14471:                                                              $count,$hiddenelem);
1.1065    raeburn  14472:                             my $startcount = 6;
1.1055    raeburn  14473:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  14474:                                                            \%titles,\%children);
1.1055    raeburn  14475:                         }
1.1067    raeburn  14476:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  14477:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  14478:                             my %displayed;
                   14479:                             my $total = 1;
                   14480:                             $env{'form.archive_directory'} = [];
                   14481:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   14482:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   14483:                                 $path =~ s{/$}{};
                   14484:                                 my $item;
                   14485:                                 if ($path ne '') {
                   14486:                                     $item = "$path/$titles{$i}";
                   14487:                                 } else {
                   14488:                                     $item = $titles{$i};
                   14489:                                 }
                   14490:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   14491:                                 if ($item eq $contents[0]) {
                   14492:                                     push(@{$env{'form.archive_directory'}},$i);
                   14493:                                     $env{'form.archive_'.$i} = 'display';
                   14494:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   14495:                                     $displayed{'folder'} = $i;
1.1164    raeburn  14496:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   14497:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  14498:                                     $env{'form.archive_'.$i} = 'display';
                   14499:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   14500:                                     $displayed{'web'} = $i;
                   14501:                                 } else {
1.1164    raeburn  14502:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   14503:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   14504:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  14505:                                         push(@{$env{'form.archive_directory'}},$i);
                   14506:                                     }
                   14507:                                     $env{'form.archive_'.$i} = 'dependency';
                   14508:                                 }
                   14509:                                 $total ++;
                   14510:                             }
                   14511:                             for (my $i=1; $i<$total; $i++) {
                   14512:                                 next if ($i == $displayed{'web'});
                   14513:                                 next if ($i == $displayed{'folder'});
                   14514:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   14515:                             }
                   14516:                             $env{'form.phase'} = 'decompress_cleanup';
                   14517:                             $env{'form.archivedelete'} = 1;
                   14518:                             $env{'form.archive_count'} = $total-1;
                   14519:                             $output .=
                   14520:                                 &process_extracted_files('coursedocs',$docudom,
                   14521:                                                          $docuname,$destination,
                   14522:                                                          $dir_root,$hiddenelem);
                   14523:                         }
1.1055    raeburn  14524:                     } else {
                   14525:                         $warning = &mt('No new items extracted from archive file.');
                   14526:                     }
                   14527:                 } else {
                   14528:                     $output = $display;
                   14529:                     $error = &mt('An error occurred during extraction from the archive file.');
                   14530:                 }
                   14531:             }
                   14532:         }
                   14533:     }
                   14534:     if ($error) {
                   14535:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14536:                    $error.'</p>'."\n";
                   14537:     }
                   14538:     if ($warning) {
                   14539:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14540:     }
                   14541:     return $output;
                   14542: }
                   14543: 
                   14544: sub get_extracted {
1.1056    raeburn  14545:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   14546:         $titles,$wantform) = @_;
1.1055    raeburn  14547:     my $count = 0;
                   14548:     my $depth = 0;
                   14549:     my $datatable;
1.1056    raeburn  14550:     my @hierarchy;
1.1055    raeburn  14551:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  14552:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   14553:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  14554:     foreach my $item (@{$contents}) {
                   14555:         $count ++;
1.1056    raeburn  14556:         @{$dirorder->{$count}} = @hierarchy;
                   14557:         $titles->{$count} = $item;
1.1055    raeburn  14558:         &archive_hierarchy($depth,$count,$parent,$children);
                   14559:         if ($wantform) {
                   14560:             $datatable .= &archive_row($is_dir->{$item},$item,
                   14561:                                        $currdir,$depth,$count);
                   14562:         }
                   14563:         if ($is_dir->{$item}) {
                   14564:             $depth ++;
1.1056    raeburn  14565:             push(@hierarchy,$count);
                   14566:             $parent->{$depth} = $count;
1.1055    raeburn  14567:             $datatable .=
                   14568:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  14569:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   14570:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  14571:             $depth --;
1.1056    raeburn  14572:             pop(@hierarchy);
1.1055    raeburn  14573:         }
                   14574:     }
                   14575:     return ($count,$datatable);
                   14576: }
                   14577: 
                   14578: sub recurse_extracted_archive {
1.1056    raeburn  14579:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   14580:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  14581:     my $result='';
1.1056    raeburn  14582:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   14583:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   14584:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  14585:         return $result;
                   14586:     }
                   14587:     my $dirptr = 16384;
                   14588:     my ($newdirlistref,$newlisterror) =
                   14589:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   14590:     if (ref($newdirlistref) eq 'ARRAY') {
                   14591:         foreach my $dir_line (@{$newdirlistref}) {
                   14592:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   14593:             unless ($item =~ /^\.+$/) {
                   14594:                 $$count ++;
1.1056    raeburn  14595:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   14596:                 $titles->{$$count} = $item;
1.1055    raeburn  14597:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  14598: 
1.1055    raeburn  14599:                 my $is_dir;
                   14600:                 if ($dirptr&$testdir) {
                   14601:                     $is_dir = 1;
                   14602:                 }
                   14603:                 if ($wantform) {
                   14604:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   14605:                 }
                   14606:                 if ($is_dir) {
                   14607:                     $$depth ++;
1.1056    raeburn  14608:                     push(@{$hierarchy},$$count);
                   14609:                     $parent->{$$depth} = $$count;
1.1055    raeburn  14610:                     $result .=
                   14611:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   14612:                                                    $docuname,$depth,$count,
1.1056    raeburn  14613:                                                    $hierarchy,$dirorder,$children,
                   14614:                                                    $parent,$titles,$wantform);
1.1055    raeburn  14615:                     $$depth --;
1.1056    raeburn  14616:                     pop(@{$hierarchy});
1.1055    raeburn  14617:                 }
                   14618:             }
                   14619:         }
                   14620:     }
                   14621:     return $result;
                   14622: }
                   14623: 
                   14624: sub archive_hierarchy {
                   14625:     my ($depth,$count,$parent,$children) =@_;
                   14626:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   14627:         if (exists($parent->{$depth})) {
                   14628:              $children->{$parent->{$depth}} .= $count.':';
                   14629:         }
                   14630:     }
                   14631:     return;
                   14632: }
                   14633: 
                   14634: sub archive_row {
                   14635:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   14636:     my ($name) = ($item =~ m{([^/]+)$});
                   14637:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  14638:                                        'display'    => 'Add as file',
1.1055    raeburn  14639:                                        'dependency' => 'Include as dependency',
                   14640:                                        'discard'    => 'Discard',
                   14641:                                       );
                   14642:     if ($is_dir) {
1.1059    raeburn  14643:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  14644:     }
1.1056    raeburn  14645:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   14646:     my $offset = 0;
1.1055    raeburn  14647:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  14648:         $offset ++;
1.1065    raeburn  14649:         if ($action ne 'display') {
                   14650:             $offset ++;
                   14651:         }  
1.1055    raeburn  14652:         $output .= '<td><span class="LC_nobreak">'.
                   14653:                    '<label><input type="radio" name="archive_'.$count.
                   14654:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   14655:         my $text = $choices{$action};
                   14656:         if ($is_dir) {
                   14657:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   14658:             if ($action eq 'display') {
1.1059    raeburn  14659:                 $text = &mt('Add as folder');
1.1055    raeburn  14660:             }
1.1056    raeburn  14661:         } else {
                   14662:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   14663: 
                   14664:         }
                   14665:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   14666:         if ($action eq 'dependency') {
                   14667:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   14668:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   14669:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   14670:                        '<option value=""></option>'."\n".
                   14671:                        '</select>'."\n".
                   14672:                        '</div>';
1.1059    raeburn  14673:         } elsif ($action eq 'display') {
                   14674:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   14675:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   14676:                        '</div>';
1.1055    raeburn  14677:         }
1.1056    raeburn  14678:         $output .= '</td>';
1.1055    raeburn  14679:     }
                   14680:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   14681:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   14682:     for (my $i=0; $i<$depth; $i++) {
                   14683:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   14684:     }
                   14685:     if ($is_dir) {
                   14686:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   14687:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   14688:     } else {
                   14689:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   14690:     }
                   14691:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   14692:                &end_data_table_row();
                   14693:     return $output;
                   14694: }
                   14695: 
                   14696: sub archive_options_form {
1.1065    raeburn  14697:     my ($form,$display,$count,$hiddenelem) = @_;
                   14698:     my %lt = &Apache::lonlocal::texthash(
                   14699:                perm => 'Permanently remove archive file?',
                   14700:                hows => 'How should each extracted item be incorporated in the course?',
                   14701:                cont => 'Content actions for all',
                   14702:                addf => 'Add as folder/file',
                   14703:                incd => 'Include as dependency for a displayed file',
                   14704:                disc => 'Discard',
                   14705:                no   => 'No',
                   14706:                yes  => 'Yes',
                   14707:                save => 'Save',
                   14708:     );
                   14709:     my $output = <<"END";
                   14710: <form name="$form" method="post" action="">
                   14711: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   14712: <label>
                   14713:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   14714: </label>
                   14715: &nbsp;
                   14716: <label>
                   14717:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   14718: </span>
                   14719: </p>
                   14720: <input type="hidden" name="phase" value="decompress_cleanup" />
                   14721: <br />$lt{'hows'}
                   14722: <div class="LC_columnSection">
                   14723:   <fieldset>
                   14724:     <legend>$lt{'cont'}</legend>
                   14725:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   14726:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   14727:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   14728:   </fieldset>
                   14729: </div>
                   14730: END
                   14731:     return $output.
1.1055    raeburn  14732:            &start_data_table()."\n".
1.1065    raeburn  14733:            $display."\n".
1.1055    raeburn  14734:            &end_data_table()."\n".
                   14735:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   14736:            $hiddenelem.
1.1065    raeburn  14737:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  14738:            '</form>';
                   14739: }
                   14740: 
                   14741: sub archive_javascript {
1.1056    raeburn  14742:     my ($startcount,$numitems,$titles,$children) = @_;
                   14743:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  14744:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  14745:     my $scripttag = <<START;
                   14746: <script type="text/javascript">
                   14747: // <![CDATA[
                   14748: 
                   14749: function checkAll(form,prefix) {
                   14750:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14751:     for (var i=0; i < form.elements.length; i++) {
                   14752:         var id = form.elements[i].id;
                   14753:         if ((id != '') && (id != undefined)) {
                   14754:             if (idstr.test(id)) {
                   14755:                 if (form.elements[i].type == 'radio') {
                   14756:                     form.elements[i].checked = true;
1.1056    raeburn  14757:                     var nostart = i-$startcount;
1.1059    raeburn  14758:                     var offset = nostart%7;
                   14759:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14760:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14761:                 }
                   14762:             }
                   14763:         }
                   14764:     }
                   14765: }
                   14766: 
                   14767: function propagateCheck(form,count) {
                   14768:     if (count > 0) {
1.1059    raeburn  14769:         var startelement = $startcount + ((count-1) * 7);
                   14770:         for (var j=1; j<6; j++) {
                   14771:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14772:                 var item = startelement + j; 
                   14773:                 if (form.elements[item].type == 'radio') {
                   14774:                     if (form.elements[item].checked) {
                   14775:                         containerCheck(form,count,j);
                   14776:                         break;
                   14777:                     }
1.1055    raeburn  14778:                 }
                   14779:             }
                   14780:         }
                   14781:     }
                   14782: }
                   14783: 
                   14784: numitems = $numitems
1.1056    raeburn  14785: var titles = new Array(numitems);
                   14786: var parents = new Array(numitems);
1.1055    raeburn  14787: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14788:     parents[i] = new Array;
1.1055    raeburn  14789: }
1.1059    raeburn  14790: var maintitle = '$maintitle';
1.1055    raeburn  14791: 
                   14792: START
                   14793: 
1.1056    raeburn  14794:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14795:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14796:         for (my $i=0; $i<@contents; $i ++) {
                   14797:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14798:         }
                   14799:     }
                   14800: 
1.1056    raeburn  14801:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14802:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14803:     }
                   14804: 
1.1055    raeburn  14805:     $scripttag .= <<END;
                   14806: 
                   14807: function containerCheck(form,count,offset) {
                   14808:     if (count > 0) {
1.1056    raeburn  14809:         dependencyCheck(form,count,offset);
1.1059    raeburn  14810:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14811:         form.elements[item].checked = true;
                   14812:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14813:             if (parents[count].length > 0) {
                   14814:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14815:                     containerCheck(form,parents[count][j],offset);
                   14816:                 }
                   14817:             }
                   14818:         }
                   14819:     }
                   14820: }
                   14821: 
                   14822: function dependencyCheck(form,count,offset) {
                   14823:     if (count > 0) {
1.1059    raeburn  14824:         var chosen = (offset+$startcount)+7*(count-1);
                   14825:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14826:         var currtype = form.elements[depitem].type;
                   14827:         if (form.elements[chosen].value == 'dependency') {
                   14828:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14829:             form.elements[depitem].options.length = 0;
                   14830:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14831:             for (var i=1; i<=numitems; i++) {
                   14832:                 if (i == count) {
                   14833:                     continue;
                   14834:                 }
1.1059    raeburn  14835:                 var startelement = $startcount + (i-1) * 7;
                   14836:                 for (var j=1; j<6; j++) {
                   14837:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14838:                         var item = startelement + j;
                   14839:                         if (form.elements[item].type == 'radio') {
                   14840:                             if (form.elements[item].checked) {
                   14841:                                 if (form.elements[item].value == 'display') {
                   14842:                                     var n = form.elements[depitem].options.length;
                   14843:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14844:                                 }
                   14845:                             }
                   14846:                         }
                   14847:                     }
                   14848:                 }
                   14849:             }
                   14850:         } else {
                   14851:             document.getElementById('arc_depon_'+count).style.display='none';
                   14852:             form.elements[depitem].options.length = 0;
                   14853:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14854:         }
1.1059    raeburn  14855:         titleCheck(form,count,offset);
1.1056    raeburn  14856:     }
                   14857: }
                   14858: 
                   14859: function propagateSelect(form,count,offset) {
                   14860:     if (count > 0) {
1.1065    raeburn  14861:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14862:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14863:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14864:             if (parents[count].length > 0) {
                   14865:                 for (var j=0; j<parents[count].length; j++) {
                   14866:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14867:                 }
                   14868:             }
                   14869:         }
                   14870:     }
                   14871: }
1.1056    raeburn  14872: 
                   14873: function containerSelect(form,count,offset,picked) {
                   14874:     if (count > 0) {
1.1065    raeburn  14875:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14876:         if (form.elements[item].type == 'radio') {
                   14877:             if (form.elements[item].value == 'dependency') {
                   14878:                 if (form.elements[item+1].type == 'select-one') {
                   14879:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14880:                         if (form.elements[item+1].options[i].value == picked) {
                   14881:                             form.elements[item+1].selectedIndex = i;
                   14882:                             break;
                   14883:                         }
                   14884:                     }
                   14885:                 }
                   14886:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14887:                     if (parents[count].length > 0) {
                   14888:                         for (var j=0; j<parents[count].length; j++) {
                   14889:                             containerSelect(form,parents[count][j],offset,picked);
                   14890:                         }
                   14891:                     }
                   14892:                 }
                   14893:             }
                   14894:         }
                   14895:     }
                   14896: }
                   14897: 
1.1059    raeburn  14898: function titleCheck(form,count,offset) {
                   14899:     if (count > 0) {
                   14900:         var chosen = (offset+$startcount)+7*(count-1);
                   14901:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14902:         var currtype = form.elements[depitem].type;
                   14903:         if (form.elements[chosen].value == 'display') {
                   14904:             document.getElementById('arc_title_'+count).style.display='block';
                   14905:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14906:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14907:             }
                   14908:         } else {
                   14909:             document.getElementById('arc_title_'+count).style.display='none';
                   14910:             if (currtype == 'text') { 
                   14911:                 document.getElementById('archive_title_'+count).value='';
                   14912:             }
                   14913:         }
                   14914:     }
                   14915:     return;
                   14916: }
                   14917: 
1.1055    raeburn  14918: // ]]>
                   14919: </script>
                   14920: END
                   14921:     return $scripttag;
                   14922: }
                   14923: 
                   14924: sub process_extracted_files {
1.1067    raeburn  14925:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14926:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14927:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14928:     my @ids=&Apache::lonnet::current_machine_ids();
                   14929:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14930:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14931:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14932:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14933:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14934:         $pathtocheck = "$dir_root/$destination";
                   14935:         $dir = $dir_root;
                   14936:         $ishome = 1;
                   14937:     } else {
                   14938:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14939:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14940:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14941:     }
                   14942:     my $currdir = "$dir_root/$destination";
                   14943:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14944:     if ($env{'form.folderpath'}) {
                   14945:         my @items = split('&',$env{'form.folderpath'});
                   14946:         $folders{'0'} = $items[-2];
1.1099    raeburn  14947:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14948:             $containers{'0'}='page';
                   14949:         } else {  
                   14950:             $containers{'0'}='sequence';
                   14951:         }
1.1055    raeburn  14952:     }
                   14953:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14954:     if ($numitems) {
                   14955:         for (my $i=1; $i<=$numitems; $i++) {
                   14956:             my $path = $env{'form.archive_content_'.$i};
                   14957:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14958:                 my $item = $1;
                   14959:                 $toplevelitems{$item} = $i;
                   14960:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14961:                     $is_dir{$item} = 1;
                   14962:                 }
                   14963:             }
                   14964:         }
                   14965:     }
1.1067    raeburn  14966:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14967:     if (keys(%toplevelitems) > 0) {
                   14968:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14969:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14970:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14971:     }
1.1066    raeburn  14972:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14973:     if ($numitems) {
                   14974:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14975:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14976:             my $path = $env{'form.archive_content_'.$i};
                   14977:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14978:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14979:                     if ($prefix ne '' && $path ne '') {
                   14980:                         if (-e $prefix.$path) {
1.1066    raeburn  14981:                             if ((@archdirs > 0) && 
                   14982:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14983:                                 $todeletedir{$prefix.$path} = 1;
                   14984:                             } else {
                   14985:                                 $todelete{$prefix.$path} = 1;
                   14986:                             }
1.1055    raeburn  14987:                         }
                   14988:                     }
                   14989:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14990:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14991:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14992:                     $docstitle = $env{'form.archive_title_'.$i};
                   14993:                     if ($docstitle eq '') {
                   14994:                         $docstitle = $title;
                   14995:                     }
1.1055    raeburn  14996:                     $outer = 0;
1.1056    raeburn  14997:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14998:                         if (@{$dirorder{$i}} > 0) {
                   14999:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  15000:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   15001:                                     $outer = $item;
                   15002:                                     last;
                   15003:                                 }
                   15004:                             }
                   15005:                         }
                   15006:                     }
                   15007:                     my ($errtext,$fatal) = 
                   15008:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   15009:                                                '/'.$folders{$outer}.'.'.
                   15010:                                                $containers{$outer});
                   15011:                     next if ($fatal);
                   15012:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   15013:                         if ($context eq 'coursedocs') {
1.1056    raeburn  15014:                             $mapinner{$i} = time;
1.1055    raeburn  15015:                             $folders{$i} = 'default_'.$mapinner{$i};
                   15016:                             $containers{$i} = 'sequence';
                   15017:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   15018:                                       $folders{$i}.'.'.$containers{$i};
                   15019:                             my $newidx = &LONCAPA::map::getresidx();
                   15020:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  15021:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  15022:                             push(@LONCAPA::map::order,$newidx);
                   15023:                             my ($outtext,$errtext) =
                   15024:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   15025:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  15026:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  15027:                             $newseqid{$i} = $newidx;
1.1067    raeburn  15028:                             unless ($errtext) {
1.1294    raeburn  15029:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   15030:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   15031:                                             '</li>'."\n";
1.1067    raeburn  15032:                             }
1.1055    raeburn  15033:                         }
                   15034:                     } else {
                   15035:                         if ($context eq 'coursedocs') {
                   15036:                             my $newidx=&LONCAPA::map::getresidx();
                   15037:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   15038:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   15039:                                       $title;
1.1392    raeburn  15040:                             if (($outer !~ /\D/) &&
                   15041:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   15042:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  15043:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   15044:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   15045:                                 }
                   15046:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   15047:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   15048:                                 }
                   15049:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   15050:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   15051:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   15052:                                         unless ($ishome) {
                   15053:                                             my $fetch = "$newdest{$i}/$title";
                   15054:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   15055:                                             $prompttofetch{$fetch} = 1;
                   15056:                                         }
1.1292    raeburn  15057:                                     }
1.1067    raeburn  15058:                                 }
1.1294    raeburn  15059:                                 $LONCAPA::map::resources[$newidx]=
                   15060:                                     $docstitle.':'.$url.':false:normal:res';
                   15061:                                 push(@LONCAPA::map::order, $newidx);
                   15062:                                 my ($outtext,$errtext)=
                   15063:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   15064:                                                             $docuname.'/'.$folders{$outer}.
                   15065:                                                             '.'.$containers{$outer},1,1);
                   15066:                                 unless ($errtext) {
                   15067:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   15068:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   15069:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   15070:                                                    '</li>'."\n";
                   15071:                                     }
1.1067    raeburn  15072:                                 }
1.1294    raeburn  15073:                             } else {
                   15074:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   15075:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  15076:                             }
1.1055    raeburn  15077:                         }
                   15078:                     }
1.1086    raeburn  15079:                 }
                   15080:             } else {
1.1294    raeburn  15081:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   15082:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  15083:             }
                   15084:         }
                   15085:         for (my $i=1; $i<=$numitems; $i++) {
                   15086:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   15087:             my $path = $env{'form.archive_content_'.$i};
                   15088:             if ($path =~ /^\Q$pathtocheck\E/) {
                   15089:                 my ($title) = ($path =~ m{/([^/]+)$});
                   15090:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   15091:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   15092:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   15093:                         my ($itemidx,$fullpath,$relpath);
                   15094:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   15095:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  15096:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  15097:                                 if ($dirorder{$i}->[$j] eq $container) {
                   15098:                                     $itemidx = $j;
1.1056    raeburn  15099:                                 }
                   15100:                             }
1.1086    raeburn  15101:                         }
                   15102:                         if ($itemidx eq '') {
                   15103:                             $itemidx =  0;
                   15104:                         } 
                   15105:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   15106:                             if ($mapinner{$referrer{$i}}) {
                   15107:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   15108:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15109:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15110:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15111:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15112:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15113:                                             if (!-e $fullpath) {
                   15114:                                                 mkdir($fullpath,0755);
1.1056    raeburn  15115:                                             }
                   15116:                                         }
1.1086    raeburn  15117:                                     } else {
                   15118:                                         last;
1.1056    raeburn  15119:                                     }
1.1086    raeburn  15120:                                 }
                   15121:                             }
                   15122:                         } elsif ($newdest{$referrer{$i}}) {
                   15123:                             $fullpath = $newdest{$referrer{$i}};
                   15124:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15125:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   15126:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   15127:                                     last;
                   15128:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15129:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15130:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15131:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15132:                                         if (!-e $fullpath) {
                   15133:                                             mkdir($fullpath,0755);
1.1056    raeburn  15134:                                         }
                   15135:                                     }
1.1086    raeburn  15136:                                 } else {
                   15137:                                     last;
1.1056    raeburn  15138:                                 }
1.1055    raeburn  15139:                             }
                   15140:                         }
1.1086    raeburn  15141:                         if ($fullpath ne '') {
                   15142:                             if (-e "$prefix$path") {
1.1292    raeburn  15143:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   15144:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   15145:                                 }
1.1086    raeburn  15146:                             }
                   15147:                             if (-e "$fullpath/$title") {
                   15148:                                 my $showpath;
                   15149:                                 if ($relpath ne '') {
                   15150:                                     $showpath = "$relpath/$title";
                   15151:                                 } else {
                   15152:                                     $showpath = "/$title";
                   15153:                                 } 
1.1294    raeburn  15154:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   15155:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   15156:                                            '</li>'."\n";
1.1292    raeburn  15157:                                 unless ($ishome) {
                   15158:                                     my $fetch = "$fullpath/$title";
                   15159:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   15160:                                     $prompttofetch{$fetch} = 1;
                   15161:                                 }
1.1086    raeburn  15162:                             }
                   15163:                         }
1.1055    raeburn  15164:                     }
1.1086    raeburn  15165:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   15166:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  15167:                                     &HTML::Entities::encode($path,'<>&"'),
                   15168:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   15169:                                 '<br />';
1.1055    raeburn  15170:                 }
                   15171:             } else {
1.1294    raeburn  15172:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  15173:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  15174:             }
                   15175:         }
                   15176:         if (keys(%todelete)) {
                   15177:             foreach my $key (keys(%todelete)) {
                   15178:                 unlink($key);
1.1066    raeburn  15179:             }
                   15180:         }
                   15181:         if (keys(%todeletedir)) {
                   15182:             foreach my $key (keys(%todeletedir)) {
                   15183:                 rmdir($key);
                   15184:             }
                   15185:         }
                   15186:         foreach my $dir (sort(keys(%is_dir))) {
                   15187:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   15188:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  15189:             }
                   15190:         }
1.1067    raeburn  15191:         if ($result ne '') {
                   15192:             $output .= '<ul>'."\n".
                   15193:                        $result."\n".
                   15194:                        '</ul>';
                   15195:         }
                   15196:         unless ($ishome) {
                   15197:             my $replicationfail;
                   15198:             foreach my $item (keys(%prompttofetch)) {
                   15199:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   15200:                 unless ($fetchresult eq 'ok') {
                   15201:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   15202:                 }
                   15203:             }
                   15204:             if ($replicationfail) {
                   15205:                 $output .= '<p class="LC_error">'.
                   15206:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   15207:                            $replicationfail.
                   15208:                            '</ul></p>';
                   15209:             }
                   15210:         }
1.1055    raeburn  15211:     } else {
                   15212:         $warning = &mt('No items found in archive.');
                   15213:     }
                   15214:     if ($error) {
                   15215:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   15216:                    $error.'</p>'."\n";
                   15217:     }
                   15218:     if ($warning) {
                   15219:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   15220:     }
                   15221:     return $output;
                   15222: }
                   15223: 
1.1066    raeburn  15224: sub cleanup_empty_dirs {
                   15225:     my ($path) = @_;
                   15226:     if (($path ne '') && (-d $path)) {
                   15227:         if (opendir(my $dirh,$path)) {
                   15228:             my @dircontents = grep(!/^\./,readdir($dirh));
                   15229:             my $numitems = 0;
                   15230:             foreach my $item (@dircontents) {
                   15231:                 if (-d "$path/$item") {
1.1111    raeburn  15232:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  15233:                     if (-e "$path/$item") {
                   15234:                         $numitems ++;
                   15235:                     }
                   15236:                 } else {
                   15237:                     $numitems ++;
                   15238:                 }
                   15239:             }
                   15240:             if ($numitems == 0) {
                   15241:                 rmdir($path);
                   15242:             }
                   15243:             closedir($dirh);
                   15244:         }
                   15245:     }
                   15246:     return;
                   15247: }
                   15248: 
1.41      ng       15249: =pod
1.45      matthew  15250: 
1.1162    raeburn  15251: =item * &get_folder_hierarchy()
1.1068    raeburn  15252: 
                   15253: Provides hierarchy of names of folders/sub-folders containing the current
                   15254: item,
                   15255: 
                   15256: Inputs: 3
                   15257:      - $navmap - navmaps object
                   15258: 
                   15259:      - $map - url for map (either the trigger itself, or map containing
                   15260:                            the resource, which is the trigger).
                   15261: 
                   15262:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   15263: 
                   15264: Outputs: 1 @pathitems - array of folder/subfolder names.
                   15265: 
                   15266: =cut
                   15267: 
                   15268: sub get_folder_hierarchy {
                   15269:     my ($navmap,$map,$showitem) = @_;
                   15270:     my @pathitems;
                   15271:     if (ref($navmap)) {
                   15272:         my $mapres = $navmap->getResourceByUrl($map);
                   15273:         if (ref($mapres)) {
                   15274:             my $pcslist = $mapres->map_hierarchy();
                   15275:             if ($pcslist ne '') {
                   15276:                 my @pcs = split(/,/,$pcslist);
                   15277:                 foreach my $pc (@pcs) {
                   15278:                     if ($pc == 1) {
1.1129    raeburn  15279:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  15280:                     } else {
                   15281:                         my $res = $navmap->getByMapPc($pc);
                   15282:                         if (ref($res)) {
                   15283:                             my $title = $res->compTitle();
                   15284:                             $title =~ s/\W+/_/g;
                   15285:                             if ($title ne '') {
                   15286:                                 push(@pathitems,$title);
                   15287:                             }
                   15288:                         }
                   15289:                     }
                   15290:                 }
                   15291:             }
1.1071    raeburn  15292:             if ($showitem) {
                   15293:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  15294:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  15295:                 } else {
                   15296:                     my $maptitle = $mapres->compTitle();
                   15297:                     $maptitle =~ s/\W+/_/g;
                   15298:                     if ($maptitle ne '') {
                   15299:                         push(@pathitems,$maptitle);
                   15300:                     }
1.1068    raeburn  15301:                 }
                   15302:             }
                   15303:         }
                   15304:     }
                   15305:     return @pathitems;
                   15306: }
                   15307: 
                   15308: =pod
                   15309: 
1.1015    raeburn  15310: =item * &get_turnedin_filepath()
                   15311: 
                   15312: Determines path in a user's portfolio file for storage of files uploaded
                   15313: to a specific essayresponse or dropbox item.
                   15314: 
                   15315: Inputs: 3 required + 1 optional.
                   15316: $symb is symb for resource, $uname and $udom are for current user (required).
                   15317: $caller is optional (can be "submission", if routine is called when storing
                   15318: an upoaded file when "Submit Answer" button was pressed).
                   15319: 
                   15320: Returns array containing $path and $multiresp. 
                   15321: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   15322: than one file upload item.  Callers of routine should append partid as a 
                   15323: subdirectory to $path in cases where $multiresp is 1.
                   15324: 
                   15325: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   15326: 
                   15327: =cut
                   15328: 
                   15329: sub get_turnedin_filepath {
                   15330:     my ($symb,$uname,$udom,$caller) = @_;
                   15331:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   15332:     my $turnindir;
                   15333:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   15334:     $turnindir = $userhash{'turnindir'};
                   15335:     my ($path,$multiresp);
                   15336:     if ($turnindir eq '') {
                   15337:         if ($caller eq 'submission') {
                   15338:             $turnindir = &mt('turned in');
                   15339:             $turnindir =~ s/\W+/_/g;
                   15340:             my %newhash = (
                   15341:                             'turnindir' => $turnindir,
                   15342:                           );
                   15343:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   15344:         }
                   15345:     }
                   15346:     if ($turnindir ne '') {
                   15347:         $path = '/'.$turnindir.'/';
                   15348:         my ($multipart,$turnin,@pathitems);
                   15349:         my $navmap = Apache::lonnavmaps::navmap->new();
                   15350:         if (defined($navmap)) {
                   15351:             my $mapres = $navmap->getResourceByUrl($map);
                   15352:             if (ref($mapres)) {
                   15353:                 my $pcslist = $mapres->map_hierarchy();
                   15354:                 if ($pcslist ne '') {
                   15355:                     foreach my $pc (split(/,/,$pcslist)) {
                   15356:                         my $res = $navmap->getByMapPc($pc);
                   15357:                         if (ref($res)) {
                   15358:                             my $title = $res->compTitle();
                   15359:                             $title =~ s/\W+/_/g;
                   15360:                             if ($title ne '') {
1.1149    raeburn  15361:                                 if (($pc > 1) && (length($title) > 12)) {
                   15362:                                     $title = substr($title,0,12);
                   15363:                                 }
1.1015    raeburn  15364:                                 push(@pathitems,$title);
                   15365:                             }
                   15366:                         }
                   15367:                     }
                   15368:                 }
                   15369:                 my $maptitle = $mapres->compTitle();
                   15370:                 $maptitle =~ s/\W+/_/g;
                   15371:                 if ($maptitle ne '') {
1.1149    raeburn  15372:                     if (length($maptitle) > 12) {
                   15373:                         $maptitle = substr($maptitle,0,12);
                   15374:                     }
1.1015    raeburn  15375:                     push(@pathitems,$maptitle);
                   15376:                 }
                   15377:                 unless ($env{'request.state'} eq 'construct') {
                   15378:                     my $res = $navmap->getBySymb($symb);
                   15379:                     if (ref($res)) {
                   15380:                         my $partlist = $res->parts();
                   15381:                         my $totaluploads = 0;
                   15382:                         if (ref($partlist) eq 'ARRAY') {
                   15383:                             foreach my $part (@{$partlist}) {
                   15384:                                 my @types = $res->responseType($part);
                   15385:                                 my @ids = $res->responseIds($part);
                   15386:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   15387:                                     if ($types[$i] eq 'essay') {
                   15388:                                         my $partid = $part.'_'.$ids[$i];
                   15389:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   15390:                                             $totaluploads ++;
                   15391:                                         }
                   15392:                                     }
                   15393:                                 }
                   15394:                             }
                   15395:                             if ($totaluploads > 1) {
                   15396:                                 $multiresp = 1;
                   15397:                             }
                   15398:                         }
                   15399:                     }
                   15400:                 }
                   15401:             } else {
                   15402:                 return;
                   15403:             }
                   15404:         } else {
                   15405:             return;
                   15406:         }
                   15407:         my $restitle=&Apache::lonnet::gettitle($symb);
                   15408:         $restitle =~ s/\W+/_/g;
                   15409:         if ($restitle eq '') {
                   15410:             $restitle = ($resurl =~ m{/[^/]+$});
                   15411:             if ($restitle eq '') {
                   15412:                 $restitle = time;
                   15413:             }
                   15414:         }
1.1149    raeburn  15415:         if (length($restitle) > 12) {
                   15416:             $restitle = substr($restitle,0,12);
                   15417:         }
1.1015    raeburn  15418:         push(@pathitems,$restitle);
                   15419:         $path .= join('/',@pathitems);
                   15420:     }
                   15421:     return ($path,$multiresp);
                   15422: }
                   15423: 
                   15424: =pod
                   15425: 
1.464     albertel 15426: =back
1.41      ng       15427: 
1.112     bowersj2 15428: =head1 CSV Upload/Handling functions
1.38      albertel 15429: 
1.41      ng       15430: =over 4
                   15431: 
1.648     raeburn  15432: =item * &upfile_store($r)
1.41      ng       15433: 
                   15434: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 15435: needs $env{'form.upfile'}
1.41      ng       15436: returns $datatoken to be put into hidden field
                   15437: 
                   15438: =cut
1.31      albertel 15439: 
                   15440: sub upfile_store {
                   15441:     my $r=shift;
1.258     albertel 15442:     $env{'form.upfile'}=~s/\r/\n/gs;
                   15443:     $env{'form.upfile'}=~s/\f/\n/gs;
                   15444:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   15445:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 15446: 
1.1299    raeburn  15447:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   15448:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   15449:                                      time.'_'.$$);
                   15450:     return if ($datatoken eq '');
                   15451: 
1.31      albertel 15452:     {
1.158     raeburn  15453:         my $datafile = $r->dir_config('lonDaemons').
                   15454:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15455:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 15456:             print $fh $env{'form.upfile'};
1.158     raeburn  15457:             close($fh);
                   15458:         }
1.31      albertel 15459:     }
                   15460:     return $datatoken;
                   15461: }
                   15462: 
1.56      matthew  15463: =pod
                   15464: 
1.1290    raeburn  15465: =item * &load_tmp_file($r,$datatoken)
1.41      ng       15466: 
                   15467: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  15468: $datatoken is the name to assign to the temporary file.
1.258     albertel 15469: sets $env{'form.upfile'} to the contents of the file
1.41      ng       15470: 
                   15471: =cut
1.31      albertel 15472: 
                   15473: sub load_tmp_file {
1.1290    raeburn  15474:     my ($r,$datatoken) = @_;
                   15475:     return if ($datatoken eq '');
1.31      albertel 15476:     my @studentdata=();
                   15477:     {
1.158     raeburn  15478:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  15479:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15480:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  15481:             @studentdata=<$fh>;
                   15482:             close($fh);
                   15483:         }
1.31      albertel 15484:     }
1.258     albertel 15485:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 15486: }
                   15487: 
1.1290    raeburn  15488: sub valid_datatoken {
                   15489:     my ($datatoken) = @_;
1.1325    raeburn  15490:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  15491:         return $datatoken;
                   15492:     }
                   15493:     return;
                   15494: }
                   15495: 
1.56      matthew  15496: =pod
                   15497: 
1.648     raeburn  15498: =item * &upfile_record_sep()
1.41      ng       15499: 
                   15500: Separate uploaded file into records
                   15501: returns array of records,
1.258     albertel 15502: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       15503: 
                   15504: =cut
1.31      albertel 15505: 
                   15506: sub upfile_record_sep {
1.258     albertel 15507:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 15508:     } else {
1.248     albertel 15509: 	my @records;
1.258     albertel 15510: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 15511: 	    if ($line=~/^\s*$/) { next; }
                   15512: 	    push(@records,$line);
                   15513: 	}
                   15514: 	return @records;
1.31      albertel 15515:     }
                   15516: }
                   15517: 
1.56      matthew  15518: =pod
                   15519: 
1.648     raeburn  15520: =item * &record_sep($record)
1.41      ng       15521: 
1.258     albertel 15522: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       15523: 
                   15524: =cut
                   15525: 
1.263     www      15526: sub takeleft {
                   15527:     my $index=shift;
                   15528:     return substr('0000'.$index,-4,4);
                   15529: }
                   15530: 
1.31      albertel 15531: sub record_sep {
                   15532:     my $record=shift;
                   15533:     my %components=();
1.258     albertel 15534:     if ($env{'form.upfiletype'} eq 'xml') {
                   15535:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 15536:         my $i=0;
1.356     albertel 15537:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 15538:             $field=~s/^(\"|\')//;
                   15539:             $field=~s/(\"|\')$//;
1.263     www      15540:             $components{&takeleft($i)}=$field;
1.31      albertel 15541:             $i++;
                   15542:         }
1.258     albertel 15543:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 15544:         my $i=0;
1.356     albertel 15545:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 15546:             $field=~s/^(\"|\')//;
                   15547:             $field=~s/(\"|\')$//;
1.263     www      15548:             $components{&takeleft($i)}=$field;
1.31      albertel 15549:             $i++;
                   15550:         }
                   15551:     } else {
1.561     www      15552:         my $separator=',';
1.480     banghart 15553:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      15554:             $separator=';';
1.480     banghart 15555:         }
1.31      albertel 15556:         my $i=0;
1.561     www      15557: # the character we are looking for to indicate the end of a quote or a record 
                   15558:         my $looking_for=$separator;
                   15559: # do not add the characters to the fields
                   15560:         my $ignore=0;
                   15561: # we just encountered a separator (or the beginning of the record)
                   15562:         my $just_found_separator=1;
                   15563: # store the field we are working on here
                   15564:         my $field='';
                   15565: # work our way through all characters in record
                   15566:         foreach my $character ($record=~/(.)/g) {
                   15567:             if ($character eq $looking_for) {
                   15568:                if ($character ne $separator) {
                   15569: # Found the end of a quote, again looking for separator
                   15570:                   $looking_for=$separator;
                   15571:                   $ignore=1;
                   15572:                } else {
                   15573: # Found a separator, store away what we got
                   15574:                   $components{&takeleft($i)}=$field;
                   15575: 	          $i++;
                   15576:                   $just_found_separator=1;
                   15577:                   $ignore=0;
                   15578:                   $field='';
                   15579:                }
                   15580:                next;
                   15581:             }
                   15582: # single or double quotation marks after a separator indicate beginning of a quote
                   15583: # we are now looking for the end of the quote and need to ignore separators
                   15584:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   15585:                $looking_for=$character;
                   15586:                next;
                   15587:             }
                   15588: # ignore would be true after we reached the end of a quote
                   15589:             if ($ignore) { next; }
                   15590:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   15591:             $field.=$character;
                   15592:             $just_found_separator=0; 
1.31      albertel 15593:         }
1.561     www      15594: # catch the very last entry, since we never encountered the separator
                   15595:         $components{&takeleft($i)}=$field;
1.31      albertel 15596:     }
                   15597:     return %components;
                   15598: }
                   15599: 
1.144     matthew  15600: ######################################################
                   15601: ######################################################
                   15602: 
1.56      matthew  15603: =pod
                   15604: 
1.648     raeburn  15605: =item * &upfile_select_html()
1.41      ng       15606: 
1.144     matthew  15607: Return HTML code to select a file from the users machine and specify 
                   15608: the file type.
1.41      ng       15609: 
                   15610: =cut
                   15611: 
1.144     matthew  15612: ######################################################
                   15613: ######################################################
1.31      albertel 15614: sub upfile_select_html {
1.144     matthew  15615:     my %Types = (
                   15616:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 15617:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  15618:                  space => &mt('Space separated'),
                   15619:                  tab   => &mt('Tabulator separated'),
                   15620: #                 xml   => &mt('HTML/XML'),
                   15621:                  );
                   15622:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  15623:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  15624:     foreach my $type (sort(keys(%Types))) {
                   15625:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   15626:     }
                   15627:     $Str .= "</select>\n";
                   15628:     return $Str;
1.31      albertel 15629: }
                   15630: 
1.301     albertel 15631: sub get_samples {
                   15632:     my ($records,$toget) = @_;
                   15633:     my @samples=({});
                   15634:     my $got=0;
                   15635:     foreach my $rec (@$records) {
                   15636: 	my %temp = &record_sep($rec);
                   15637: 	if (! grep(/\S/, values(%temp))) { next; }
                   15638: 	if (%temp) {
                   15639: 	    $samples[$got]=\%temp;
                   15640: 	    $got++;
                   15641: 	    if ($got == $toget) { last; }
                   15642: 	}
                   15643:     }
                   15644:     return \@samples;
                   15645: }
                   15646: 
1.144     matthew  15647: ######################################################
                   15648: ######################################################
                   15649: 
1.56      matthew  15650: =pod
                   15651: 
1.648     raeburn  15652: =item * &csv_print_samples($r,$records)
1.41      ng       15653: 
                   15654: Prints a table of sample values from each column uploaded $r is an
                   15655: Apache Request ref, $records is an arrayref from
                   15656: &Apache::loncommon::upfile_record_sep
                   15657: 
                   15658: =cut
                   15659: 
1.144     matthew  15660: ######################################################
                   15661: ######################################################
1.31      albertel 15662: sub csv_print_samples {
                   15663:     my ($r,$records) = @_;
1.662     bisitz   15664:     my $samples = &get_samples($records,5);
1.301     albertel 15665: 
1.594     raeburn  15666:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   15667:               &start_data_table_header_row());
1.356     albertel 15668:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   15669:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  15670:     $r->print(&end_data_table_header_row());
1.301     albertel 15671:     foreach my $hash (@$samples) {
1.594     raeburn  15672: 	$r->print(&start_data_table_row());
1.356     albertel 15673: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 15674: 	    $r->print('<td>');
1.356     albertel 15675: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 15676: 	    $r->print('</td>');
                   15677: 	}
1.594     raeburn  15678: 	$r->print(&end_data_table_row());
1.31      albertel 15679:     }
1.594     raeburn  15680:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 15681: }
                   15682: 
1.144     matthew  15683: ######################################################
                   15684: ######################################################
                   15685: 
1.56      matthew  15686: =pod
                   15687: 
1.648     raeburn  15688: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       15689: 
                   15690: Prints a table to create associations between values and table columns.
1.144     matthew  15691: 
1.41      ng       15692: $r is an Apache Request ref,
                   15693: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  15694: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       15695: 
                   15696: =cut
                   15697: 
1.144     matthew  15698: ######################################################
                   15699: ######################################################
1.31      albertel 15700: sub csv_print_select_table {
                   15701:     my ($r,$records,$d) = @_;
1.301     albertel 15702:     my $i=0;
                   15703:     my $samples = &get_samples($records,1);
1.144     matthew  15704:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  15705: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  15706:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  15707:               '<th>'.&mt('Column').'</th>'.
                   15708:               &end_data_table_header_row()."\n");
1.356     albertel 15709:     foreach my $array_ref (@$d) {
                   15710: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  15711: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 15712: 
1.875     bisitz   15713: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  15714: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 15715: 	$r->print('<option value="none"></option>');
1.356     albertel 15716: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   15717: 	    $r->print('<option value="'.$sample.'"'.
                   15718:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   15719:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 15720: 	}
1.594     raeburn  15721: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 15722: 	$i++;
                   15723:     }
1.594     raeburn  15724:     $r->print(&end_data_table());
1.31      albertel 15725:     $i--;
                   15726:     return $i;
                   15727: }
1.56      matthew  15728: 
1.144     matthew  15729: ######################################################
                   15730: ######################################################
                   15731: 
1.56      matthew  15732: =pod
1.31      albertel 15733: 
1.648     raeburn  15734: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       15735: 
                   15736: Prints a table of sample values from the upload and can make associate samples to internal names.
                   15737: 
                   15738: $r is an Apache Request ref,
                   15739: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   15740: $d is an array of 2 element arrays (internal name, displayed name)
                   15741: 
                   15742: =cut
                   15743: 
1.144     matthew  15744: ######################################################
                   15745: ######################################################
1.31      albertel 15746: sub csv_samples_select_table {
                   15747:     my ($r,$records,$d) = @_;
                   15748:     my $i=0;
1.144     matthew  15749:     #
1.662     bisitz   15750:     my $max_samples = 5;
                   15751:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15752:     $r->print(&start_data_table().
                   15753:               &start_data_table_header_row().'<th>'.
                   15754:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15755:               &end_data_table_header_row());
1.301     albertel 15756: 
                   15757:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15758: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15759: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15760: 	foreach my $option (@$d) {
                   15761: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15762: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15763:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15764:                       $display.'</option>');
1.31      albertel 15765: 	}
                   15766: 	$r->print('</select></td><td>');
1.662     bisitz   15767: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15768: 	    if (defined($samples->[$line]{$key})) { 
                   15769: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15770: 	    }
                   15771: 	}
1.594     raeburn  15772: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15773: 	$i++;
                   15774:     }
1.594     raeburn  15775:     $r->print(&end_data_table());
1.31      albertel 15776:     $i--;
                   15777:     return($i);
1.115     matthew  15778: }
                   15779: 
1.144     matthew  15780: ######################################################
                   15781: ######################################################
                   15782: 
1.115     matthew  15783: =pod
                   15784: 
1.648     raeburn  15785: =item * &clean_excel_name($name)
1.115     matthew  15786: 
                   15787: Returns a replacement for $name which does not contain any illegal characters.
                   15788: 
                   15789: =cut
                   15790: 
1.144     matthew  15791: ######################################################
                   15792: ######################################################
1.115     matthew  15793: sub clean_excel_name {
                   15794:     my ($name) = @_;
                   15795:     $name =~ s/[:\*\?\/\\]//g;
                   15796:     if (length($name) > 31) {
                   15797:         $name = substr($name,0,31);
                   15798:     }
                   15799:     return $name;
1.25      albertel 15800: }
1.84      albertel 15801: 
1.85      albertel 15802: =pod
                   15803: 
1.648     raeburn  15804: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15805: 
                   15806: Returns either 1 or undef
                   15807: 
                   15808: 1 if the part is to be hidden, undef if it is to be shown
                   15809: 
                   15810: Arguments are:
                   15811: 
                   15812: $id the id of the part to be checked
                   15813: $symb, optional the symb of the resource to check
                   15814: $udom, optional the domain of the user to check for
                   15815: $uname, optional the username of the user to check for
                   15816: 
                   15817: =cut
1.84      albertel 15818: 
                   15819: sub check_if_partid_hidden {
                   15820:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15821:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15822: 					 $symb,$udom,$uname);
1.141     albertel 15823:     my $truth=1;
                   15824:     #if the string starts with !, then the list is the list to show not hide
                   15825:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15826:     my @hiddenlist=split(/,/,$hiddenparts);
                   15827:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15828: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15829:     }
1.141     albertel 15830:     return !$truth;
1.84      albertel 15831: }
1.127     matthew  15832: 
1.138     matthew  15833: 
                   15834: ############################################################
                   15835: ############################################################
                   15836: 
                   15837: =pod
                   15838: 
1.157     matthew  15839: =back 
                   15840: 
1.138     matthew  15841: =head1 cgi-bin script and graphing routines
                   15842: 
1.157     matthew  15843: =over 4
                   15844: 
1.648     raeburn  15845: =item * &get_cgi_id()
1.138     matthew  15846: 
                   15847: Inputs: none
                   15848: 
                   15849: Returns an id which can be used to pass environment variables
                   15850: to various cgi-bin scripts.  These environment variables will
                   15851: be removed from the users environment after a given time by
                   15852: the routine &Apache::lonnet::transfer_profile_to_env.
                   15853: 
                   15854: =cut
                   15855: 
                   15856: ############################################################
                   15857: ############################################################
1.152     albertel 15858: my $uniq=0;
1.136     matthew  15859: sub get_cgi_id {
1.154     albertel 15860:     $uniq=($uniq+1)%100000;
1.280     albertel 15861:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15862: }
                   15863: 
1.127     matthew  15864: ############################################################
                   15865: ############################################################
                   15866: 
                   15867: =pod
                   15868: 
1.648     raeburn  15869: =item * &DrawBarGraph()
1.127     matthew  15870: 
1.138     matthew  15871: Facilitates the plotting of data in a (stacked) bar graph.
                   15872: Puts plot definition data into the users environment in order for 
                   15873: graph.png to plot it.  Returns an <img> tag for the plot.
                   15874: The bars on the plot are labeled '1','2',...,'n'.
                   15875: 
                   15876: Inputs:
                   15877: 
                   15878: =over 4
                   15879: 
                   15880: =item $Title: string, the title of the plot
                   15881: 
                   15882: =item $xlabel: string, text describing the X-axis of the plot
                   15883: 
                   15884: =item $ylabel: string, text describing the Y-axis of the plot
                   15885: 
                   15886: =item $Max: scalar, the maximum Y value to use in the plot
                   15887: If $Max is < any data point, the graph will not be rendered.
                   15888: 
1.140     matthew  15889: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15890: they are plotted.  If undefined, default values will be used.
                   15891: 
1.178     matthew  15892: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15893: 
1.138     matthew  15894: =item @Values: An array of array references.  Each array reference holds data
                   15895: to be plotted in a stacked bar chart.
                   15896: 
1.239     matthew  15897: =item If the final element of @Values is a hash reference the key/value
                   15898: pairs will be added to the graph definition.
                   15899: 
1.138     matthew  15900: =back
                   15901: 
                   15902: Returns:
                   15903: 
                   15904: An <img> tag which references graph.png and the appropriate identifying
                   15905: information for the plot.
                   15906: 
1.127     matthew  15907: =cut
                   15908: 
                   15909: ############################################################
                   15910: ############################################################
1.134     matthew  15911: sub DrawBarGraph {
1.178     matthew  15912:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15913:     #
                   15914:     if (! defined($colors)) {
                   15915:         $colors = ['#33ff00', 
                   15916:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15917:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15918:                   ]; 
                   15919:     }
1.228     matthew  15920:     my $extra_settings = {};
                   15921:     if (ref($Values[-1]) eq 'HASH') {
                   15922:         $extra_settings = pop(@Values);
                   15923:     }
1.127     matthew  15924:     #
1.136     matthew  15925:     my $identifier = &get_cgi_id();
                   15926:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15927:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15928:         return '';
                   15929:     }
1.225     matthew  15930:     #
                   15931:     my @Labels;
                   15932:     if (defined($labels)) {
                   15933:         @Labels = @$labels;
                   15934:     } else {
                   15935:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15936:             push(@Labels,$i+1);
1.225     matthew  15937:         }
                   15938:     }
                   15939:     #
1.129     matthew  15940:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15941:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15942:     my %ValuesHash;
                   15943:     my $NumSets=1;
                   15944:     foreach my $array (@Values) {
                   15945:         next if (! ref($array));
1.136     matthew  15946:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15947:             join(',',@$array);
1.129     matthew  15948:     }
1.127     matthew  15949:     #
1.136     matthew  15950:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15951:     if ($NumBars < 3) {
                   15952:         $width = 120+$NumBars*32;
1.220     matthew  15953:         $xskip = 1;
1.225     matthew  15954:         $bar_width = 30;
                   15955:     } elsif ($NumBars < 5) {
                   15956:         $width = 120+$NumBars*20;
                   15957:         $xskip = 1;
                   15958:         $bar_width = 20;
1.220     matthew  15959:     } elsif ($NumBars < 10) {
1.136     matthew  15960:         $width = 120+$NumBars*15;
                   15961:         $xskip = 1;
                   15962:         $bar_width = 15;
                   15963:     } elsif ($NumBars <= 25) {
                   15964:         $width = 120+$NumBars*11;
                   15965:         $xskip = 5;
                   15966:         $bar_width = 8;
                   15967:     } elsif ($NumBars <= 50) {
                   15968:         $width = 120+$NumBars*8;
                   15969:         $xskip = 5;
                   15970:         $bar_width = 4;
                   15971:     } else {
                   15972:         $width = 120+$NumBars*8;
                   15973:         $xskip = 5;
                   15974:         $bar_width = 4;
                   15975:     }
                   15976:     #
1.137     matthew  15977:     $Max = 1 if ($Max < 1);
                   15978:     if ( int($Max) < $Max ) {
                   15979:         $Max++;
                   15980:         $Max = int($Max);
                   15981:     }
1.127     matthew  15982:     $Title  = '' if (! defined($Title));
                   15983:     $xlabel = '' if (! defined($xlabel));
                   15984:     $ylabel = '' if (! defined($ylabel));
1.369     www      15985:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15986:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15987:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15988:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15989:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15990:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15991:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15992:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15993:     $ValuesHash{$id.'.height'}   = $height;
                   15994:     $ValuesHash{$id.'.width'}    = $width;
                   15995:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15996:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15997:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15998:     #
1.228     matthew  15999:     # Deal with other parameters
                   16000:     while (my ($key,$value) = each(%$extra_settings)) {
                   16001:         $ValuesHash{$id.'.'.$key} = $value;
                   16002:     }
                   16003:     #
1.646     raeburn  16004:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  16005:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   16006: }
                   16007: 
                   16008: ############################################################
                   16009: ############################################################
                   16010: 
                   16011: =pod
                   16012: 
1.648     raeburn  16013: =item * &DrawXYGraph()
1.137     matthew  16014: 
1.138     matthew  16015: Facilitates the plotting of data in an XY graph.
                   16016: Puts plot definition data into the users environment in order for 
                   16017: graph.png to plot it.  Returns an <img> tag for the plot.
                   16018: 
                   16019: Inputs:
                   16020: 
                   16021: =over 4
                   16022: 
                   16023: =item $Title: string, the title of the plot
                   16024: 
                   16025: =item $xlabel: string, text describing the X-axis of the plot
                   16026: 
                   16027: =item $ylabel: string, text describing the Y-axis of the plot
                   16028: 
                   16029: =item $Max: scalar, the maximum Y value to use in the plot
                   16030: If $Max is < any data point, the graph will not be rendered.
                   16031: 
                   16032: =item $colors: Array ref containing the hex color codes for the data to be 
                   16033: plotted in.  If undefined, default values will be used.
                   16034: 
                   16035: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   16036: 
                   16037: =item $Ydata: Array ref containing Array refs.  
1.185     www      16038: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  16039: 
                   16040: =item %Values: hash indicating or overriding any default values which are 
                   16041: passed to graph.png.  
                   16042: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   16043: 
                   16044: =back
                   16045: 
                   16046: Returns:
                   16047: 
                   16048: An <img> tag which references graph.png and the appropriate identifying
                   16049: information for the plot.
                   16050: 
1.137     matthew  16051: =cut
                   16052: 
                   16053: ############################################################
                   16054: ############################################################
                   16055: sub DrawXYGraph {
                   16056:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   16057:     #
                   16058:     # Create the identifier for the graph
                   16059:     my $identifier = &get_cgi_id();
                   16060:     my $id = 'cgi.'.$identifier;
                   16061:     #
                   16062:     $Title  = '' if (! defined($Title));
                   16063:     $xlabel = '' if (! defined($xlabel));
                   16064:     $ylabel = '' if (! defined($ylabel));
                   16065:     my %ValuesHash = 
                   16066:         (
1.369     www      16067:          $id.'.title'  => &escape($Title),
                   16068:          $id.'.xlabel' => &escape($xlabel),
                   16069:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  16070:          $id.'.y_max_value'=> $Max,
                   16071:          $id.'.labels'     => join(',',@$Xlabels),
                   16072:          $id.'.PlotType'   => 'XY',
                   16073:          );
                   16074:     #
                   16075:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16076:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16077:     }
                   16078:     #
                   16079:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   16080:         return '';
                   16081:     }
                   16082:     my $NumSets=1;
1.138     matthew  16083:     foreach my $array (@{$Ydata}){
1.137     matthew  16084:         next if (! ref($array));
                   16085:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   16086:     }
1.138     matthew  16087:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  16088:     #
                   16089:     # Deal with other parameters
                   16090:     while (my ($key,$value) = each(%Values)) {
                   16091:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  16092:     }
                   16093:     #
1.646     raeburn  16094:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  16095:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   16096: }
                   16097: 
                   16098: ############################################################
                   16099: ############################################################
                   16100: 
                   16101: =pod
                   16102: 
1.648     raeburn  16103: =item * &DrawXYYGraph()
1.138     matthew  16104: 
                   16105: Facilitates the plotting of data in an XY graph with two Y axes.
                   16106: Puts plot definition data into the users environment in order for 
                   16107: graph.png to plot it.  Returns an <img> tag for the plot.
                   16108: 
                   16109: Inputs:
                   16110: 
                   16111: =over 4
                   16112: 
                   16113: =item $Title: string, the title of the plot
                   16114: 
                   16115: =item $xlabel: string, text describing the X-axis of the plot
                   16116: 
                   16117: =item $ylabel: string, text describing the Y-axis of the plot
                   16118: 
                   16119: =item $colors: Array ref containing the hex color codes for the data to be 
                   16120: plotted in.  If undefined, default values will be used.
                   16121: 
                   16122: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   16123: 
                   16124: =item $Ydata1: The first data set
                   16125: 
                   16126: =item $Min1: The minimum value of the left Y-axis
                   16127: 
                   16128: =item $Max1: The maximum value of the left Y-axis
                   16129: 
                   16130: =item $Ydata2: The second data set
                   16131: 
                   16132: =item $Min2: The minimum value of the right Y-axis
                   16133: 
                   16134: =item $Max2: The maximum value of the left Y-axis
                   16135: 
                   16136: =item %Values: hash indicating or overriding any default values which are 
                   16137: passed to graph.png.  
                   16138: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   16139: 
                   16140: =back
                   16141: 
                   16142: Returns:
                   16143: 
                   16144: An <img> tag which references graph.png and the appropriate identifying
                   16145: information for the plot.
1.136     matthew  16146: 
                   16147: =cut
                   16148: 
                   16149: ############################################################
                   16150: ############################################################
1.137     matthew  16151: sub DrawXYYGraph {
                   16152:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   16153:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  16154:     #
                   16155:     # Create the identifier for the graph
                   16156:     my $identifier = &get_cgi_id();
                   16157:     my $id = 'cgi.'.$identifier;
                   16158:     #
                   16159:     $Title  = '' if (! defined($Title));
                   16160:     $xlabel = '' if (! defined($xlabel));
                   16161:     $ylabel = '' if (! defined($ylabel));
                   16162:     my %ValuesHash = 
                   16163:         (
1.369     www      16164:          $id.'.title'  => &escape($Title),
                   16165:          $id.'.xlabel' => &escape($xlabel),
                   16166:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  16167:          $id.'.labels' => join(',',@$Xlabels),
                   16168:          $id.'.PlotType' => 'XY',
                   16169:          $id.'.NumSets' => 2,
1.137     matthew  16170:          $id.'.two_axes' => 1,
                   16171:          $id.'.y1_max_value' => $Max1,
                   16172:          $id.'.y1_min_value' => $Min1,
                   16173:          $id.'.y2_max_value' => $Max2,
                   16174:          $id.'.y2_min_value' => $Min2,
1.136     matthew  16175:          );
                   16176:     #
1.137     matthew  16177:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16178:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16179:     }
                   16180:     #
                   16181:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   16182:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  16183:         return '';
                   16184:     }
                   16185:     my $NumSets=1;
1.137     matthew  16186:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  16187:         next if (! ref($array));
                   16188:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  16189:     }
                   16190:     #
                   16191:     # Deal with other parameters
                   16192:     while (my ($key,$value) = each(%Values)) {
                   16193:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  16194:     }
                   16195:     #
1.646     raeburn  16196:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 16197:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  16198: }
                   16199: 
                   16200: ############################################################
                   16201: ############################################################
                   16202: 
                   16203: =pod
                   16204: 
1.157     matthew  16205: =back 
                   16206: 
1.139     matthew  16207: =head1 Statistics helper routines?  
                   16208: 
                   16209: Bad place for them but what the hell.
                   16210: 
1.157     matthew  16211: =over 4
                   16212: 
1.648     raeburn  16213: =item * &chartlink()
1.139     matthew  16214: 
                   16215: Returns a link to the chart for a specific student.  
                   16216: 
                   16217: Inputs:
                   16218: 
                   16219: =over 4
                   16220: 
                   16221: =item $linktext: The text of the link
                   16222: 
                   16223: =item $sname: The students username
                   16224: 
                   16225: =item $sdomain: The students domain
                   16226: 
                   16227: =back
                   16228: 
1.157     matthew  16229: =back
                   16230: 
1.139     matthew  16231: =cut
                   16232: 
                   16233: ############################################################
                   16234: ############################################################
                   16235: sub chartlink {
                   16236:     my ($linktext, $sname, $sdomain) = @_;
                   16237:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      16238:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 16239:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  16240:        '">'.$linktext.'</a>';
1.153     matthew  16241: }
                   16242: 
                   16243: #######################################################
                   16244: #######################################################
                   16245: 
                   16246: =pod
                   16247: 
                   16248: =head1 Course Environment Routines
1.157     matthew  16249: 
                   16250: =over 4
1.153     matthew  16251: 
1.648     raeburn  16252: =item * &restore_course_settings()
1.153     matthew  16253: 
1.648     raeburn  16254: =item * &store_course_settings()
1.153     matthew  16255: 
                   16256: Restores/Store indicated form parameters from the course environment.
                   16257: Will not overwrite existing values of the form parameters.
                   16258: 
                   16259: Inputs: 
                   16260: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   16261: 
                   16262: a hash ref describing the data to be stored.  For example:
                   16263:    
                   16264: %Save_Parameters = ('Status' => 'scalar',
                   16265:     'chartoutputmode' => 'scalar',
                   16266:     'chartoutputdata' => 'scalar',
                   16267:     'Section' => 'array',
1.373     raeburn  16268:     'Group' => 'array',
1.153     matthew  16269:     'StudentData' => 'array',
                   16270:     'Maps' => 'array');
                   16271: 
                   16272: Returns: both routines return nothing
                   16273: 
1.631     raeburn  16274: =back
                   16275: 
1.153     matthew  16276: =cut
                   16277: 
                   16278: #######################################################
                   16279: #######################################################
                   16280: sub store_course_settings {
1.496     albertel 16281:     return &store_settings($env{'request.course.id'},@_);
                   16282: }
                   16283: 
                   16284: sub store_settings {
1.153     matthew  16285:     # save to the environment
                   16286:     # appenv the same items, just to be safe
1.300     albertel 16287:     my $udom  = $env{'user.domain'};
                   16288:     my $uname = $env{'user.name'};
1.496     albertel 16289:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16290:     my %SaveHash;
                   16291:     my %AppHash;
                   16292:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 16293:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 16294:         my $envname = 'environment.'.$basename;
1.258     albertel 16295:         if (exists($env{'form.'.$setting})) {
1.153     matthew  16296:             # Save this value away
                   16297:             if ($type eq 'scalar' &&
1.258     albertel 16298:                 (! exists($env{$envname}) || 
                   16299:                  $env{$envname} ne $env{'form.'.$setting})) {
                   16300:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   16301:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  16302:             } elsif ($type eq 'array') {
                   16303:                 my $stored_form;
1.258     albertel 16304:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  16305:                     $stored_form = join(',',
                   16306:                                         map {
1.369     www      16307:                                             &escape($_);
1.258     albertel 16308:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  16309:                 } else {
                   16310:                     $stored_form = 
1.369     www      16311:                         &escape($env{'form.'.$setting});
1.153     matthew  16312:                 }
                   16313:                 # Determine if the array contents are the same.
1.258     albertel 16314:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  16315:                     $SaveHash{$basename} = $stored_form;
                   16316:                     $AppHash{$envname}   = $stored_form;
                   16317:                 }
                   16318:             }
                   16319:         }
                   16320:     }
                   16321:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 16322:                                           $udom,$uname);
1.153     matthew  16323:     if ($put_result !~ /^(ok|delayed)/) {
                   16324:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   16325:                                  'got error:'.$put_result);
                   16326:     }
                   16327:     # Make sure these settings stick around in this session, too
1.646     raeburn  16328:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  16329:     return;
                   16330: }
                   16331: 
                   16332: sub restore_course_settings {
1.499     albertel 16333:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 16334: }
                   16335: 
                   16336: sub restore_settings {
                   16337:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16338:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 16339:         next if (exists($env{'form.'.$setting}));
1.496     albertel 16340:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  16341:             '.'.$setting;
1.258     albertel 16342:         if (exists($env{$envname})) {
1.153     matthew  16343:             if ($type eq 'scalar') {
1.258     albertel 16344:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  16345:             } elsif ($type eq 'array') {
1.258     albertel 16346:                 $env{'form.'.$setting} = [ 
1.153     matthew  16347:                                            map { 
1.369     www      16348:                                                &unescape($_); 
1.258     albertel 16349:                                            } split(',',$env{$envname})
1.153     matthew  16350:                                            ];
                   16351:             }
                   16352:         }
                   16353:     }
1.127     matthew  16354: }
                   16355: 
1.618     raeburn  16356: #######################################################
                   16357: #######################################################
                   16358: 
                   16359: =pod
                   16360: 
                   16361: =head1 Domain E-mail Routines  
                   16362: 
                   16363: =over 4
                   16364: 
1.648     raeburn  16365: =item * &build_recipient_list()
1.618     raeburn  16366: 
1.1144    raeburn  16367: Build recipient lists for following types of e-mail:
1.766     raeburn  16368: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  16369: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   16370: module change checking, student/employee ID conflict checks, as
                   16371: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   16372: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  16373: 
                   16374: Inputs:
1.619     raeburn  16375: defmail (scalar - email address of default recipient), 
1.1144    raeburn  16376: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   16377: requestsmail, updatesmail, or idconflictsmail).
                   16378: 
1.619     raeburn  16379: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  16380: 
1.619     raeburn  16381: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  16382: i.e., predates configuration by DC via domainprefs.pm
                   16383: 
                   16384: $requname username of requester (if mailing type is helpdeskmail)
                   16385: 
                   16386: $requdom domain of requester (if mailing type is helpdeskmail)
                   16387: 
                   16388: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   16389: 
1.618     raeburn  16390: 
1.655     raeburn  16391: Returns: comma separated list of addresses to which to send e-mail.
                   16392: 
                   16393: =back
1.618     raeburn  16394: 
                   16395: =cut
                   16396: 
                   16397: ############################################################
                   16398: ############################################################
                   16399: sub build_recipient_list {
1.1297    raeburn  16400:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  16401:     my @recipients;
1.1270    raeburn  16402:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  16403:     my %domconfig =
1.1270    raeburn  16404:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  16405:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  16406:         if (exists($domconfig{'contacts'}{$mailing})) {
                   16407:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   16408:                 my @contacts = ('adminemail','supportemail');
                   16409:                 foreach my $item (@contacts) {
                   16410:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   16411:                         my $addr = $domconfig{'contacts'}{$item}; 
                   16412:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16413:                             push(@recipients,$addr);
                   16414:                         }
1.619     raeburn  16415:                     }
1.1270    raeburn  16416:                 }
                   16417:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   16418:                 if ($mailing eq 'helpdeskmail') {
                   16419:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   16420:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   16421:                         my @ok_bccs;
                   16422:                         foreach my $bcc (@bccs) {
                   16423:                             $bcc =~ s/^\s+//g;
                   16424:                             $bcc =~ s/\s+$//g;
                   16425:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16426:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16427:                                     push(@ok_bccs,$bcc);
                   16428:                                 }
                   16429:                             }
                   16430:                         }
                   16431:                         if (@ok_bccs > 0) {
                   16432:                             $allbcc = join(', ',@ok_bccs);
                   16433:                         }
                   16434:                     }
                   16435:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  16436:                 }
                   16437:             }
1.766     raeburn  16438:         } elsif ($origmail ne '') {
1.1270    raeburn  16439:             $lastresort = $origmail;
1.618     raeburn  16440:         }
1.1297    raeburn  16441:         if ($mailing eq 'helpdeskmail') {
                   16442:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   16443:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   16444:                 my ($inststatus,$inststatus_checked);
                   16445:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   16446:                     ($env{'user.domain'} ne 'public')) {
                   16447:                     $inststatus_checked = 1;
                   16448:                     $inststatus = $env{'environment.inststatus'};
                   16449:                 }
                   16450:                 unless ($inststatus_checked) {
                   16451:                     if (($requname ne '') && ($requdom ne '')) {
                   16452:                         if (($requname =~ /^$match_username$/) &&
                   16453:                             ($requdom =~ /^$match_domain$/) &&
                   16454:                             (&Apache::lonnet::domain($requdom))) {
                   16455:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   16456:                                                                       $requdom);
                   16457:                             unless ($requhome eq 'no_host') {
                   16458:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   16459:                                 $inststatus = $userenv{'inststatus'};
                   16460:                                 $inststatus_checked = 1;
                   16461:                             }
                   16462:                         }
                   16463:                     }
                   16464:                 }
                   16465:                 unless ($inststatus_checked) {
                   16466:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   16467:                         my %srch = (srchby     => 'email',
                   16468:                                     srchdomain => $defdom,
                   16469:                                     srchterm   => $reqemail,
                   16470:                                     srchtype   => 'exact');
                   16471:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   16472:                         foreach my $uname (keys(%srch_results)) {
                   16473:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16474:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16475:                                 $inststatus_checked = 1;
                   16476:                                 last;
                   16477:                             }
                   16478:                         }
                   16479:                         unless ($inststatus_checked) {
                   16480:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   16481:                             if ($dirsrchres eq 'ok') {
                   16482:                                 foreach my $uname (keys(%srch_results)) {
                   16483:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16484:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16485:                                         $inststatus_checked = 1;
                   16486:                                         last;
                   16487:                                     }
                   16488:                                 }
                   16489:                             }
                   16490:                         }
                   16491:                     }
                   16492:                 }
                   16493:                 if ($inststatus ne '') {
                   16494:                     foreach my $status (split(/\:/,$inststatus)) {
                   16495:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   16496:                             my @contacts = ('adminemail','supportemail');
                   16497:                             foreach my $item (@contacts) {
                   16498:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   16499:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   16500:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16501:                                         push(@recipients,$addr);
                   16502:                                     }
                   16503:                                 }
                   16504:                             }
                   16505:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   16506:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   16507:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   16508:                                 my @ok_bccs;
                   16509:                                 foreach my $bcc (@bccs) {
                   16510:                                     $bcc =~ s/^\s+//g;
                   16511:                                     $bcc =~ s/\s+$//g;
                   16512:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16513:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16514:                                             push(@ok_bccs,$bcc);
                   16515:                                         }
                   16516:                                     }
                   16517:                                 }
                   16518:                                 if (@ok_bccs > 0) {
                   16519:                                     $allbcc = join(', ',@ok_bccs);
                   16520:                                 }
                   16521:                             }
                   16522:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   16523:                             last;
                   16524:                         }
                   16525:                     }
                   16526:                 }
                   16527:             }
                   16528:         }
1.619     raeburn  16529:     } elsif ($origmail ne '') {
1.1270    raeburn  16530:         $lastresort = $origmail;
                   16531:     }
1.1297    raeburn  16532:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  16533:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   16534:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   16535:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   16536:             my %what = (
                   16537:                           perlvar => 1,
                   16538:                        );
                   16539:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   16540:             if ($primary) {
                   16541:                 my $gotaddr;
                   16542:                 my ($result,$returnhash) =
                   16543:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   16544:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   16545:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   16546:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   16547:                         $gotaddr = 1;
                   16548:                     }
                   16549:                 }
                   16550:                 unless ($gotaddr) {
                   16551:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   16552:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   16553:                     unless ($uintdom eq $intdom) {
                   16554:                         my %domconfig =
                   16555:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   16556:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   16557:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   16558:                                 my @contacts = ('adminemail','supportemail');
                   16559:                                 foreach my $item (@contacts) {
                   16560:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   16561:                                         my $addr = $domconfig{'contacts'}{$item};
                   16562:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16563:                                             push(@recipients,$addr);
                   16564:                                         }
                   16565:                                     }
                   16566:                                 }
                   16567:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   16568:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   16569:                                 }
                   16570:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   16571:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   16572:                                     my @ok_bccs;
                   16573:                                     foreach my $bcc (@bccs) {
                   16574:                                         $bcc =~ s/^\s+//g;
                   16575:                                         $bcc =~ s/\s+$//g;
                   16576:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16577:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16578:                                                 push(@ok_bccs,$bcc);
                   16579:                                             }
                   16580:                                         }
                   16581:                                     }
                   16582:                                     if (@ok_bccs > 0) {
                   16583:                                         $allbcc = join(', ',@ok_bccs);
                   16584:                                     }
                   16585:                                 }
                   16586:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   16587:                             }
                   16588:                         }
                   16589:                     }
                   16590:                 }
                   16591:             }
                   16592:         }
1.618     raeburn  16593:     }
1.688     raeburn  16594:     if (defined($defmail)) {
                   16595:         if ($defmail ne '') {
                   16596:             push(@recipients,$defmail);
                   16597:         }
1.618     raeburn  16598:     }
                   16599:     if ($otheremails) {
1.619     raeburn  16600:         my @others;
                   16601:         if ($otheremails =~ /,/) {
                   16602:             @others = split(/,/,$otheremails);
1.618     raeburn  16603:         } else {
1.619     raeburn  16604:             push(@others,$otheremails);
                   16605:         }
                   16606:         foreach my $addr (@others) {
                   16607:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16608:                 push(@recipients,$addr);
                   16609:             }
1.618     raeburn  16610:         }
                   16611:     }
1.1298    raeburn  16612:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  16613:         if ((!@recipients) && ($lastresort ne '')) {
                   16614:             push(@recipients,$lastresort);
                   16615:         }
                   16616:     } elsif ($lastresort ne '') {
                   16617:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   16618:             push(@recipients,$lastresort);
                   16619:         }
                   16620:     }
1.1271    raeburn  16621:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  16622:     if (wantarray) {
                   16623:         return ($recipientlist,$allbcc,$addtext);
                   16624:     } else {
                   16625:         return $recipientlist;
                   16626:     }
1.618     raeburn  16627: }
                   16628: 
1.127     matthew  16629: ############################################################
                   16630: ############################################################
1.154     albertel 16631: 
1.655     raeburn  16632: =pod
                   16633: 
1.1224    musolffc 16634: =over 4
                   16635: 
1.1223    musolffc 16636: =item * &mime_email()
                   16637: 
                   16638: Sends an email with a possible attachment
                   16639: 
                   16640: Inputs:
                   16641: 
                   16642: =over 4
                   16643: 
                   16644: from -              Sender's email address
                   16645: 
1.1343    raeburn  16646: replyto -           Reply-To email address
                   16647: 
1.1223    musolffc 16648: to -                Email address of recipient
                   16649: 
                   16650: subject -           Subject of email
                   16651: 
                   16652: body -              Body of email
                   16653: 
                   16654: cc_string -         Carbon copy email address
                   16655: 
                   16656: bcc -               Blind carbon copy email address
                   16657: 
                   16658: attachment_path -   Path of file to be attached
                   16659: 
                   16660: file_name -         Name of file to be attached
                   16661: 
                   16662: attachment_text -   The body of an attachment of type "TEXT"
                   16663: 
                   16664: =back
                   16665: 
                   16666: =back
                   16667: 
                   16668: =cut
                   16669: 
                   16670: ############################################################
                   16671: ############################################################
                   16672: 
                   16673: sub mime_email {
1.1343    raeburn  16674:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   16675:         $file_name,$attachment_text) = @_;
                   16676:  
1.1223    musolffc 16677:     my $msg = MIME::Lite->new(
                   16678:              From    => $from,
                   16679:              To      => $to,
                   16680:              Subject => $subject,
                   16681:              Type    =>'TEXT',
                   16682:              Data    => $body,
                   16683:              );
1.1343    raeburn  16684:     if ($replyto ne '') {
                   16685:         $msg->add("Reply-To" => $replyto);
                   16686:     }
1.1223    musolffc 16687:     if ($cc_string ne '') {
                   16688:         $msg->add("Cc" => $cc_string);
                   16689:     }
                   16690:     if ($bcc ne '') {
                   16691:         $msg->add("Bcc" => $bcc);
                   16692:     }
                   16693:     $msg->attr("content-type"         => "text/plain");
                   16694:     $msg->attr("content-type.charset" => "UTF-8");
                   16695:     # Attach file if given
                   16696:     if ($attachment_path) {
                   16697:         unless ($file_name) {
                   16698:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   16699:         }
                   16700:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   16701:         $msg->attach(Type     => $type,
                   16702:                      Path     => $attachment_path,
                   16703:                      Filename => $file_name
                   16704:                      );
                   16705:     # Otherwise attach text if given
                   16706:     } elsif ($attachment_text) {
                   16707:         $msg->attach(Type => 'TEXT',
                   16708:                      Data => $attachment_text);
                   16709:     }
                   16710:     # Send it
                   16711:     $msg->send('sendmail');
                   16712: }
                   16713: 
                   16714: ############################################################
                   16715: ############################################################
                   16716: 
                   16717: =pod
                   16718: 
1.655     raeburn  16719: =head1 Course Catalog Routines
                   16720: 
                   16721: =over 4
                   16722: 
                   16723: =item * &gather_categories()
                   16724: 
                   16725: Converts category definitions - keys of categories hash stored in  
                   16726: coursecategories in configuration.db on the primary library server in a 
                   16727: domain - to an array.  Also generates javascript and idx hash used to 
                   16728: generate Domain Coordinator interface for editing Course Categories.
                   16729: 
                   16730: Inputs:
1.663     raeburn  16731: 
1.655     raeburn  16732: categories (reference to hash of category definitions).
1.663     raeburn  16733: 
1.655     raeburn  16734: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16735:       categories and subcategories).
1.663     raeburn  16736: 
1.655     raeburn  16737: idx (reference to hash of counters used in Domain Coordinator interface for 
                   16738:       editing Course Categories).
1.663     raeburn  16739: 
1.655     raeburn  16740: jsarray (reference to array of categories used to create Javascript arrays for
                   16741:          Domain Coordinator interface for editing Course Categories).
                   16742: 
                   16743: Returns: nothing
                   16744: 
                   16745: Side effects: populates cats, idx and jsarray. 
                   16746: 
                   16747: =cut
                   16748: 
                   16749: sub gather_categories {
                   16750:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16751:     my %counters;
                   16752:     my $num = 0;
                   16753:     foreach my $item (keys(%{$categories})) {
                   16754:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16755:         if ($container eq '' && $depth == 0) {
                   16756:             $cats->[$depth][$categories->{$item}] = $cat;
                   16757:         } else {
                   16758:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16759:         }
                   16760:         my ($escitem,$tail) = split(/:/,$item,2);
                   16761:         if ($counters{$tail} eq '') {
                   16762:             $counters{$tail} = $num;
                   16763:             $num ++;
                   16764:         }
                   16765:         if (ref($idx) eq 'HASH') {
                   16766:             $idx->{$item} = $counters{$tail};
                   16767:         }
                   16768:         if (ref($jsarray) eq 'ARRAY') {
                   16769:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16770:         }
                   16771:     }
                   16772:     return;
                   16773: }
                   16774: 
                   16775: =pod
                   16776: 
                   16777: =item * &extract_categories()
                   16778: 
                   16779: Used to generate breadcrumb trails for course categories.
                   16780: 
                   16781: Inputs:
1.663     raeburn  16782: 
1.655     raeburn  16783: categories (reference to hash of category definitions).
1.663     raeburn  16784: 
1.655     raeburn  16785: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16786:       categories and subcategories).
1.663     raeburn  16787: 
1.655     raeburn  16788: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16789: 
1.655     raeburn  16790: allitems (reference to hash - key is category key 
                   16791:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16792: 
1.655     raeburn  16793: idx (reference to hash of counters used in Domain Coordinator interface for
                   16794:       editing Course Categories).
1.663     raeburn  16795: 
1.655     raeburn  16796: jsarray (reference to array of categories used to create Javascript arrays for
                   16797:          Domain Coordinator interface for editing Course Categories).
                   16798: 
1.665     raeburn  16799: subcats (reference to hash of arrays containing all subcategories within each 
                   16800:          category, -recursive)
                   16801: 
1.1321    raeburn  16802: maxd (reference to hash used to hold max depth for all top-level categories).
                   16803: 
1.655     raeburn  16804: Returns: nothing
                   16805: 
                   16806: Side effects: populates trails and allitems hash references.
                   16807: 
                   16808: =cut
                   16809: 
                   16810: sub extract_categories {
1.1321    raeburn  16811:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16812:     if (ref($categories) eq 'HASH') {
                   16813:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16814:         if (ref($cats->[0]) eq 'ARRAY') {
                   16815:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16816:                 my $name = $cats->[0][$i];
                   16817:                 my $item = &escape($name).'::0';
                   16818:                 my $trailstr;
                   16819:                 if ($name eq 'instcode') {
                   16820:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16821:                 } elsif ($name eq 'communities') {
                   16822:                     $trailstr = &mt('Communities');
1.1239    raeburn  16823:                 } elsif ($name eq 'placement') {
                   16824:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16825:                 } else {
                   16826:                     $trailstr = $name;
                   16827:                 }
                   16828:                 if ($allitems->{$item} eq '') {
                   16829:                     push(@{$trails},$trailstr);
                   16830:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16831:                 }
                   16832:                 my @parents = ($name);
                   16833:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16834:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16835:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16836:                         if (ref($subcats) eq 'HASH') {
                   16837:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16838:                         }
1.1321    raeburn  16839:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16840:                     }
                   16841:                 } else {
                   16842:                     if (ref($subcats) eq 'HASH') {
                   16843:                         $subcats->{$item} = [];
1.655     raeburn  16844:                     }
1.1321    raeburn  16845:                     if (ref($maxd) eq 'HASH') {
                   16846:                         $maxd->{$name} = 1;
                   16847:                     }
1.655     raeburn  16848:                 }
                   16849:             }
                   16850:         }
                   16851:     }
                   16852:     return;
                   16853: }
                   16854: 
                   16855: =pod
                   16856: 
1.1162    raeburn  16857: =item * &recurse_categories()
1.655     raeburn  16858: 
                   16859: Recursively used to generate breadcrumb trails for course categories.
                   16860: 
                   16861: Inputs:
1.663     raeburn  16862: 
1.655     raeburn  16863: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16864:       categories and subcategories).
1.663     raeburn  16865: 
1.655     raeburn  16866: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16867: 
                   16868: category (current course category, for which breadcrumb trail is being generated).
                   16869: 
                   16870: trails (reference to array of breadcrumb trails for each category).
                   16871: 
1.655     raeburn  16872: allitems (reference to hash - key is category key
                   16873:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16874: 
1.655     raeburn  16875: parents (array containing containers directories for current category, 
                   16876:          back to top level). 
                   16877: 
                   16878: Returns: nothing
                   16879: 
                   16880: Side effects: populates trails and allitems hash references
                   16881: 
                   16882: =cut
                   16883: 
                   16884: sub recurse_categories {
1.1321    raeburn  16885:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16886:     my $shallower = $depth - 1;
                   16887:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16888:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16889:             my $name = $cats->[$depth]{$category}[$k];
                   16890:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16891:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16892:             if ($allitems->{$item} eq '') {
                   16893:                 push(@{$trails},$trailstr);
                   16894:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16895:             }
                   16896:             my $deeper = $depth+1;
                   16897:             push(@{$parents},$category);
1.665     raeburn  16898:             if (ref($subcats) eq 'HASH') {
                   16899:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16900:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16901:                     my $higher;
                   16902:                     if ($j > 0) {
                   16903:                         $higher = &escape($parents->[$j]).':'.
                   16904:                                   &escape($parents->[$j-1]).':'.$j;
                   16905:                     } else {
                   16906:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16907:                     }
                   16908:                     push(@{$subcats->{$higher}},$subcat);
                   16909:                 }
                   16910:             }
                   16911:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16912:                                 $subcats,$maxd);
1.655     raeburn  16913:             pop(@{$parents});
                   16914:         }
                   16915:     } else {
                   16916:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16917:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16918:         if ($allitems->{$item} eq '') {
                   16919:             push(@{$trails},$trailstr);
                   16920:             $allitems->{$item} = scalar(@{$trails})-1;
                   16921:         }
1.1321    raeburn  16922:         if (ref($maxd) eq 'HASH') {
                   16923:             if ($depth > $maxd->{$parents->[0]}) {
                   16924:                 $maxd->{$parents->[0]} = $depth;
                   16925:             }
                   16926:         }
1.655     raeburn  16927:     }
                   16928:     return;
                   16929: }
                   16930: 
1.663     raeburn  16931: =pod
                   16932: 
1.1162    raeburn  16933: =item * &assign_categories_table()
1.663     raeburn  16934: 
                   16935: Create a datatable for display of hierarchical categories in a domain,
                   16936: with checkboxes to allow a course to be categorized. 
                   16937: 
                   16938: Inputs:
                   16939: 
                   16940: cathash - reference to hash of categories defined for the domain (from
                   16941:           configuration.db)
                   16942: 
                   16943: currcat - scalar with an & separated list of categories assigned to a course. 
                   16944: 
1.919     raeburn  16945: type    - scalar contains course type (Course or Community).
                   16946: 
1.1260    raeburn  16947: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16948:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16949: 
1.663     raeburn  16950: Returns: $output (markup to be displayed) 
                   16951: 
                   16952: =cut
                   16953: 
                   16954: sub assign_categories_table {
1.1259    raeburn  16955:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16956:     my $output;
                   16957:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16958:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16959:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16960:         $maxdepth = scalar(@cats);
                   16961:         if (@cats > 0) {
                   16962:             my $itemcount = 0;
                   16963:             if (ref($cats[0]) eq 'ARRAY') {
                   16964:                 my @currcategories;
                   16965:                 if ($currcat ne '') {
                   16966:                     @currcategories = split('&',$currcat);
                   16967:                 }
1.919     raeburn  16968:                 my $table;
1.663     raeburn  16969:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16970:                     my $parent = $cats[0][$i];
1.919     raeburn  16971:                     next if ($parent eq 'instcode');
                   16972:                     if ($type eq 'Community') {
                   16973:                         next unless ($parent eq 'communities');
1.1239    raeburn  16974:                     } elsif ($type eq 'Placement') {
                   16975:                         next unless ($parent eq 'placement');
1.919     raeburn  16976:                     } else {
1.1239    raeburn  16977:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16978:                     }
1.663     raeburn  16979:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16980:                     my $item = &escape($parent).'::0';
                   16981:                     my $checked = '';
                   16982:                     if (@currcategories > 0) {
                   16983:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16984:                             $checked = ' checked="checked"';
1.663     raeburn  16985:                         }
                   16986:                     }
1.919     raeburn  16987:                     my $parent_title = $parent;
                   16988:                     if ($parent eq 'communities') {
                   16989:                         $parent_title = &mt('Communities');
1.1239    raeburn  16990:                     } elsif ($parent eq 'placement') {
                   16991:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16992:                     }
                   16993:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16994:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16995:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16996:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16997:                     my $depth = 1;
                   16998:                     push(@path,$parent);
1.1259    raeburn  16999:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  17000:                     pop(@path);
1.919     raeburn  17001:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  17002:                     $itemcount ++;
                   17003:                 }
1.919     raeburn  17004:                 if ($itemcount) {
                   17005:                     $output = &Apache::loncommon::start_data_table().
                   17006:                               $table.
                   17007:                               &Apache::loncommon::end_data_table();
                   17008:                 }
1.663     raeburn  17009:             }
                   17010:         }
                   17011:     }
                   17012:     return $output;
                   17013: }
                   17014: 
                   17015: =pod
                   17016: 
1.1162    raeburn  17017: =item * &assign_category_rows()
1.663     raeburn  17018: 
                   17019: Create a datatable row for display of nested categories in a domain,
                   17020: with checkboxes to allow a course to be categorized,called recursively.
                   17021: 
                   17022: Inputs:
                   17023: 
                   17024: itemcount - track row number for alternating colors
                   17025: 
                   17026: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   17027:       categories and subcategories.
                   17028: 
                   17029: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   17030: 
                   17031: parent - parent of current category item
                   17032: 
                   17033: path - Array containing all categories back up through the hierarchy from the
                   17034:        current category to the top level.
                   17035: 
                   17036: currcategories - reference to array of current categories assigned to the course
                   17037: 
1.1260    raeburn  17038: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   17039:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   17040: 
1.663     raeburn  17041: Returns: $output (markup to be displayed).
                   17042: 
                   17043: =cut
                   17044: 
                   17045: sub assign_category_rows {
1.1259    raeburn  17046:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  17047:     my ($text,$name,$item,$chgstr);
                   17048:     if (ref($cats) eq 'ARRAY') {
                   17049:         my $maxdepth = scalar(@{$cats});
                   17050:         if (ref($cats->[$depth]) eq 'HASH') {
                   17051:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   17052:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   17053:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  17054:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  17055:                 for (my $j=0; $j<$numchildren; $j++) {
                   17056:                     $name = $cats->[$depth]{$parent}[$j];
                   17057:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   17058:                     my $deeper = $depth+1;
                   17059:                     my $checked = '';
                   17060:                     if (ref($currcategories) eq 'ARRAY') {
                   17061:                         if (@{$currcategories} > 0) {
                   17062:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   17063:                                 $checked = ' checked="checked"';
1.663     raeburn  17064:                             }
                   17065:                         }
                   17066:                     }
1.664     raeburn  17067:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   17068:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  17069:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  17070:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   17071:                              '</td><td>';
1.663     raeburn  17072:                     if (ref($path) eq 'ARRAY') {
                   17073:                         push(@{$path},$name);
1.1259    raeburn  17074:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  17075:                         pop(@{$path});
                   17076:                     }
                   17077:                     $text .= '</td></tr>';
                   17078:                 }
                   17079:                 $text .= '</table></td>';
                   17080:             }
                   17081:         }
                   17082:     }
                   17083:     return $text;
                   17084: }
                   17085: 
1.1181    raeburn  17086: =pod
                   17087: 
                   17088: =back
                   17089: 
                   17090: =cut
                   17091: 
1.655     raeburn  17092: ############################################################
                   17093: ############################################################
                   17094: 
                   17095: 
1.443     albertel 17096: sub commit_customrole {
1.1408    raeburn  17097:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
1.1399    raeburn  17098:     my $result = &Apache::lonnet::assigncustomrole(
1.1408    raeburn  17099:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
                   17100:                      $context,$othdomby,$requester);
1.630     raeburn  17101:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 17102:                          ($start?', '.&mt('starting').' '.localtime($start):'').
1.1399    raeburn  17103:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
                   17104:     if (wantarray) {
                   17105:         return ($output,$result);
                   17106:     } else {
                   17107:         return $output;
                   17108:     }
1.443     albertel 17109: }
                   17110: 
                   17111: sub commit_standardrole {
1.1408    raeburn  17112:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
                   17113:         $othdomby,$requester) = @_;
1.1399    raeburn  17114:     my ($output,$logmsg,$linefeed,$result);
1.541     raeburn  17115:     if ($context eq 'auto') {
                   17116:         $linefeed = "\n";
                   17117:     } else {
                   17118:         $linefeed = "<br />\n";
                   17119:     }  
1.443     albertel 17120:     if ($three eq 'st') {
1.1399    raeburn  17121:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1408    raeburn  17122:                                       $one,$two,$sec,$context,$credits,$othdomby,
                   17123:                                       $requester);
1.541     raeburn  17124:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  17125:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   17126:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 17127:         } else {
1.541     raeburn  17128:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 17129:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17130:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   17131:             if ($context eq 'auto') {
                   17132:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   17133:             } else {
                   17134:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   17135:                &mt('Add to classlist').': <b>ok</b>';
                   17136:             }
                   17137:             $output .= $linefeed;
1.443     albertel 17138:         }
                   17139:     } else {
                   17140:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   17141:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17142:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.1408    raeburn  17143:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
                   17144:                                               '','',$context,$othdomby,$requester);
1.541     raeburn  17145:         if ($context eq 'auto') {
                   17146:             $output .= $result.$linefeed;
                   17147:         } else {
                   17148:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   17149:         }
1.443     albertel 17150:     }
1.1399    raeburn  17151:     if (wantarray) {
                   17152:         return ($output,$result);
                   17153:     } else {
                   17154:         return $output;
                   17155:     }
1.443     albertel 17156: }
                   17157: 
                   17158: sub commit_studentrole {
1.1116    raeburn  17159:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
1.1408    raeburn  17160:         $credits,$othdomby,$requester) = @_;
1.626     raeburn  17161:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  17162:     if ($context eq 'auto') {
                   17163:         $linefeed = "\n";
                   17164:     } else {
                   17165:         $linefeed = '<br />'."\n";
                   17166:     }
1.443     albertel 17167:     if (defined($one) && defined($two)) {
                   17168:         my $cid=$one.'_'.$two;
                   17169:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   17170:         my $secchange = 0;
                   17171:         my $expire_role_result;
                   17172:         my $modify_section_result;
1.628     raeburn  17173:         if ($oldsec ne '-1') { 
                   17174:             if ($oldsec ne $sec) {
1.443     albertel 17175:                 $secchange = 1;
1.628     raeburn  17176:                 my $now = time;
1.443     albertel 17177:                 my $uurl='/'.$cid;
                   17178:                 $uurl=~s/\_/\//g;
                   17179:                 if ($oldsec) {
                   17180:                     $uurl.='/'.$oldsec;
                   17181:                 }
1.626     raeburn  17182:                 $oldsecurl = $uurl;
1.628     raeburn  17183:                 $expire_role_result = 
1.1408    raeburn  17184:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
                   17185:                                                 '','','',$context,$othdomby,$requester);
                   17186:                 if ($env{'request.course.sec'} ne '') {
1.628     raeburn  17187:                     if ($expire_role_result eq 'refused') {
                   17188:                         my @roles = ('st');
                   17189:                         my @statuses = ('previous');
                   17190:                         my @roledoms = ($one);
                   17191:                         my $withsec = 1;
                   17192:                         my %roleshash = 
                   17193:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   17194:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   17195:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   17196:                             my ($oldstart,$oldend) = 
                   17197:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   17198:                             if ($oldend > 0 && $oldend <= $now) {
                   17199:                                 $expire_role_result = 'ok';
                   17200:                             }
                   17201:                         }
                   17202:                     }
                   17203:                 }
1.443     albertel 17204:                 $result = $expire_role_result;
                   17205:             }
                   17206:         }
                   17207:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  17208:             $modify_section_result = 
                   17209:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   17210:                                                            undef,undef,undef,$sec,
                   17211:                                                            $end,$start,'','',$cid,
1.1408    raeburn  17212:                                                            '',$context,$credits,'',
                   17213:                                                            $othdomby,$requester);
1.443     albertel 17214:             if ($modify_section_result =~ /^ok/) {
                   17215:                 if ($secchange == 1) {
1.628     raeburn  17216:                     if ($sec eq '') {
                   17217:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   17218:                     } else {
                   17219:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   17220:                     }
1.443     albertel 17221:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  17222:                     if ($sec eq '') {
                   17223:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   17224:                     } else {
                   17225:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17226:                     }
1.443     albertel 17227:                 } else {
1.628     raeburn  17228:                     if ($sec eq '') {
                   17229:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   17230:                     } else {
                   17231:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17232:                     }
1.443     albertel 17233:                 }
                   17234:             } else {
1.1115    raeburn  17235:                 if ($secchange) { 
1.628     raeburn  17236:                     $$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;
                   17237:                 } else {
                   17238:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   17239:                 }
1.443     albertel 17240:             }
                   17241:             $result = $modify_section_result;
                   17242:         } elsif ($secchange == 1) {
1.628     raeburn  17243:             if ($oldsec eq '') {
1.1103    raeburn  17244:                 $$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  17245:             } else {
                   17246:                 $$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;
                   17247:             }
1.626     raeburn  17248:             if ($expire_role_result eq 'refused') {
                   17249:                 my $newsecurl = '/'.$cid;
                   17250:                 $newsecurl =~ s/\_/\//g;
                   17251:                 if ($sec ne '') {
                   17252:                     $newsecurl.='/'.$sec;
                   17253:                 }
                   17254:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   17255:                     if ($sec eq '') {
                   17256:                         $$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;
                   17257:                     } else {
                   17258:                         $$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;
                   17259:                     }
                   17260:                 }
                   17261:             }
1.443     albertel 17262:         }
                   17263:     } else {
1.626     raeburn  17264:         $$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 17265:         $result = "error: incomplete course id\n";
                   17266:     }
                   17267:     return $result;
                   17268: }
                   17269: 
1.1108    raeburn  17270: sub show_role_extent {
                   17271:     my ($scope,$context,$role) = @_;
                   17272:     $scope =~ s{^/}{};
                   17273:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   17274:     push(@courseroles,'co');
                   17275:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   17276:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   17277:         $scope =~ s{/}{_};
                   17278:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   17279:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   17280:         my ($audom,$auname) = split(/\//,$scope);
                   17281:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   17282:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   17283:     } else {
                   17284:         $scope =~ s{/$}{};
                   17285:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   17286:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   17287:     }
                   17288: }
                   17289: 
1.443     albertel 17290: ############################################################
                   17291: ############################################################
                   17292: 
1.566     albertel 17293: sub check_clone {
1.578     raeburn  17294:     my ($args,$linefeed) = @_;
1.566     albertel 17295:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   17296:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   17297:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  17298:     my $clonetitle;
                   17299:     my @clonemsg;
1.566     albertel 17300:     my $can_clone = 0;
1.944     raeburn  17301:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  17302:     if ($lctype ne 'community') {
                   17303:         $lctype = 'course';
                   17304:     }
1.566     albertel 17305:     if ($clonehome eq 'no_host') {
1.944     raeburn  17306:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17307:             push(@clonemsg,({
                   17308:                               mt => 'No new community created.',
                   17309:                               args => [],
                   17310:                             },
                   17311:                             {
                   17312:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   17313:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   17314:                             }));
1.908     raeburn  17315:         } else {
1.1344    raeburn  17316:             push(@clonemsg,({
                   17317:                               mt => 'No new course created.',
                   17318:                               args => [],
                   17319:                             },
                   17320:                             {
                   17321:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   17322:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17323:                             }));
                   17324:         }
1.566     albertel 17325:     } else {
                   17326: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  17327:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  17328:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  17329:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  17330:                 push(@clonemsg,({
                   17331:                                   mt => 'No new community created.',
                   17332:                                   args => [],
                   17333:                                 },
                   17334:                                 {
                   17335:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   17336:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17337:                                 }));
                   17338:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  17339:             }
                   17340:         }
1.1262    raeburn  17341: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  17342:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 17343: 	    $can_clone = 1;
                   17344: 	} else {
1.1221    raeburn  17345: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 17346: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  17347:             if ($clonehash{'cloners'} eq '') {
                   17348:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   17349:                 if ($domdefs{'canclone'}) {
                   17350:                     unless ($domdefs{'canclone'} eq 'none') {
                   17351:                         if ($domdefs{'canclone'} eq 'domain') {
                   17352:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   17353:                                 $can_clone = 1;
                   17354:                             }
                   17355:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17356:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   17357:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   17358:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   17359:                                 $can_clone = 1;
                   17360:                             }
                   17361:                         }
                   17362:                     }
                   17363:                 }
1.578     raeburn  17364:             } else {
1.1221    raeburn  17365: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   17366:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  17367:                     $can_clone = 1;
1.1221    raeburn  17368:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  17369:                     $can_clone = 1;
1.1225    raeburn  17370:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   17371:                     $can_clone = 1;
1.1221    raeburn  17372:                 }
                   17373:                 unless ($can_clone) {
1.1225    raeburn  17374:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17375:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  17376:                         my (%gotdomdefaults,%gotcodedefaults);
                   17377:                         foreach my $cloner (@cloners) {
                   17378:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   17379:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   17380:                                 my (%codedefaults,@code_order);
                   17381:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   17382:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   17383:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   17384:                                     }
                   17385:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   17386:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   17387:                                     }
                   17388:                                 } else {
                   17389:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   17390:                                                                             \%codedefaults,
                   17391:                                                                             \@code_order);
                   17392:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   17393:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   17394:                                 }
                   17395:                                 if (@code_order > 0) {
                   17396:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   17397:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   17398:                                                                                 $args->{'crscode'})) {
                   17399:                                         $can_clone = 1;
                   17400:                                         last;
                   17401:                                     }
                   17402:                                 }
                   17403:                             }
                   17404:                         }
                   17405:                     }
1.1225    raeburn  17406:                 }
                   17407:             }
                   17408:             unless ($can_clone) {
                   17409:                 my $ccrole = 'cc';
                   17410:                 if ($args->{'crstype'} eq 'Community') {
                   17411:                     $ccrole = 'co';
                   17412:                 }
                   17413: 	        my %roleshash =
                   17414: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   17415: 					          $args->{'ccdomain'},
                   17416:                                                   'userroles',['active'],[$ccrole],
                   17417: 					          [$args->{'clonedomain'}]);
                   17418: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   17419:                     $can_clone = 1;
                   17420:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   17421:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   17422:                     $can_clone = 1;
1.1221    raeburn  17423:                 }
                   17424:             }
                   17425:             unless ($can_clone) {
                   17426:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17427:                     push(@clonemsg,({
                   17428:                                       mt => 'No new community created.',
                   17429:                                       args => [],
                   17430:                                     },
                   17431:                                     {
                   17432:                                       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]).',
                   17433:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17434:                                     }));
1.942     raeburn  17435:                 } else {
1.1344    raeburn  17436:                     push(@clonemsg,({
                   17437:                                       mt => 'No new course created.',
                   17438:                                       args => [],
                   17439:                                     },
                   17440:                                     {
                   17441:                                       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]).',
                   17442:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17443:                                     }));
1.1221    raeburn  17444:                 }
1.566     albertel 17445: 	    }
1.578     raeburn  17446:         }
1.566     albertel 17447:     }
1.1344    raeburn  17448:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17449: }
                   17450: 
1.444     albertel 17451: sub construct_course {
1.1262    raeburn  17452:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  17453:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   17454:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  17455:     my $linefeed =  '<br />'."\n";
                   17456:     if ($context eq 'auto') {
                   17457:         $linefeed = "\n";
                   17458:     }
1.566     albertel 17459: 
                   17460: #
                   17461: # Are we cloning?
                   17462: #
1.1344    raeburn  17463:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17464:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  17465: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 17466:         if (!$can_clone) {
1.1344    raeburn  17467: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 17468: 	}
                   17469:     }
                   17470: 
1.444     albertel 17471: #
                   17472: # Open course
                   17473: #
1.1239    raeburn  17474:     my $showncrstype;
                   17475:     if ($args->{'crstype'} eq 'Placement') {
                   17476:         $showncrstype = 'placement test'; 
                   17477:     } else {  
                   17478:         $showncrstype = lc($args->{'crstype'});
                   17479:     }
1.444     albertel 17480:     my %cenv=();
                   17481:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   17482:                                              $args->{'cdescr'},
                   17483:                                              $args->{'curl'},
                   17484:                                              $args->{'course_home'},
                   17485:                                              $args->{'nonstandard'},
                   17486:                                              $args->{'crscode'},
                   17487:                                              $args->{'ccuname'}.':'.
                   17488:                                              $args->{'ccdomain'},
1.882     raeburn  17489:                                              $args->{'crstype'},
1.1344    raeburn  17490:                                              $cnum,$context,$category,
                   17491:                                              $callercontext);
1.444     albertel 17492: 
                   17493:     # Note: The testing routines depend on this being output; see 
                   17494:     # Utils::Course. This needs to at least be output as a comment
                   17495:     # if anyone ever decides to not show this, and Utils::Course::new
                   17496:     # will need to be suitably modified.
1.1344    raeburn  17497:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17498:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17499:     } else {
                   17500:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17501:     }
1.943     raeburn  17502:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  17503:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17504:     }
                   17505: 
1.444     albertel 17506: #
                   17507: # Check if created correctly
                   17508: #
1.479     albertel 17509:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 17510:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  17511:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  17512:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17513:             $outcome .= &mt_user($user_lh,
                   17514:                             'Course creation failed, unrecognized course home server.');
                   17515:         } else {
                   17516:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   17517:         }
                   17518:         $outcome .= $linefeed;
                   17519:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17520:     }
1.541     raeburn  17521:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 17522: 
1.444     albertel 17523: #
1.566     albertel 17524: # Do the cloning
                   17525: #   
1.1344    raeburn  17526:     my @clonemsg;
1.566     albertel 17527:     if ($can_clone && $cloneid) {
1.1344    raeburn  17528:         push(@clonemsg,
                   17529:                       {
                   17530:                           mt => 'Created [_1] by cloning from [_2]',
                   17531:                           args => [$showncrstype,$clonetitle],
                   17532:                       });
1.566     albertel 17533: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 17534: # Copy all files
1.1344    raeburn  17535:         my @info =
                   17536: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   17537: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   17538:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   17539:                                                      $args->{'tinyurls'});
                   17540:         if (@info) {
                   17541:             push(@clonemsg,@info);
                   17542:         }
1.444     albertel 17543: # Restore URL
1.566     albertel 17544: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 17545: # Restore title
1.566     albertel 17546: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  17547: # Restore creation date, creator and creation context.
                   17548:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   17549:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   17550:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 17551: # Mark as cloned
1.566     albertel 17552: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      17553: # Need to clone grading mode
                   17554:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   17555:         $cenv{'grading'}=$newenv{'grading'};
                   17556: # Do not clone these environment entries
                   17557:         &Apache::lonnet::del('environment',
                   17558:                   ['default_enrollment_start_date',
                   17559:                    'default_enrollment_end_date',
                   17560:                    'question.email',
                   17561:                    'policy.email',
                   17562:                    'comment.email',
                   17563:                    'pch.users.denied',
1.725     raeburn  17564:                    'plc.users.denied',
                   17565:                    'hidefromcat',
1.1121    raeburn  17566:                    'checkforpriv',
1.1355    raeburn  17567:                    'categories'],
1.638     www      17568:                    $$crsudom,$$crsunum);
1.1170    raeburn  17569:         if ($args->{'textbook'}) {
                   17570:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   17571:         }
1.444     albertel 17572:     }
1.566     albertel 17573: 
1.444     albertel 17574: #
                   17575: # Set environment (will override cloned, if existing)
                   17576: #
                   17577:     my @sections = ();
                   17578:     my @xlists = ();
                   17579:     if ($args->{'crstype'}) {
                   17580:         $cenv{'type'}=$args->{'crstype'};
                   17581:     }
1.1371    raeburn  17582:     if ($args->{'lti'}) {
                   17583:         $cenv{'internal.lti'}=$args->{'lti'};
                   17584:     }
1.444     albertel 17585:     if ($args->{'crsid'}) {
                   17586:         $cenv{'courseid'}=$args->{'crsid'};
                   17587:     }
                   17588:     if ($args->{'crscode'}) {
                   17589:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   17590:     }
                   17591:     if ($args->{'crsquota'} ne '') {
                   17592:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   17593:     } else {
                   17594:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   17595:     }
                   17596:     if ($args->{'ccuname'}) {
                   17597:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   17598:                                         ':'.$args->{'ccdomain'};
                   17599:     } else {
                   17600:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   17601:     }
1.1116    raeburn  17602:     if ($args->{'defaultcredits'}) {
                   17603:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   17604:     }
1.444     albertel 17605:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1412    raeburn  17606:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 17607:     if ($args->{'crssections'}) {
                   17608:         $cenv{'internal.sectionnums'} = '';
                   17609:         if ($args->{'crssections'} =~ m/,/) {
                   17610:             @sections = split/,/,$args->{'crssections'};
                   17611:         } else {
                   17612:             $sections[0] = $args->{'crssections'};
                   17613:         }
                   17614:         if (@sections > 0) {
                   17615:             foreach my $item (@sections) {
                   17616:                 my ($sec,$gp) = split/:/,$item;
                   17617:                 my $class = $args->{'crscode'}.$sec;
                   17618:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   17619:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1412    raeburn  17620:                 if ($addcheck eq 'ok') {
                   17621:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17622:                         push(@oklcsecs,$gp);
                   17623:                     }
                   17624:                 } else {
1.1263    raeburn  17625:                     push(@badclasses,$class);
1.444     albertel 17626:                 }
                   17627:             }
                   17628:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   17629:         }
                   17630:     }
                   17631: # do not hide course coordinator from staff listing, 
                   17632: # even if privileged
                   17633:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  17634: # add course coordinator's domain to domains to check for privileged users
                   17635: # if different to course domain
                   17636:     if ($$crsudom ne $args->{'ccdomain'}) {
                   17637:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   17638:     }
1.444     albertel 17639: # add crosslistings
                   17640:     if ($args->{'crsxlist'}) {
                   17641:         $cenv{'internal.crosslistings'}='';
                   17642:         if ($args->{'crsxlist'} =~ m/,/) {
                   17643:             @xlists = split/,/,$args->{'crsxlist'};
                   17644:         } else {
                   17645:             $xlists[0] = $args->{'crsxlist'};
                   17646:         }
                   17647:         if (@xlists > 0) {
                   17648:             foreach my $item (@xlists) {
                   17649:                 my ($xl,$gp) = split/:/,$item;
                   17650:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   17651:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1412    raeburn  17652:                 if ($addcheck eq 'ok') {
                   17653:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17654:                         push(@oklcsecs,$gp);
                   17655:                     }
                   17656:                 } else {
1.1263    raeburn  17657:                     push(@badclasses,$xl);
1.444     albertel 17658:                 }
                   17659:             }
                   17660:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   17661:         }
                   17662:     }
                   17663:     if ($args->{'autoadds'}) {
                   17664:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   17665:     }
                   17666:     if ($args->{'autodrops'}) {
                   17667:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   17668:     }
                   17669: # check for notification of enrollment changes
                   17670:     my @notified = ();
                   17671:     if ($args->{'notify_owner'}) {
                   17672:         if ($args->{'ccuname'} ne '') {
                   17673:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   17674:         }
                   17675:     }
                   17676:     if ($args->{'notify_dc'}) {
                   17677:         if ($uname ne '') { 
1.630     raeburn  17678:             push(@notified,$uname.':'.$udom);
1.444     albertel 17679:         }
                   17680:     }
                   17681:     if (@notified > 0) {
                   17682:         my $notifylist;
                   17683:         if (@notified > 1) {
                   17684:             $notifylist = join(',',@notified);
                   17685:         } else {
                   17686:             $notifylist = $notified[0];
                   17687:         }
                   17688:         $cenv{'internal.notifylist'} = $notifylist;
                   17689:     }
                   17690:     if (@badclasses > 0) {
                   17691:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  17692:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   17693:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   17694:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 17695:         );
1.1264    raeburn  17696:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   17697:                            &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  17698:         if ($context eq 'auto') {
                   17699:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  17700:         } else {
1.566     albertel 17701:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  17702:         }
                   17703:         foreach my $item (@badclasses) {
1.541     raeburn  17704:             if ($context eq 'auto') {
1.1261    raeburn  17705:                 $outcome .= " - $item\n";
1.541     raeburn  17706:             } else {
1.1261    raeburn  17707:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  17708:             }
1.1261    raeburn  17709:         }
                   17710:         if ($context eq 'auto') {
                   17711:             $outcome .= $linefeed;
                   17712:         } else {
                   17713:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  17714:         } 
1.444     albertel 17715:     }
                   17716:     if ($args->{'no_end_date'}) {
                   17717:         $args->{'endaccess'} = 0;
                   17718:     }
1.1412    raeburn  17719: #  If an official course with institutional sections is created by cloning 
                   17720: #  an existing course, section-specific hiding of course totals in student's
                   17721: #  view of grades as copied from cloned course, will be checked for valid 
                   17722: #  sections.
                   17723:     if (($can_clone && $cloneid) &&
                   17724:         ($cenv{'internal.coursecode'} ne '') &&
                   17725:         ($cenv{'grading'} eq 'standard') &&
                   17726:         ($cenv{'hidetotals'} ne '') &&
                   17727:         ($cenv{'hidetotals'} ne 'all')) {
                   17728:         my @hidesecs;
                   17729:         my $deletehidetotals;
                   17730:         if (@oklcsecs) {
                   17731:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   17732:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   17733:                     push(@hidesecs,$sec);
                   17734:                 }
                   17735:             }
                   17736:             if (@hidesecs) {
                   17737:                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   17738:             } else {
                   17739:                 $deletehidetotals = 1;
                   17740:             }
                   17741:         } else {
                   17742:             $deletehidetotals = 1;
                   17743:         }
                   17744:         if ($deletehidetotals) {
                   17745:             delete($cenv{'hidetotals'});
                   17746:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   17747:         }
                   17748:     }
1.444     albertel 17749:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   17750:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   17751:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   17752:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   17753:     if ($args->{'showphotos'}) {
                   17754:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   17755:     }
                   17756:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   17757:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   17758:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   17759:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  17760:             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'); 
                   17761:             if ($context eq 'auto') {
                   17762:                 $outcome .= $krb_msg;
                   17763:             } else {
1.566     albertel 17764:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  17765:             }
                   17766:             $outcome .= $linefeed;
1.444     albertel 17767:         }
                   17768:     }
                   17769:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   17770:        if ($args->{'setpolicy'}) {
                   17771:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17772:        }
                   17773:        if ($args->{'setcontent'}) {
                   17774:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17775:        }
1.1251    raeburn  17776:        if ($args->{'setcomment'}) {
                   17777:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17778:        }
1.444     albertel 17779:     }
                   17780:     if ($args->{'reshome'}) {
                   17781: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   17782: 	$cenv{'reshome'}=~s/\/+$/\//;
                   17783:     }
                   17784: #
                   17785: # course has keyed access
                   17786: #
                   17787:     if ($args->{'setkeys'}) {
                   17788:        $cenv{'keyaccess'}='yes';
                   17789:     }
                   17790: # if specified, key authority is not course, but user
                   17791: # only active if keyaccess is yes
                   17792:     if ($args->{'keyauth'}) {
1.487     albertel 17793: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   17794: 	$user = &LONCAPA::clean_username($user);
                   17795: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     17796: 	if ($user ne '' && $domain ne '') {
1.487     albertel 17797: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 17798: 	}
                   17799:     }
                   17800: 
1.1166    raeburn  17801: #
1.1167    raeburn  17802: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17803: #
                   17804:     if ($args->{'uniquecode'}) {
                   17805:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17806:         if ($code) {
                   17807:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17808:             my %crsinfo =
                   17809:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17810:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17811:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17812:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17813:             } 
1.1166    raeburn  17814:             if (ref($coderef)) {
                   17815:                 $$coderef = $code;
                   17816:             }
                   17817:         }
                   17818:     }
                   17819: 
1.444     albertel 17820:     if ($args->{'disresdis'}) {
                   17821:         $cenv{'pch.roles.denied'}='st';
                   17822:     }
                   17823:     if ($args->{'disablechat'}) {
                   17824:         $cenv{'plc.roles.denied'}='st';
                   17825:     }
                   17826: 
                   17827:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17828:     # course
                   17829:     $cenv{'course.helper.not.run'} = 1;
                   17830:     #
                   17831:     # Use new Randomseed
                   17832:     #
                   17833:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17834:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17835:     #
                   17836:     # The encryption code and receipt prefix for this course
                   17837:     #
                   17838:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17839:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17840:     #
                   17841:     # By default, use standard grading
                   17842:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17843: 
1.541     raeburn  17844:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17845:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17846: #
                   17847: # Open all assignments
                   17848: #
                   17849:     if ($args->{'openall'}) {
1.1341    raeburn  17850:        my $opendate = time;
                   17851:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17852:            $opendate = $args->{'openallfrom'};
                   17853:        }
1.444     albertel 17854:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17855:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17856:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17857:        $outcome .= &mt('All assignments open starting [_1]',
                   17858:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17859:                    &Apache::lonnet::cput
                   17860:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17861:    }
                   17862: #
                   17863: # Set first page
                   17864: #
                   17865:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17866: 	    || ($cloneid)) {
                   17867: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17868: 
                   17869: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17870:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17871: 
1.444     albertel 17872:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17873:         my $title; my $url;
                   17874:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17875: 	    $title=&mt('Syllabus');
1.444     albertel 17876:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17877:         } else {
1.963     raeburn  17878:             $title=&mt('Table of Contents');
1.444     albertel 17879:             $url='/adm/navmaps';
                   17880:         }
1.445     albertel 17881: 
                   17882:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17883: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17884: 
                   17885: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17886:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17887:     }
1.566     albertel 17888: 
1.1237    raeburn  17889: # 
                   17890: # Set params for Placement Tests
                   17891: #
1.1239    raeburn  17892:     if ($args->{'crstype'} eq 'Placement') {
                   17893:        my %storecontent; 
                   17894:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17895:        my %defaults = (
                   17896:                         buttonshide   => { value => 'yes',
                   17897:                                            type => 'string_yesno',},
                   17898:                         type          => { value => 'randomizetry',
                   17899:                                            type  => 'string_questiontype',},
                   17900:                         maxtries      => { value => 1,
                   17901:                                            type => 'int_pos',},
                   17902:                         problemstatus => { value => 'no',
                   17903:                                            type  => 'string_problemstatus',},
                   17904:                       );
                   17905:        foreach my $key (keys(%defaults)) {
                   17906:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17907:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17908:        }
1.1237    raeburn  17909:        &Apache::lonnet::cput
                   17910:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17911:     }
                   17912: 
1.1344    raeburn  17913:     return (1,$outcome,\@clonemsg);
1.444     albertel 17914: }
                   17915: 
1.1166    raeburn  17916: sub make_unique_code {
                   17917:     my ($cdom,$cnum) = @_;
                   17918:     # get lock on uniquecodes db
                   17919:     my $lockhash = {
                   17920:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17921:                                                   ':'.$env{'user.domain'},
                   17922:                    };
                   17923:     my $tries = 0;
                   17924:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17925:     my ($code,$error);
                   17926:   
                   17927:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17928:         $tries ++;
                   17929:         sleep 1;
                   17930:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17931:     }
                   17932:     if ($gotlock eq 'ok') {
                   17933:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17934:         my $gotcode;
                   17935:         my $attempts = 0;
                   17936:         while ((!$gotcode) && ($attempts < 100)) {
                   17937:             $code = &generate_code();
                   17938:             if (!exists($currcodes{$code})) {
                   17939:                 $gotcode = 1;
                   17940:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17941:                     $error = 'nostore';
                   17942:                 }
                   17943:             }
                   17944:             $attempts ++;
                   17945:         }
                   17946:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17947:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17948:     } else {
                   17949:         $error = 'nolock';
                   17950:     }
                   17951:     return ($code,$error);
                   17952: }
                   17953: 
                   17954: sub generate_code {
                   17955:     my $code;
                   17956:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17957:     for (my $i=0; $i<6; $i++) {
                   17958:         my $lettnum = int (rand 2);
                   17959:         my $item = '';
                   17960:         if ($lettnum) {
                   17961:             $item = $letts[int( rand(18) )];
                   17962:         } else {
                   17963:             $item = 1+int( rand(8) );
                   17964:         }
                   17965:         $code .= $item;
                   17966:     }
                   17967:     return $code;
                   17968: }
                   17969: 
1.444     albertel 17970: ############################################################
                   17971: ############################################################
                   17972: 
1.1237    raeburn  17973: # Community, Course and Placement Test
1.378     raeburn  17974: sub course_type {
                   17975:     my ($cid) = @_;
                   17976:     if (!defined($cid)) {
                   17977:         $cid = $env{'request.course.id'};
                   17978:     }
1.404     albertel 17979:     if (defined($env{'course.'.$cid.'.type'})) {
                   17980:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17981:     } else {
                   17982:         return 'Course';
1.377     raeburn  17983:     }
                   17984: }
1.156     albertel 17985: 
1.406     raeburn  17986: sub group_term {
                   17987:     my $crstype = &course_type();
                   17988:     my %names = (
                   17989:                   'Course' => 'group',
1.865     raeburn  17990:                   'Community' => 'group',
1.1237    raeburn  17991:                   'Placement' => 'group',
1.406     raeburn  17992:                 );
                   17993:     return $names{$crstype};
                   17994: }
                   17995: 
1.902     raeburn  17996: sub course_types {
1.1310    raeburn  17997:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17998:     my %typename = (
                   17999:                          official   => 'Official course',
                   18000:                          unofficial => 'Unofficial course',
                   18001:                          community  => 'Community',
1.1165    raeburn  18002:                          textbook   => 'Textbook course',
1.1237    raeburn  18003:                          placement  => 'Placement test',
1.1310    raeburn  18004:                          lti        => 'LTI provider',
1.902     raeburn  18005:                    );
                   18006:     return (\@types,\%typename);
                   18007: }
                   18008: 
1.156     albertel 18009: sub icon {
                   18010:     my ($file)=@_;
1.505     albertel 18011:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 18012:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 18013:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 18014:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   18015: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   18016: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   18017: 	            $curfext.".gif") {
                   18018: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   18019: 		$curfext.".gif";
                   18020: 	}
                   18021:     }
1.249     albertel 18022:     return &lonhttpdurl($iconname);
1.154     albertel 18023: } 
1.84      albertel 18024: 
1.575     albertel 18025: sub lonhttpdurl {
1.692     www      18026: #
                   18027: # Had been used for "small fry" static images on separate port 8080.
                   18028: # Modify here if lightweight http functionality desired again.
                   18029: # Currently eliminated due to increasing firewall issues.
                   18030: #
1.575     albertel 18031:     my ($url)=@_;
1.692     www      18032:     return $url;
1.215     albertel 18033: }
                   18034: 
1.213     albertel 18035: sub connection_aborted {
                   18036:     my ($r)=@_;
                   18037:     $r->print(" ");$r->rflush();
                   18038:     my $c = $r->connection;
                   18039:     return $c->aborted();
                   18040: }
                   18041: 
1.221     foxr     18042: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     18043: #    strings as 'strings'.
                   18044: sub escape_single {
1.221     foxr     18045:     my ($input) = @_;
1.223     albertel 18046:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     18047:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   18048:     return $input;
                   18049: }
1.223     albertel 18050: 
1.222     foxr     18051: #  Same as escape_single, but escape's "'s  This 
                   18052: #  can be used for  "strings"
                   18053: sub escape_double {
                   18054:     my ($input) = @_;
                   18055:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   18056:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   18057:     return $input;
                   18058: }
1.223     albertel 18059:  
1.222     foxr     18060: #   Escapes the last element of a full URL.
                   18061: sub escape_url {
                   18062:     my ($url)   = @_;
1.238     raeburn  18063:     my @urlslices = split(/\//, $url,-1);
1.369     www      18064:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  18065:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     18066: }
1.462     albertel 18067: 
1.820     raeburn  18068: sub compare_arrays {
                   18069:     my ($arrayref1,$arrayref2) = @_;
                   18070:     my (@difference,%count);
                   18071:     @difference = ();
                   18072:     %count = ();
                   18073:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   18074:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   18075:         foreach my $element (keys(%count)) {
                   18076:             if ($count{$element} == 1) {
                   18077:                 push(@difference,$element);
                   18078:             }
                   18079:         }
                   18080:     }
                   18081:     return @difference;
                   18082: }
                   18083: 
1.1322    raeburn  18084: sub lon_status_items {
                   18085:     my %defaults = (
                   18086:                      E         => 100,
                   18087:                      W         => 4,
                   18088:                      N         => 1,
1.1324    raeburn  18089:                      U         => 5,
1.1322    raeburn  18090:                      threshold => 200,
                   18091:                      sysmail   => 2500,
                   18092:                    );
                   18093:     my %names = (
                   18094:                    E => 'Errors',
                   18095:                    W => 'Warnings',
                   18096:                    N => 'Notices',
1.1324    raeburn  18097:                    U => 'Unsent',
1.1322    raeburn  18098:                 );
                   18099:     return (\%defaults,\%names);
                   18100: }
                   18101: 
1.817     bisitz   18102: # -------------------------------------------------------- Initialize user login
1.462     albertel 18103: sub init_user_environment {
1.463     albertel 18104:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 18105:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   18106: 
                   18107:     my $public=($username eq 'public' && $domain eq 'public');
                   18108: 
1.1415    raeburn  18109:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   18110:         $coauthorenv);
1.462     albertel 18111:     my $now=time;
                   18112: 
                   18113:     if ($public) {
                   18114: 	my $max_public=100;
                   18115: 	my $oldest;
                   18116: 	my $oldest_time=0;
                   18117: 	for(my $next=1;$next<=$max_public;$next++) {
                   18118: 	    if (-e $lonids."/publicuser_$next.id") {
                   18119: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   18120: 		if ($mtime<$oldest_time || !$oldest_time) {
                   18121: 		    $oldest_time=$mtime;
                   18122: 		    $oldest=$next;
                   18123: 		}
                   18124: 	    } else {
                   18125: 		$cookie="publicuser_$next";
                   18126: 		last;
                   18127: 	    }
                   18128: 	}
                   18129: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   18130:     } else {
1.1275    raeburn  18131: 	# See if old ID present, if so, remove if this isn't a robot,
                   18132: 	# killing any existing non-robot sessions
1.463     albertel 18133: 	if (!$args->{'robot'}) {
                   18134: 	    opendir(DIR,$lonids);
                   18135: 	    while ($filename=readdir(DIR)) {
                   18136: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  18137:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   18138:                             &GDBM_READER(),0640)) {
1.1295    raeburn  18139:                         my $linkedfile;
1.1320    raeburn  18140:                         if (exists($oldenv{'user.linkedenv'})) {
                   18141:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  18142:                         }
1.1320    raeburn  18143:                         untie(%oldenv);
                   18144:                         if (unlink("$lonids/$filename")) {
                   18145:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   18146:                                 if (-l "$lonids/$linkedfile.id") {
                   18147:                                     unlink("$lonids/$linkedfile.id");
                   18148:                                 }
1.1295    raeburn  18149:                             }
                   18150:                         }
                   18151:                     } else {
                   18152:                         unlink($lonids.'/'.$filename);
                   18153:                     }
1.463     albertel 18154: 		}
1.462     albertel 18155: 	    }
1.463     albertel 18156: 	    closedir(DIR);
1.1204    raeburn  18157: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   18158:             my $namespace = 'nohist_courseeditor';
                   18159:             my $lockingkey = 'paste'."\0".'locked_num';
                   18160:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   18161:                                                 $domain,$username);
                   18162:             if (exists($lockhash{$lockingkey})) {
                   18163:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   18164:                 unless ($delresult eq 'ok') {
                   18165:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   18166:                 }
                   18167:             }
1.462     albertel 18168: 	}
                   18169: # Give them a new cookie
1.463     albertel 18170: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      18171: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 18172: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 18173:     
                   18174: # Initialize roles
                   18175: 
1.1414    raeburn  18176: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  18177:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 18178:     }
                   18179: # ------------------------------------ Check browser type and MathML capability
                   18180: 
1.1194    raeburn  18181:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   18182:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 18183: 
                   18184: # ------------------------------------------------------------- Get environment
                   18185: 
                   18186:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   18187:     my ($tmp) = keys(%userenv);
1.1275    raeburn  18188:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 18189: 	undef(%userenv);
                   18190:     }
                   18191:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   18192: 	$form->{'interface'}=$userenv{'interface'};
                   18193:     }
                   18194:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   18195: 
                   18196: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   18197:     foreach my $option ('interface','localpath','localres') {
                   18198:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 18199:     }
                   18200: # --------------------------------------------------------- Write first profile
                   18201: 
                   18202:     {
1.1350    raeburn  18203:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 18204: 	my %initial_env = 
                   18205: 	    ("user.name"          => $username,
                   18206: 	     "user.domain"        => $domain,
                   18207: 	     "user.home"          => $authhost,
                   18208: 	     "browser.type"       => $clientbrowser,
                   18209: 	     "browser.version"    => $clientversion,
                   18210: 	     "browser.mathml"     => $clientmathml,
                   18211: 	     "browser.unicode"    => $clientunicode,
                   18212: 	     "browser.os"         => $clientos,
1.1137    raeburn  18213:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  18214:              "browser.info"       => $clientinfo,
1.1194    raeburn  18215:              "browser.osversion"  => $clientosversion,
1.462     albertel 18216: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   18217: 	     "request.course.fn"  => '',
                   18218: 	     "request.course.uri" => '',
                   18219: 	     "request.course.sec" => '',
                   18220: 	     "request.role"       => 'cm',
                   18221: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  18222: 	     "request.host"       => $ip,);
1.462     albertel 18223: 
                   18224:         if ($form->{'localpath'}) {
                   18225: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   18226: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   18227:         }
                   18228: 	
                   18229: 	if ($form->{'interface'}) {
                   18230: 	    $form->{'interface'}=~s/\W//gs;
                   18231: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   18232: 	    $env{'browser.interface'}=$form->{'interface'};
                   18233: 	}
                   18234: 
1.1157    raeburn  18235:         if ($form->{'iptoken'}) {
                   18236:             my $lonhost = $r->dir_config('lonHostID');
                   18237:             $initial_env{"user.noloadbalance"} = $lonhost;
                   18238:             $env{'user.noloadbalance'} = $lonhost;
                   18239:         }
                   18240: 
1.1268    raeburn  18241:         if ($form->{'noloadbalance'}) {
                   18242:             my @hosts = &Apache::lonnet::current_machine_ids();
                   18243:             my $hosthere = $form->{'noloadbalance'};
                   18244:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   18245:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   18246:                 $env{'user.noloadbalance'} = $hosthere;
                   18247:             }
                   18248:         }
                   18249: 
1.1016    raeburn  18250:         unless ($domain eq 'public') {
1.1273    raeburn  18251:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   18252:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   18253: 
1.1414    raeburn  18254:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
                   18255:                 $userenv{'availabletools.'.$tool} =
1.1273    raeburn  18256:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   18257:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   18258:             }
1.980     raeburn  18259: 
1.1311    raeburn  18260:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  18261:                 $userenv{'canrequest.'.$crstype} =
                   18262:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   18263:                                                       'reload','requestcourses',
                   18264:                                                       \%userenv,\%domdef,\%is_adv);
                   18265:             }
1.724     raeburn  18266: 
1.1418    raeburn  18267:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   18268:                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   18269:                 if ($userenv{'authoreditors'}) {
                   18270:                     $userenv{'editors'} = $userenv{'authoreditors'};
                   18271:                 } elsif ($domdef{'editors'} ne '') {
                   18272:                     $userenv{'editors'} = $domdef{'editors'};
                   18273:                 } else {
                   18274:                     $userenv{'editors'} = 'edit,xml';
                   18275:                 }
1.1431    raeburn  18276:                 if ($userenv{'authorarchive'}) {
                   18277:                     $userenv{'canarchive'} = 1;
                   18278:                 } elsif (($userenv{'authorarchive'} eq '') &&
                   18279:                          ($domdef{'archive'})) {
                   18280:                     $userenv{'canarchive'} = 1;
                   18281:                 }
1.1418    raeburn  18282:             }
                   18283: 
1.1273    raeburn  18284:             $userenv{'canrequest.author'} =
                   18285:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   18286:                                                   'reload','requestauthor',
1.980     raeburn  18287:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  18288:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   18289:                                                  $domain,$username);
                   18290:             my $reqstatus = $reqauthor{'author_status'};
                   18291:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   18292:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   18293:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   18294:                                                       $reqauthor{'author'}{'timestamp'};
                   18295:                 }
1.1092    raeburn  18296:             }
1.1287    raeburn  18297:             my ($types,$typename) = &course_types();
                   18298:             if (ref($types) eq 'ARRAY') {
                   18299:                 my @options = ('approval','validate','autolimit');
                   18300:                 my $optregex = join('|',@options);
                   18301:                 my (%willtrust,%trustchecked);
                   18302:                 foreach my $type (@{$types}) {
                   18303:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   18304:                     if ($dom_str ne '') {
                   18305:                         my $updatedstr = '';
                   18306:                         my @possdomains = split(',',$dom_str);
                   18307:                         foreach my $entry (@possdomains) {
                   18308:                             my ($extdom,$extopt) = split(':',$entry);
                   18309:                             unless ($trustchecked{$extdom}) {
                   18310:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   18311:                                 $trustchecked{$extdom} = 1;
                   18312:                             }
                   18313:                             if ($willtrust{$extdom}) {
                   18314:                                 $updatedstr .= $entry.',';
                   18315:                             }
                   18316:                         }
                   18317:                         $updatedstr =~ s/,$//;
                   18318:                         if ($updatedstr) {
                   18319:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   18320:                         } else {
                   18321:                             delete($userenv{'reqcrsotherdom.'.$type});
                   18322:                         }
                   18323:                     }
                   18324:                 }
                   18325:             }
1.1092    raeburn  18326:         }
1.462     albertel 18327: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  18328: 
1.462     albertel 18329: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   18330: 		 &GDBM_WRCREAT(),0640)) {
                   18331: 	    &_add_to_env(\%disk_env,\%initial_env);
                   18332: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   18333: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  18334:             if (ref($firstaccenv) eq 'HASH') {
                   18335:                 &_add_to_env(\%disk_env,$firstaccenv);
                   18336:             }
                   18337:             if (ref($timerintenv) eq 'HASH') {
                   18338:                 &_add_to_env(\%disk_env,$timerintenv);
                   18339:             }
1.1414    raeburn  18340:             if (ref($coauthorenv) eq 'HASH') {
                   18341:                 if (keys(%{$coauthorenv})) {
                   18342:                     &_add_to_env(\%disk_env,$coauthorenv);
                   18343:                 }
                   18344:             }
1.463     albertel 18345: 	    if (ref($args->{'extra_env'})) {
                   18346: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   18347: 	    }
1.462     albertel 18348: 	    untie(%disk_env);
                   18349: 	} else {
1.705     tempelho 18350: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   18351: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 18352: 	    return 'error: '.$!;
                   18353: 	}
                   18354:     }
                   18355:     $env{'request.role'}='cm';
                   18356:     $env{'request.role.adv'}=$env{'user.adv'};
                   18357:     $env{'browser.type'}=$clientbrowser;
                   18358: 
                   18359:     return $cookie;
                   18360: 
                   18361: }
                   18362: 
                   18363: sub _add_to_env {
                   18364:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  18365:     if (ref($env_data) eq 'HASH') {
                   18366:         while (my ($key,$value) = each(%$env_data)) {
                   18367: 	    $idf->{$prefix.$key} = $value;
                   18368: 	    $env{$prefix.$key}   = $value;
                   18369:         }
1.462     albertel 18370:     }
                   18371: }
                   18372: 
1.685     tempelho 18373: # --- Get the symbolic name of a problem and the url
                   18374: sub get_symb {
                   18375:     my ($request,$silent) = @_;
1.726     raeburn  18376:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 18377:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   18378:     if ($symb eq '') {
                   18379:         if (!$silent) {
1.1071    raeburn  18380:             if (ref($request)) { 
                   18381:                 $request->print("Unable to handle ambiguous references:$url:.");
                   18382:             }
1.685     tempelho 18383:             return ();
                   18384:         }
                   18385:     }
                   18386:     &Apache::lonenc::check_decrypt(\$symb);
                   18387:     return ($symb);
                   18388: }
                   18389: 
                   18390: # --------------------------------------------------------------Get annotation
                   18391: 
                   18392: sub get_annotation {
                   18393:     my ($symb,$enc) = @_;
                   18394: 
                   18395:     my $key = $symb;
                   18396:     if (!$enc) {
                   18397:         $key =
                   18398:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   18399:     }
                   18400:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   18401:     return $annotation{$key};
                   18402: }
                   18403: 
                   18404: sub clean_symb {
1.731     raeburn  18405:     my ($symb,$delete_enc) = @_;
1.685     tempelho 18406: 
                   18407:     &Apache::lonenc::check_decrypt(\$symb);
                   18408:     my $enc = $env{'request.enc'};
1.731     raeburn  18409:     if ($delete_enc) {
1.730     raeburn  18410:         delete($env{'request.enc'});
                   18411:     }
1.685     tempelho 18412: 
                   18413:     return ($symb,$enc);
                   18414: }
1.462     albertel 18415: 
1.1181    raeburn  18416: ############################################################
                   18417: ############################################################
                   18418: 
                   18419: =pod
                   18420: 
                   18421: =head1 Routines for building display used to search for courses
                   18422: 
                   18423: 
                   18424: =over 4
                   18425: 
                   18426: =item * &build_filters()
                   18427: 
                   18428: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  18429: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   18430: and quotacheck.pl
                   18431: 
1.1181    raeburn  18432: 
                   18433: Inputs:
                   18434: 
                   18435: filterlist - anonymous array of fields to include as potential filters 
                   18436: 
                   18437: crstype - course type
                   18438: 
                   18439: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   18440:               to pop-open a course selector (will contain "extra element"). 
                   18441: 
                   18442: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   18443: 
                   18444: filter - anonymous hash of criteria and their values
                   18445: 
                   18446: action - form action
                   18447: 
                   18448: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   18449: 
1.1182    raeburn  18450: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  18451: 
                   18452: cloneruname - username of owner of new course who wants to clone
                   18453: 
                   18454: clonerudom - domain of owner of new course who wants to clone
                   18455: 
                   18456: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   18457: 
                   18458: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   18459: 
                   18460: codedom - domain
                   18461: 
                   18462: formname - value of form element named "form". 
                   18463: 
                   18464: fixeddom - domain, if fixed.
                   18465: 
                   18466: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   18467: 
                   18468: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   18469: 
                   18470: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   18471: 
                   18472: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   18473: 
                   18474: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   18475: 
                   18476: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   18477: 
                   18478: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   18479: 
1.1182    raeburn  18480: 
1.1181    raeburn  18481: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   18482: 
1.1182    raeburn  18483: 
1.1181    raeburn  18484: Side Effects: None
                   18485: 
                   18486: =cut
                   18487: 
                   18488: # ---------------------------------------------- search for courses based on last activity etc.
                   18489: 
                   18490: sub build_filters {
                   18491:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   18492:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   18493:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   18494:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   18495:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  18496:     my ($list,$jscript);
1.1181    raeburn  18497:     my $onchange = 'javascript:updateFilters(this)';
                   18498:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   18499:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   18500:         $typeselectform,$instcodetitle);
                   18501:     if ($formname eq '') {
                   18502:         $formname = $caller;
                   18503:     }
                   18504:     foreach my $item (@{$filterlist}) {
                   18505:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   18506:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   18507:             if ($item eq 'domainfilter') {
                   18508:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   18509:             } elsif ($item eq 'coursefilter') {
                   18510:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   18511:             } elsif ($item eq 'ownerfilter') {
                   18512:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18513:             } elsif ($item eq 'ownerdomfilter') {
                   18514:                 $filter->{'ownerdomfilter'} =
                   18515:                     &LONCAPA::clean_domain($filter->{$item});
                   18516:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   18517:                                                        'ownerdomfilter',1);
                   18518:             } elsif ($item eq 'personfilter') {
                   18519:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18520:             } elsif ($item eq 'persondomfilter') {
                   18521:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   18522:                                                         'persondomfilter',1);
                   18523:             } else {
                   18524:                 $filter->{$item} =~ s/\W//g;
                   18525:             }
                   18526:             if (!$filter->{$item}) {
                   18527:                 $filter->{$item} = '';
                   18528:             }
                   18529:         }
                   18530:         if ($item eq 'domainfilter') {
                   18531:             my $allow_blank = 1;
                   18532:             if ($formname eq 'portform') {
                   18533:                 $allow_blank=0;
                   18534:             } elsif ($formname eq 'studentform') {
                   18535:                 $allow_blank=0;
                   18536:             }
                   18537:             if ($fixeddom) {
                   18538:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   18539:                                     ' value="'.$codedom.'" />'.
                   18540:                                     &Apache::lonnet::domain($codedom,'description');
                   18541:             } else {
                   18542:                 $domainselectform = &select_dom_form($filter->{$item},
                   18543:                                                      'domainfilter',
                   18544:                                                       $allow_blank,'',$onchange);
                   18545:             }
                   18546:         } else {
                   18547:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   18548:         }
                   18549:     }
                   18550: 
                   18551:     # last course activity filter and selection
                   18552:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   18553: 
                   18554:     # course created filter and selection
                   18555:     if (exists($filter->{'createdfilter'})) {
                   18556:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   18557:     }
                   18558: 
1.1239    raeburn  18559:     my $prefix = $crstype;
                   18560:     if ($crstype eq 'Placement') {
                   18561:         $prefix = 'Placement Test'
                   18562:     }
1.1181    raeburn  18563:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  18564:                 'cac' => "$prefix Activity",
                   18565:                 'ccr' => "$prefix Created",
                   18566:                 'cde' => "$prefix Title",
                   18567:                 'cdo' => "$prefix Domain",
1.1181    raeburn  18568:                 'ins' => 'Institutional Code',
                   18569:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  18570:                 'cow' => "$prefix Owner/Co-owner",
                   18571:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  18572:                 'cog' => 'Type',
                   18573:              );
                   18574: 
                   18575:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18576:         my $typeval = 'Course';
                   18577:         if ($crstype eq 'Community') {
                   18578:             $typeval = 'Community';
1.1239    raeburn  18579:         } elsif ($crstype eq 'Placement') {
                   18580:             $typeval = 'Placement';
1.1181    raeburn  18581:         }
                   18582:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   18583:     } else {
                   18584:         $typeselectform =  '<select name="type" size="1"';
                   18585:         if ($onchange) {
                   18586:             $typeselectform .= ' onchange="'.$onchange.'"';
                   18587:         }
                   18588:         $typeselectform .= '>'."\n";
1.1237    raeburn  18589:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  18590:             my $shown;
                   18591:             if ($posstype eq 'Placement') {
                   18592:                 $shown = &mt('Placement Test');
                   18593:             } else {
                   18594:                 $shown = &mt($posstype);
                   18595:             }
1.1181    raeburn  18596:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  18597:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  18598:         }
                   18599:         $typeselectform.="</select>";
                   18600:     }
                   18601: 
                   18602:     my ($cloneableonlyform,$cloneabletitle);
                   18603:     if (exists($filter->{'cloneableonly'})) {
                   18604:         my $cloneableon = '';
                   18605:         my $cloneableoff = ' checked="checked"';
                   18606:         if ($filter->{'cloneableonly'}) {
                   18607:             $cloneableon = $cloneableoff;
                   18608:             $cloneableoff = '';
                   18609:         }
                   18610:         $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>';
                   18611:         if ($formname eq 'ccrs') {
1.1187    bisitz   18612:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  18613:         } else {
                   18614:             $cloneabletitle = &mt('Cloneable by you');
                   18615:         }
                   18616:     }
                   18617:     my $officialjs;
                   18618:     if ($crstype eq 'Course') {
                   18619:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  18620: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   18621: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   18622:             if ($codedom) { 
1.1181    raeburn  18623:                 $officialjs = 1;
                   18624:                 ($instcodeform,$jscript,$$numtitlesref) =
                   18625:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   18626:                                                                   $officialjs,$codetitlesref);
                   18627:                 if ($jscript) {
1.1182    raeburn  18628:                     $jscript = '<script type="text/javascript">'."\n".
                   18629:                                '// <![CDATA['."\n".
                   18630:                                $jscript."\n".
                   18631:                                '// ]]>'."\n".
                   18632:                                '</script>'."\n";
1.1181    raeburn  18633:                 }
                   18634:             }
                   18635:             if ($instcodeform eq '') {
                   18636:                 $instcodeform =
                   18637:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   18638:                     $list->{'instcodefilter'}.'" />';
                   18639:                 $instcodetitle = $lt{'ins'};
                   18640:             } else {
                   18641:                 $instcodetitle = $lt{'inc'};
                   18642:             }
                   18643:             if ($fixeddom) {
                   18644:                 $instcodetitle .= '<br />('.$codedom.')';
                   18645:             }
                   18646:         }
                   18647:     }
                   18648:     my $output = qq|
                   18649: <form method="post" name="filterpicker" action="$action">
                   18650: <input type="hidden" name="form" value="$formname" />
                   18651: |;
                   18652:     if ($formname eq 'modifycourse') {
                   18653:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   18654:                    '<input type="hidden" name="prevphase" value="'.
                   18655:                    $prevphase.'" />'."\n";
1.1198    musolffc 18656:     } elsif ($formname eq 'quotacheck') {
                   18657:         $output .= qq|
                   18658: <input type="hidden" name="sortby" value="" />
                   18659: <input type="hidden" name="sortorder" value="" />
                   18660: |;
                   18661:     } else {
1.1181    raeburn  18662:         my $name_input;
                   18663:         if ($cnameelement ne '') {
                   18664:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   18665:                           $cnameelement.'" />';
                   18666:         }
                   18667:         $output .= qq|
1.1182    raeburn  18668: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   18669: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  18670: $name_input
                   18671: $roleelement
                   18672: $multelement
                   18673: $typeelement
                   18674: |;
                   18675:         if ($formname eq 'portform') {
                   18676:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   18677:         }
                   18678:     }
                   18679:     if ($fixeddom) {
                   18680:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   18681:     }
                   18682:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   18683:     if ($sincefilterform) {
                   18684:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   18685:                   .$sincefilterform
                   18686:                   .&Apache::lonhtmlcommon::row_closure();
                   18687:     }
                   18688:     if ($createdfilterform) {
                   18689:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   18690:                   .$createdfilterform
                   18691:                   .&Apache::lonhtmlcommon::row_closure();
                   18692:     }
                   18693:     if ($domainselectform) {
                   18694:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   18695:                   .$domainselectform
                   18696:                   .&Apache::lonhtmlcommon::row_closure();
                   18697:     }
                   18698:     if ($typeselectform) {
                   18699:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18700:             $output .= $typeselectform;
                   18701:         } else {
                   18702:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   18703:                       .$typeselectform
                   18704:                       .&Apache::lonhtmlcommon::row_closure();
                   18705:         }
                   18706:     }
                   18707:     if ($instcodeform) {
                   18708:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   18709:                   .$instcodeform
                   18710:                   .&Apache::lonhtmlcommon::row_closure();
                   18711:     }
                   18712:     if (exists($filter->{'ownerfilter'})) {
                   18713:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   18714:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18715:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   18716:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18717:                    $ownerdomselectform.'</td></tr></table>'.
                   18718:                    &Apache::lonhtmlcommon::row_closure();
                   18719:     }
                   18720:     if (exists($filter->{'personfilter'})) {
                   18721:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   18722:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18723:                    '<input type="text" name="personfilter" size="20" value="'.
                   18724:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18725:                    $persondomselectform.'</td></tr></table>'.
                   18726:                    &Apache::lonhtmlcommon::row_closure();
                   18727:     }
                   18728:     if (exists($filter->{'coursefilter'})) {
                   18729:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   18730:                   .'<input type="text" name="coursefilter" size="25" value="'
                   18731:                   .$list->{'coursefilter'}.'" />'
                   18732:                   .&Apache::lonhtmlcommon::row_closure();
                   18733:     }
                   18734:     if ($cloneableonlyform) {
                   18735:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   18736:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   18737:     }
                   18738:     if (exists($filter->{'descriptfilter'})) {
                   18739:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   18740:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   18741:                   .$list->{'descriptfilter'}.'" />'
                   18742:                   .&Apache::lonhtmlcommon::row_closure(1);
                   18743:     }
                   18744:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   18745:                '<input type="hidden" name="updater" value="" />'."\n".
                   18746:                '<input type="submit" name="gosearch" value="'.
                   18747:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   18748:     return $jscript.$clonewarning.$output;
                   18749: }
                   18750: 
                   18751: =pod 
                   18752: 
                   18753: =item * &timebased_select_form()
                   18754: 
1.1182    raeburn  18755: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  18756: filter e.g., Course Activity, Course Created, when searching for courses
                   18757: or communities
                   18758: 
                   18759: Inputs:
                   18760: 
                   18761: item - name of form element (sincefilter or createdfilter)
                   18762: 
                   18763: filter - anonymous hash of criteria and their values
                   18764: 
                   18765: Returns: HTML for a select box contained a blank, then six time selections,
                   18766:          with value set in incoming form variables currently selected. 
                   18767: 
                   18768: Side Effects: None
                   18769: 
                   18770: =cut
                   18771: 
                   18772: sub timebased_select_form {
                   18773:     my ($item,$filter) = @_;
                   18774:     if (ref($filter) eq 'HASH') {
                   18775:         $filter->{$item} =~ s/[^\d-]//g;
                   18776:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   18777:         return &select_form(
                   18778:                             $filter->{$item},
                   18779:                             $item,
                   18780:                             {      '-1' => '',
                   18781:                                 '86400' => &mt('today'),
                   18782:                                '604800' => &mt('last week'),
                   18783:                               '2592000' => &mt('last month'),
                   18784:                               '7776000' => &mt('last three months'),
                   18785:                              '15552000' => &mt('last six months'),
                   18786:                              '31104000' => &mt('last year'),
                   18787:                     'select_form_order' =>
                   18788:                            ['-1','86400','604800','2592000','7776000',
                   18789:                             '15552000','31104000']});
                   18790:     }
                   18791: }
                   18792: 
                   18793: =pod
                   18794: 
                   18795: =item * &js_changer()
                   18796: 
                   18797: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  18798: when course type or domain is changed, and also to hide 'Searching ...' on
                   18799: page load completion for page showing search result.
1.1181    raeburn  18800: 
                   18801: Inputs: None
                   18802: 
1.1183    raeburn  18803: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  18804: 
                   18805: Side Effects: None
                   18806: 
                   18807: =cut
                   18808: 
                   18809: sub js_changer {
                   18810:     return <<ENDJS;
                   18811: <script type="text/javascript">
                   18812: // <![CDATA[
                   18813: function updateFilters(caller) {
                   18814:     if (typeof(caller) != "undefined") {
                   18815:         document.filterpicker.updater.value = caller.name;
                   18816:     }
                   18817:     document.filterpicker.submit();
                   18818: }
1.1183    raeburn  18819: 
                   18820: function hideSearching() {
                   18821:     if (document.getElementById('searching')) {
                   18822:         document.getElementById('searching').style.display = 'none';
                   18823:     }
                   18824:     return;
                   18825: }
                   18826: 
1.1181    raeburn  18827: // ]]>
                   18828: </script>
                   18829: 
                   18830: ENDJS
                   18831: }
                   18832: 
                   18833: =pod
                   18834: 
1.1182    raeburn  18835: =item * &search_courses()
                   18836: 
                   18837: Process selected filters form course search form and pass to lonnet::courseiddump
                   18838: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18839: 
                   18840: Inputs:
                   18841: 
                   18842: dom - domain being searched 
                   18843: 
                   18844: type - course type ('Course' or 'Community' or '.' if any).
                   18845: 
                   18846: filter - anonymous hash of criteria and their values
                   18847: 
                   18848: numtitles - for institutional codes - number of categories
                   18849: 
                   18850: cloneruname - optional username of new course owner
                   18851: 
                   18852: clonerudom - optional domain of new course owner
                   18853: 
1.1221    raeburn  18854: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18855:             (used when DC is using course creation form)
                   18856: 
                   18857: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18858: 
1.1221    raeburn  18859: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18860:            (and so can clone automatically)
                   18861: 
                   18862: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18863: 
                   18864: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18865:               courses to clone 
1.1182    raeburn  18866: 
                   18867: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18868: 
                   18869: 
                   18870: Side Effects: None
                   18871: 
                   18872: =cut
                   18873: 
                   18874: 
                   18875: sub search_courses {
1.1221    raeburn  18876:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18877:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18878:     my (%courses,%showcourses,$cloner);
                   18879:     if (($filter->{'ownerfilter'} ne '') ||
                   18880:         ($filter->{'ownerdomfilter'} ne '')) {
                   18881:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18882:                                        $filter->{'ownerdomfilter'};
                   18883:     }
                   18884:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18885:         if (!$filter->{$item}) {
                   18886:             $filter->{$item}='.';
                   18887:         }
                   18888:     }
                   18889:     my $now = time;
                   18890:     my $timefilter =
                   18891:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18892:     my ($createdbefore,$createdafter);
                   18893:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18894:         $createdbefore = $now;
                   18895:         $createdafter = $now-$filter->{'createdfilter'};
                   18896:     }
                   18897:     my ($instcodefilter,$regexpok);
                   18898:     if ($numtitles) {
                   18899:         if ($env{'form.official'} eq 'on') {
                   18900:             $instcodefilter =
                   18901:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18902:             $regexpok = 1;
                   18903:         } elsif ($env{'form.official'} eq 'off') {
                   18904:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18905:             unless ($instcodefilter eq '') {
                   18906:                 $regexpok = -1;
                   18907:             }
                   18908:         }
                   18909:     } else {
                   18910:         $instcodefilter = $filter->{'instcodefilter'};
                   18911:     }
                   18912:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18913:     if ($type eq '') { $type = '.'; }
                   18914: 
                   18915:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18916:         $cloner = $cloneruname.':'.$clonerudom;
                   18917:     }
                   18918:     %courses = &Apache::lonnet::courseiddump($dom,
                   18919:                                              $filter->{'descriptfilter'},
                   18920:                                              $timefilter,
                   18921:                                              $instcodefilter,
                   18922:                                              $filter->{'combownerfilter'},
                   18923:                                              $filter->{'coursefilter'},
                   18924:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18925:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18926:                                              $filter->{'cloneableonly'},
                   18927:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18928:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18929:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18930:         my $ccrole;
                   18931:         if ($type eq 'Community') {
                   18932:             $ccrole = 'co';
                   18933:         } else {
                   18934:             $ccrole = 'cc';
                   18935:         }
                   18936:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18937:                                                      $filter->{'persondomfilter'},
                   18938:                                                      'userroles',undef,
                   18939:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18940:                                                      $dom);
                   18941:         foreach my $role (keys(%rolehash)) {
                   18942:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18943:             my $cid = $cdom.'_'.$cnum;
                   18944:             if (exists($courses{$cid})) {
                   18945:                 if (ref($courses{$cid}) eq 'HASH') {
                   18946:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18947:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18948:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18949:                         }
                   18950:                     } else {
                   18951:                         $courses{$cid}{roles} = [$courserole];
                   18952:                     }
                   18953:                     $showcourses{$cid} = $courses{$cid};
                   18954:                 }
                   18955:             }
                   18956:         }
                   18957:         %courses = %showcourses;
                   18958:     }
                   18959:     return %courses;
                   18960: }
                   18961: 
                   18962: =pod
                   18963: 
1.1181    raeburn  18964: =back
                   18965: 
1.1207    raeburn  18966: =head1 Routines for version requirements for current course.
                   18967: 
                   18968: =over 4
                   18969: 
                   18970: =item * &check_release_required()
                   18971: 
                   18972: Compares required LON-CAPA version with version on server, and
                   18973: if required version is newer looks for a server with the required version.
                   18974: 
                   18975: Looks first at servers in user's owen domain; if none suitable, looks at
                   18976: servers in course's domain are permitted to host sessions for user's domain.
                   18977: 
                   18978: Inputs:
                   18979: 
                   18980: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18981: 
                   18982: $courseid - Course ID of current course
                   18983: 
                   18984: $rolecode - User's current role in course (for switchserver query string).
                   18985: 
                   18986: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18987: 
                   18988: 
                   18989: Returns:
                   18990: 
                   18991: $switchserver - query string tp append to /adm/switchserver call (if 
                   18992:                 current server's LON-CAPA version is too old. 
                   18993: 
                   18994: $warning - Message is displayed if no suitable server could be found.
                   18995: 
                   18996: =cut
                   18997: 
                   18998: sub check_release_required {
                   18999:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   19000:     my ($switchserver,$warning);
                   19001:     if ($required ne '') {
                   19002:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   19003:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   19004:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   19005:             my $otherserver;
                   19006:             if (($major eq '' && $minor eq '') ||
                   19007:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   19008:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   19009:                 my $switchlcrev =
                   19010:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   19011:                                                            $userdomserver);
                   19012:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   19013:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   19014:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   19015:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   19016:                     if ($cdom ne $env{'user.domain'}) {
                   19017:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   19018:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   19019:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   19020:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   19021:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   19022:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   19023:                         my $canhost =
                   19024:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   19025:                                                               $coursedomserver,
                   19026:                                                               $remoterev,
                   19027:                                                               $udomdefaults{'remotesessions'},
                   19028:                                                               $defdomdefaults{'hostedsessions'});
                   19029: 
                   19030:                         if ($canhost) {
                   19031:                             $otherserver = $coursedomserver;
                   19032:                         } else {
                   19033:                             $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.");
                   19034:                         }
                   19035:                     } else {
                   19036:                         $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).");
                   19037:                     }
                   19038:                 } else {
                   19039:                     $otherserver = $userdomserver;
                   19040:                 }
                   19041:             }
                   19042:             if ($otherserver ne '') {
                   19043:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   19044:             }
                   19045:         }
                   19046:     }
                   19047:     return ($switchserver,$warning);
                   19048: }
                   19049: 
                   19050: =pod
                   19051: 
                   19052: =item * &check_release_result()
                   19053: 
                   19054: Inputs:
                   19055: 
                   19056: $switchwarning - Warning message if no suitable server found to host session.
                   19057: 
                   19058: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   19059:                 and current role.
                   19060: 
                   19061: Returns: HTML to display with information about requirement to switch server.
                   19062:          Either displaying warning with link to Roles/Courses screen or
                   19063:          display link to switchserver.
                   19064: 
1.1181    raeburn  19065: =cut
                   19066: 
1.1207    raeburn  19067: sub check_release_result {
                   19068:     my ($switchwarning,$switchserver) = @_;
                   19069:     my $output = &start_page('Selected course unavailable on this server').
1.1463    raeburn  19070:                  '<div class="LC_landmark" role="main"><p class="LC_warning">';
1.1207    raeburn  19071:     if ($switchwarning) {
                   19072:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   19073:         if (&show_course()) {
                   19074:             $output .= &mt('Display courses');
                   19075:         } else {
                   19076:             $output .= &mt('Display roles');
                   19077:         }
                   19078:         $output .= '</a>';
                   19079:     } elsif ($switchserver) {
                   19080:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   19081:                    '<br />'.
                   19082:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   19083:                    &mt('Switch Server').
                   19084:                    '</a>';
                   19085:     }
1.1463    raeburn  19086:     $output .= '</p></div>'.&end_page();
1.1207    raeburn  19087:     return $output;
                   19088: }
                   19089: 
                   19090: =pod
                   19091: 
                   19092: =item * &needs_coursereinit()
                   19093: 
                   19094: Determine if course contents stored for user's session needs to be
                   19095: refreshed, because content has changed since "Big Hash" last tied.
                   19096: 
                   19097: Check for change is made if time last checked is more than 10 minutes ago
                   19098: (by default).
                   19099: 
                   19100: Inputs:
                   19101: 
                   19102: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   19103: 
                   19104: $interval (optional) - Time which may elapse (in s) between last check for content
                   19105:                        change in current course. (default: 600 s).  
                   19106: 
                   19107: Returns: an array; first element is:
                   19108: 
                   19109: =over 4
                   19110: 
                   19111: 'switch' - if content updates mean user's session
                   19112:            needs to be switched to a server running a newer LON-CAPA version
                   19113:  
                   19114: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   19115:            on current server hosting user's session                
                   19116: 
                   19117: ''       - if no action required.
                   19118: 
                   19119: =back
                   19120: 
                   19121: If first item element is 'switch':
                   19122: 
                   19123: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   19124: 
                   19125: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   19126:                               and current role. 
                   19127: 
                   19128: otherwise: no other elements returned.
                   19129: 
                   19130: =back
                   19131: 
                   19132: =cut
                   19133: 
                   19134: sub needs_coursereinit {
                   19135:     my ($loncaparev,$interval) = @_;
                   19136:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   19137:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19138:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   19139:     my $now = time;
                   19140:     if ($interval eq '') {
                   19141:         $interval = 600;
                   19142:     }
                   19143:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  19144:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  19145:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19146:         if ($blocked) {
                   19147:             return ();
                   19148:         }
1.1391    raeburn  19149:         my $update;
                   19150:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19151:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   19152:         if ($lastmainchange > $env{'request.course.tied'}) {
                   19153:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19154:             if ($needswitch) {
                   19155:                 return ('switch',$switchwarning,$switchserver);
                   19156:             }
                   19157:             $update = 'main';
                   19158:         }
                   19159:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   19160:             if ($update) {
                   19161:                 $update = 'both';
                   19162:             } else {
                   19163:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19164:                 if ($needswitch) {
                   19165:                     return ('switch',$switchwarning,$switchserver);
                   19166:                 } else {
                   19167:                     $update = 'supp';
1.1207    raeburn  19168:                 }
                   19169:             }
1.1391    raeburn  19170:         }
1.1453    raeburn  19171:         return ($update);
1.1391    raeburn  19172:     }
                   19173:     return ();
                   19174: }
                   19175: 
                   19176: sub switch_for_update {
                   19177:     my ($loncaparev,$cdom,$cnum) = @_;
                   19178:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19179:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   19180:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   19181:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   19182:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   19183:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   19184:             my ($switchserver,$switchwarning) =
                   19185:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   19186:                                         $curr_reqd_hash{'internal.releaserequired'});
                   19187:             if ($switchwarning ne '' || $switchserver ne '') {
                   19188:                 return ('switch',$switchwarning,$switchserver);
                   19189:             }
1.1207    raeburn  19190:         }
                   19191:     }
                   19192:     return ();
                   19193: }
1.1181    raeburn  19194: 
1.1083    raeburn  19195: sub update_content_constraints {
1.1395    raeburn  19196:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  19197:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19198:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  19199:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  19200:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  19201:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  19202:         if ($item eq 'resourcetag') {
                   19203:             if ($name eq 'responsetype') {
                   19204:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   19205:             }
1.1307    raeburn  19206:         } elsif ($item eq 'course') {
                   19207:             if ($name eq 'courserestype') {
                   19208:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   19209:             }
1.1083    raeburn  19210:         }
                   19211:     }
                   19212:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19213:     if (defined($navmap)) {
1.1307    raeburn  19214:         my (%allresponses,%allcrsrestypes);
                   19215:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   19216:             if ($res->is_tool()) {
                   19217:                 if ($allcrsrestypes{'exttool'}) {
                   19218:                     $allcrsrestypes{'exttool'} ++;
                   19219:                 } else {
                   19220:                     $allcrsrestypes{'exttool'} = 1;
                   19221:                 }
                   19222:                 next;
                   19223:             }
1.1083    raeburn  19224:             my %responses = $res->responseTypes();
                   19225:             foreach my $key (keys(%responses)) {
                   19226:                 next unless(exists($checkresponsetypes{$key}));
                   19227:                 $allresponses{$key} += $responses{$key};
                   19228:             }
                   19229:         }
                   19230:         foreach my $key (keys(%allresponses)) {
                   19231:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   19232:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19233:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19234:             }
                   19235:         }
1.1307    raeburn  19236:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  19237:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  19238:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19239:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19240:             }
                   19241:         }
1.1083    raeburn  19242:         undef($navmap);
                   19243:     }
1.1391    raeburn  19244:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  19245:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   19246:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19247:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   19248:         }
                   19249:     }
1.1083    raeburn  19250:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   19251:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   19252:     }
                   19253:     return;
                   19254: }
                   19255: 
1.1110    raeburn  19256: sub allmaps_incourse {
                   19257:     my ($cdom,$cnum,$chome,$cid) = @_;
                   19258:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   19259:         $cid = $env{'request.course.id'};
                   19260:         $cdom = $env{'course.'.$cid.'.domain'};
                   19261:         $cnum = $env{'course.'.$cid.'.num'};
                   19262:         $chome = $env{'course.'.$cid.'.home'};
                   19263:     }
                   19264:     my %allmaps = ();
                   19265:     my $lastchange =
                   19266:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19267:     if ($lastchange > $env{'request.course.tied'}) {
                   19268:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   19269:         unless ($ferr) {
1.1395    raeburn  19270:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  19271:         }
                   19272:     }
                   19273:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19274:     if (defined($navmap)) {
                   19275:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   19276:             $allmaps{$res->src()} = 1;
                   19277:         }
                   19278:     }
                   19279:     return \%allmaps;
                   19280: }
                   19281: 
1.1083    raeburn  19282: sub parse_supplemental_title {
                   19283:     my ($title) = @_;
                   19284: 
                   19285:     my ($foldertitle,$renametitle);
                   19286:     if ($title =~ /&amp;&amp;&amp;/) {
                   19287:         $title = &HTML::Entites::decode($title);
                   19288:     }
                   19289:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   19290:         $renametitle=$4;
                   19291:         my ($time,$uname,$udom) = ($1,$2,$3);
                   19292:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   19293:         my $name =  &plainname($uname,$udom);
                   19294:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   19295:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1401    raeburn  19296:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
1.1402    raeburn  19297:         if ($foldertitle ne '') {
1.1401    raeburn  19298:             $title .= ': <br />'.$foldertitle;
                   19299:         }
1.1083    raeburn  19300:     }
                   19301:     if (wantarray) {
                   19302:         return ($title,$foldertitle,$renametitle);
                   19303:     }
                   19304:     return $title;
                   19305: }
                   19306: 
1.1395    raeburn  19307: sub get_supplemental {
                   19308:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   19309:     my $hashid=$cnum.':'.$cdom;
                   19310:     my ($supplemental,$cached,$set_httprefs);
                   19311:     unless ($ignorecache) {
                   19312:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   19313:     }
                   19314:     unless (defined($cached)) {
                   19315:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   19316:         unless ($chome eq 'no_host') {
                   19317:             my @order = @LONCAPA::map::order;
                   19318:             my @resources = @LONCAPA::map::resources;
                   19319:             my @resparms = @LONCAPA::map::resparms;
                   19320:             my @zombies = @LONCAPA::map::zombies;
                   19321:             my ($errors,%ids,%hidden);
                   19322:             $errors =
                   19323:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   19324:                                       $errors,$possdel,\%ids,\%hidden);
                   19325:             @LONCAPA::map::order = @order;
                   19326:             @LONCAPA::map::resources = @resources;
                   19327:             @LONCAPA::map::resparms = @resparms;
                   19328:             @LONCAPA::map::zombies = @zombies;
                   19329:             $set_httprefs = 1;
                   19330:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19331:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19332:             }
                   19333:             $supplemental = {
                   19334:                                ids => \%ids,
                   19335:                                hidden => \%hidden,
                   19336:                             };
                   19337:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   19338:         }
                   19339:     }
                   19340:     return ($supplemental,$set_httprefs);
                   19341: }
                   19342: 
1.1143    raeburn  19343: sub recurse_supplemental {
1.1391    raeburn  19344:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   19345:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   19346:         my $mapnum;
                   19347:         if ($suppmap eq 'supplemental.sequence') {
                   19348:             $mapnum = 0;
                   19349:         } else {
                   19350:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   19351:         }
1.1143    raeburn  19352:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   19353:         if ($fatal) {
                   19354:             $errors ++;
                   19355:         } else {
1.1389    raeburn  19356:             my @order = @LONCAPA::map::order;
                   19357:             if (@order > 0) {
                   19358:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  19359:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  19360:                 foreach my $idx (@order) {
                   19361:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  19362:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  19363:                         my $id = $mapnum.':'.$idx;
                   19364:                         push(@{$suppids->{$src}},$id);
                   19365:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   19366:                             $hiddensupp->{$id} = 1;
                   19367:                         }
1.1146    raeburn  19368:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  19369:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   19370:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  19371:                         } else {
1.1391    raeburn  19372:                             my $allowed;
                   19373:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   19374:                                 $allowed = 1;
                   19375:                             } elsif ($possdel) {
                   19376:                                 foreach my $item (@{$suppids->{$src}}) {
                   19377:                                     next if ($item eq $id);
                   19378:                                     unless ($hiddensupp->{$item}) {
                   19379:                                        $allowed = 1;
                   19380:                                        last;
                   19381:                                     }
                   19382:                                 }
                   19383:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   19384:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   19385:                                 }
                   19386:                             }
                   19387:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   19388:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  19389:                             }
1.1143    raeburn  19390:                         }
                   19391:                     }
                   19392:                 }
                   19393:             }
                   19394:         }
                   19395:     }
1.1391    raeburn  19396:     return $errors;
                   19397: }
                   19398: 
                   19399: sub set_supp_httprefs {
                   19400:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   19401:     if (ref($supplemental) eq 'HASH') {
                   19402:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   19403:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   19404:                 next if ($src =~ /\.sequence$/);
                   19405:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   19406:                     my $allowed;
                   19407:                     if ($env{'request.role.adv'}) {
                   19408:                         $allowed = 1;
                   19409:                     } else {
                   19410:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   19411:                             unless ($supplemental->{'hidden'}->{$id}) {
                   19412:                                 $allowed = 1;
                   19413:                                 last;
                   19414:                             }
                   19415:                         }
                   19416:                     }
                   19417:                     if (exists($env{'httpref.'.$src})) {
                   19418:                         if ($possdel) {
                   19419:                             unless ($allowed) {
                   19420:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   19421:                             }
                   19422:                         }
                   19423:                     } elsif ($allowed) {
                   19424:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   19425:                     }
                   19426:                 }
                   19427:             }
                   19428:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19429:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19430:             }
                   19431:         }
                   19432:     }
                   19433: }
                   19434: 
                   19435: sub get_supp_parameter {
                   19436:     my ($resparm,$name)=@_;
                   19437:     return if ($resparm eq '');
                   19438:     my $value=undef;
                   19439:     my $ptype=undef;
                   19440:     foreach (split('&&&',$resparm)) {
                   19441:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   19442:         if ($thisname eq $name) {
                   19443:             $value=$thisvalue;
                   19444:             $ptype=$thistype;
                   19445:         }
                   19446:     }
                   19447:     return $value;
1.1143    raeburn  19448: }
                   19449: 
1.1101    raeburn  19450: sub symb_to_docspath {
1.1267    raeburn  19451:     my ($symb,$navmapref) = @_;
                   19452:     return unless ($symb && ref($navmapref));
1.1101    raeburn  19453:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   19454:     if ($resurl=~/\.(sequence|page)$/) {
                   19455:         $mapurl=$resurl;
                   19456:     } elsif ($resurl eq 'adm/navmaps') {
                   19457:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   19458:     }
                   19459:     my $mapresobj;
1.1267    raeburn  19460:     unless (ref($$navmapref)) {
                   19461:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   19462:     }
                   19463:     if (ref($$navmapref)) {
                   19464:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  19465:     }
                   19466:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   19467:     my $type=$2;
                   19468:     my $path;
                   19469:     if (ref($mapresobj)) {
                   19470:         my $pcslist = $mapresobj->map_hierarchy();
                   19471:         if ($pcslist ne '') {
                   19472:             foreach my $pc (split(/,/,$pcslist)) {
                   19473:                 next if ($pc <= 1);
1.1267    raeburn  19474:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  19475:                 if (ref($res)) {
                   19476:                     my $thisurl = $res->src();
                   19477:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   19478:                     my $thistitle = $res->title();
                   19479:                     $path .= '&'.
                   19480:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  19481:                              &escape($thistitle).
1.1101    raeburn  19482:                              ':'.$res->randompick().
                   19483:                              ':'.$res->randomout().
                   19484:                              ':'.$res->encrypted().
                   19485:                              ':'.$res->randomorder().
                   19486:                              ':'.$res->is_page();
                   19487:                 }
                   19488:             }
                   19489:         }
                   19490:         $path =~ s/^\&//;
                   19491:         my $maptitle = $mapresobj->title();
                   19492:         if ($mapurl eq 'default') {
1.1129    raeburn  19493:             $maptitle = 'Main Content';
1.1101    raeburn  19494:         }
                   19495:         $path .= (($path ne '')? '&' : '').
                   19496:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19497:                  &escape($maptitle).
1.1101    raeburn  19498:                  ':'.$mapresobj->randompick().
                   19499:                  ':'.$mapresobj->randomout().
                   19500:                  ':'.$mapresobj->encrypted().
                   19501:                  ':'.$mapresobj->randomorder().
                   19502:                  ':'.$mapresobj->is_page();
                   19503:     } else {
                   19504:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   19505:         my $ispage = (($type eq 'page')? 1 : '');
                   19506:         if ($mapurl eq 'default') {
1.1129    raeburn  19507:             $maptitle = 'Main Content';
1.1101    raeburn  19508:         }
                   19509:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19510:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  19511:     }
                   19512:     unless ($mapurl eq 'default') {
                   19513:         $path = 'default&'.
1.1146    raeburn  19514:                 &escape('Main Content').
1.1101    raeburn  19515:                 ':::::&'.$path;
                   19516:     }
                   19517:     return $path;
                   19518: }
                   19519: 
1.1393    raeburn  19520: sub validate_folderpath {
                   19521:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   19522:     if ($env{'form.folderpath'} ne '') {
                   19523:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  19524:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  19525:         for (my $i=0; $i<@items; $i++) {
                   19526:             my $odd = $i%2;
                   19527:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   19528:                 $badpath = 1;
1.1394    raeburn  19529:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  19530:                 my $idx = $i-1;
1.1394    raeburn  19531:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   19532:                     my $esc_name = $1;
                   19533:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   19534:                         $supppath .= '&'.$esc_name;
                   19535:                         $changed = 1;
                   19536:                     } else {
                   19537:                         $supppath .= '&'.$items[$i];
                   19538:                     }
                   19539:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   19540:                     $changed = 1;
1.1393    raeburn  19541:                     my $is_hidden;
                   19542:                     unless ($got_supp) {
1.1395    raeburn  19543:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  19544:                         if (ref($supplemental) eq 'HASH') {
                   19545:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   19546:                                 %supphidden = %{$supplemental->{'hidden'}};
                   19547:                             }
                   19548:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   19549:                                 %suppids = %{$supplemental->{'ids'}};
                   19550:                             }
                   19551:                         }
                   19552:                         $got_supp = 1;
                   19553:                     }
                   19554:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   19555:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   19556:                         if ($supphidden{$mapid}) {
                   19557:                             $is_hidden = 1;
                   19558:                         }
                   19559:                     }
1.1394    raeburn  19560:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   19561:                 } else {
                   19562:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  19563:                 }
                   19564:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   19565:                 $badpath = 1;
1.1394    raeburn  19566:             } elsif ($supplementalflag) {
1.1393    raeburn  19567:                 $supppath .= '&'.$items[$i];
                   19568:             }
                   19569:             last if ($badpath);
                   19570:         }
                   19571:         if ($badpath) {
                   19572:             delete($env{'form.folderpath'});
1.1394    raeburn  19573:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  19574:             $supppath =~ s/^\&//;
                   19575:             $env{'form.folderpath'} = $supppath;
                   19576:         }
                   19577:     }
                   19578:     return;
                   19579: }
                   19580: 
1.1094    raeburn  19581: sub captcha_display {
1.1327    raeburn  19582:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19583:     my ($output,$error);
1.1234    raeburn  19584:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  19585:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19586:     if ($captcha eq 'original') {
1.1094    raeburn  19587:         $output = &create_captcha();
                   19588:         unless ($output) {
1.1172    raeburn  19589:             $error = 'captcha';
1.1094    raeburn  19590:         }
                   19591:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19592:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  19593:         unless ($output) {
1.1172    raeburn  19594:             $error = 'recaptcha';
1.1094    raeburn  19595:         }
                   19596:     }
1.1234    raeburn  19597:     return ($output,$error,$captcha,$version);
1.1094    raeburn  19598: }
                   19599: 
                   19600: sub captcha_response {
1.1327    raeburn  19601:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19602:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  19603:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19604:     if ($captcha eq 'original') {
1.1094    raeburn  19605:         ($captcha_chk,$captcha_error) = &check_captcha();
                   19606:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19607:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  19608:     } else {
                   19609:         $captcha_chk = 1;
                   19610:     }
                   19611:     return ($captcha_chk,$captcha_error);
                   19612: }
                   19613: 
                   19614: sub get_captcha_config {
1.1327    raeburn  19615:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  19616:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  19617:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   19618:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   19619:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  19620:     if ($context eq 'usercreation') {
                   19621:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   19622:         if (ref($domconfig{$context}) eq 'HASH') {
                   19623:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   19624:             if (ref($hashtocheck) eq 'HASH') {
                   19625:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   19626:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   19627:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   19628:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   19629:                     }
                   19630:                     if ($privkey && $pubkey) {
                   19631:                         $captcha = 'recaptcha';
1.1234    raeburn  19632:                         $version = $hashtocheck->{'recaptchaversion'};
                   19633:                         if ($version ne '2') {
                   19634:                             $version = 1;
                   19635:                         }
1.1095    raeburn  19636:                     } else {
                   19637:                         $captcha = 'original';
                   19638:                     }
                   19639:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   19640:                     $captcha = 'original';
                   19641:                 }
1.1094    raeburn  19642:             }
1.1095    raeburn  19643:         } else {
                   19644:             $captcha = 'captcha';
                   19645:         }
                   19646:     } elsif ($context eq 'login') {
                   19647:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   19648:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   19649:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   19650:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  19651:             if ($privkey && $pubkey) {
                   19652:                 $captcha = 'recaptcha';
1.1234    raeburn  19653:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   19654:                 if ($version ne '2') {
                   19655:                     $version = 1; 
                   19656:                 }
1.1095    raeburn  19657:             } else {
                   19658:                 $captcha = 'original';
1.1094    raeburn  19659:             }
1.1095    raeburn  19660:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   19661:             $captcha = 'original';
1.1094    raeburn  19662:         }
1.1327    raeburn  19663:     } elsif ($context eq 'passwords') {
                   19664:         if ($dom_in_effect) {
                   19665:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   19666:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   19667:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   19668:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   19669:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   19670:                 }
                   19671:                 if ($privkey && $pubkey) {
                   19672:                     $captcha = 'recaptcha';
                   19673:                     $version = $passwdconf{'recaptchaversion'};
                   19674:                     if ($version ne '2') {
                   19675:                         $version = 1;
                   19676:                     }
                   19677:                 } else {
                   19678:                     $captcha = 'original';
                   19679:                 }
                   19680:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   19681:                 $captcha = 'original';
                   19682:             }
                   19683:         }
                   19684:     } 
1.1234    raeburn  19685:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  19686: }
                   19687: 
                   19688: sub create_captcha {
                   19689:     my %captcha_params = &captcha_settings();
                   19690:     my ($output,$maxtries,$tries) = ('',10,0);
                   19691:     while ($tries < $maxtries) {
                   19692:         $tries ++;
                   19693:         my $captcha = Authen::Captcha->new (
                   19694:                                            output_folder => $captcha_params{'output_dir'},
                   19695:                                            data_folder   => $captcha_params{'db_dir'},
                   19696:                                           );
                   19697:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   19698: 
                   19699:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   19700:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  19701:                       '<span class="LC_nobreak">'.
1.1453    raeburn  19702:                       '<label>'.&mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1463    raeburn  19703:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" aria-required="true" />'.
1.1453    raeburn  19704:                       '</label></span><br />'.
1.1176    raeburn  19705:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  19706:             last;
                   19707:         }
                   19708:     }
1.1323    raeburn  19709:     if ($output eq '') {
                   19710:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   19711:     }
1.1094    raeburn  19712:     return $output;
                   19713: }
                   19714: 
                   19715: sub captcha_settings {
                   19716:     my %captcha_params = (
                   19717:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   19718:                            www_output_dir => "/captchaspool",
                   19719:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   19720:                            numchars       => '5',
                   19721:                          );
                   19722:     return %captcha_params;
                   19723: }
                   19724: 
                   19725: sub check_captcha {
                   19726:     my ($captcha_chk,$captcha_error);
                   19727:     my $code = $env{'form.code'};
                   19728:     my $md5sum = $env{'form.crypt'};
                   19729:     my %captcha_params = &captcha_settings();
                   19730:     my $captcha = Authen::Captcha->new(
                   19731:                       output_folder => $captcha_params{'output_dir'},
                   19732:                       data_folder   => $captcha_params{'db_dir'},
                   19733:                   );
1.1109    raeburn  19734:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  19735:     my %captcha_hash = (
                   19736:                         0       => 'Code not checked (file error)',
                   19737:                        -1      => 'Failed: code expired',
                   19738:                        -2      => 'Failed: invalid code (not in database)',
                   19739:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   19740:     );
                   19741:     if ($captcha_chk != 1) {
                   19742:         $captcha_error = $captcha_hash{$captcha_chk}
                   19743:     }
                   19744:     return ($captcha_chk,$captcha_error);
                   19745: }
                   19746: 
                   19747: sub create_recaptcha {
1.1234    raeburn  19748:     my ($pubkey,$version) = @_;
                   19749:     if ($version >= 2) {
1.1367    raeburn  19750:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   19751:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  19752:     } else {
                   19753:         my $use_ssl;
                   19754:         if ($ENV{'SERVER_PORT'} == 443) {
                   19755:             $use_ssl = 1;
                   19756:         }
                   19757:         my $captcha = Captcha::reCAPTCHA->new;
                   19758:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   19759:                $captcha->get_html($pubkey,undef,$use_ssl).
                   19760:                &mt('If the text is hard to read, [_1] will replace them.',
                   19761:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   19762:                '<br /><br />';
                   19763:     }
1.1094    raeburn  19764: }
                   19765: 
                   19766: sub check_recaptcha {
1.1234    raeburn  19767:     my ($privkey,$version) = @_;
1.1094    raeburn  19768:     my $captcha_chk;
1.1350    raeburn  19769:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  19770:     if ($version >= 2) {
                   19771:         my %info = (
                   19772:                      secret   => $privkey, 
                   19773:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  19774:                      remoteip => $ip,
1.1234    raeburn  19775:                    );
1.1280    raeburn  19776:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   19777:         $request->content(join('&',map {
                   19778:                          my $name = escape($_);
                   19779:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   19780:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   19781:                          : &escape($info{$_}) );
                   19782:         } keys(%info)));
                   19783:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  19784:         if ($response->is_success)  {
                   19785:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   19786:             if (ref($data) eq 'HASH') {
                   19787:                 if ($data->{'success'}) {
                   19788:                     $captcha_chk = 1;
                   19789:                 }
                   19790:             }
                   19791:         }
                   19792:     } else {
                   19793:         my $captcha = Captcha::reCAPTCHA->new;
                   19794:         my $captcha_result =
                   19795:             $captcha->check_answer(
                   19796:                                     $privkey,
1.1350    raeburn  19797:                                     $ip,
1.1234    raeburn  19798:                                     $env{'form.recaptcha_challenge_field'},
                   19799:                                     $env{'form.recaptcha_response_field'},
                   19800:                                   );
                   19801:         if ($captcha_result->{is_valid}) {
                   19802:             $captcha_chk = 1;
                   19803:         }
1.1094    raeburn  19804:     }
                   19805:     return $captcha_chk;
                   19806: }
                   19807: 
1.1174    raeburn  19808: sub emailusername_info {
1.1244    raeburn  19809:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  19810:     my %titles = &Apache::lonlocal::texthash (
                   19811:                      lastname      => 'Last Name',
                   19812:                      firstname     => 'First Name',
                   19813:                      institution   => 'School/college/university',
                   19814:                      location      => "School's city, state/province, country",
                   19815:                      web           => "School's web address",
                   19816:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  19817:                      id            => 'Student/Employee ID',
1.1174    raeburn  19818:                  );
                   19819:     return (\@fields,\%titles);
                   19820: }
                   19821: 
1.1161    raeburn  19822: sub cleanup_html {
                   19823:     my ($incoming) = @_;
                   19824:     my $outgoing;
                   19825:     if ($incoming ne '') {
                   19826:         $outgoing = $incoming;
                   19827:         $outgoing =~ s/;/&#059;/g;
                   19828:         $outgoing =~ s/\#/&#035;/g;
                   19829:         $outgoing =~ s/\&/&#038;/g;
                   19830:         $outgoing =~ s/</&#060;/g;
                   19831:         $outgoing =~ s/>/&#062;/g;
                   19832:         $outgoing =~ s/\(/&#040/g;
                   19833:         $outgoing =~ s/\)/&#041;/g;
                   19834:         $outgoing =~ s/"/&#034;/g;
                   19835:         $outgoing =~ s/'/&#039;/g;
                   19836:         $outgoing =~ s/\$/&#036;/g;
                   19837:         $outgoing =~ s{/}{&#047;}g;
                   19838:         $outgoing =~ s/=/&#061;/g;
                   19839:         $outgoing =~ s/\\/&#092;/g
                   19840:     }
                   19841:     return $outgoing;
                   19842: }
                   19843: 
1.1190    musolffc 19844: # Checks for critical messages and returns a redirect url if one exists.
                   19845: # $interval indicates how often to check for messages.
1.1282    raeburn  19846: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19847: sub critical_redirect {
1.1282    raeburn  19848:     my ($interval,$context) = @_;
1.1356    raeburn  19849:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19850:         return ();
                   19851:     }
1.1190    musolffc 19852:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19853:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19854:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19855:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19856:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19857:             if ($blocked) {
                   19858:                 my $checkrole = "cm./$cdom/$cnum";
                   19859:                 if ($env{'request.course.sec'} ne '') {
                   19860:                     $checkrole .= "/$env{'request.course.sec'}";
                   19861:                 }
                   19862:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19863:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19864:                     return;
                   19865:                 }
                   19866:             }
                   19867:         }
1.1190    musolffc 19868:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19869:                                         $env{'user.name'});
                   19870:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19871:         my $redirecturl;
1.1190    musolffc 19872:         if ($what[0]) {
1.1356    raeburn  19873: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19874: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19875: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19876:                 return (1, $url);
1.1190    musolffc 19877:             }
1.1191    raeburn  19878:         }
                   19879:     } 
                   19880:     return ();
1.1190    musolffc 19881: }
                   19882: 
1.1174    raeburn  19883: # Use:
                   19884: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19885: #
                   19886: ##################################################
                   19887: #          password associated functions         #
                   19888: ##################################################
                   19889: sub des_keys {
                   19890:     # Make a new key for DES encryption.
                   19891:     # Each key has two parts which are returned separately.
                   19892:     # Please note:  Each key must be passed through the &hex function
                   19893:     # before it is output to the web browser.  The hex versions cannot
                   19894:     # be used to decrypt.
                   19895:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19896:                 '8','9','a','b','c','d','e','f');
                   19897:     my $lkey='';
                   19898:     for (0..7) {
                   19899:         $lkey.=$hexstr[rand(15)];
                   19900:     }
                   19901:     my $ukey='';
                   19902:     for (0..7) {
                   19903:         $ukey.=$hexstr[rand(15)];
                   19904:     }
                   19905:     return ($lkey,$ukey);
                   19906: }
                   19907: 
                   19908: sub des_decrypt {
                   19909:     my ($key,$cyphertext) = @_;
                   19910:     my $keybin=pack("H16",$key);
                   19911:     my $cypher;
                   19912:     if ($Crypt::DES::VERSION>=2.03) {
                   19913:         $cypher=new Crypt::DES $keybin;
                   19914:     } else {
                   19915:         $cypher=new DES $keybin;
                   19916:     }
1.1233    raeburn  19917:     my $plaintext='';
                   19918:     my $cypherlength = length($cyphertext);
                   19919:     my $numchunks = int($cypherlength/32);
                   19920:     for (my $j=0; $j<$numchunks; $j++) {
                   19921:         my $start = $j*32;
                   19922:         my $cypherblock = substr($cyphertext,$start,32);
                   19923:         my $chunk =
                   19924:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   19925:         $chunk .=
                   19926:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   19927:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   19928:         $plaintext .= $chunk;
                   19929:     }
1.1174    raeburn  19930:     return $plaintext;
                   19931: }
                   19932: 
1.1344    raeburn  19933: sub get_requested_shorturls {
1.1309    raeburn  19934:     my ($cdom,$cnum,$navmap) = @_;
                   19935:     return unless (ref($navmap));
1.1344    raeburn  19936:     my ($numnew,$errors);
1.1309    raeburn  19937:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   19938:     if (@toshorten) {
                   19939:         my (%maps,%resources,%titles);
                   19940:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   19941:                                                                'shorturls',$cdom,$cnum);
                   19942:         if (keys(%resources)) {
1.1344    raeburn  19943:             my %tocreate;
1.1309    raeburn  19944:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   19945:                 my $symb = $resources{$item};
                   19946:                 if ($symb) {
                   19947:                     $tocreate{$cnum.'&'.$symb} = 1;
                   19948:                 }
                   19949:             }
1.1344    raeburn  19950:             if (keys(%tocreate)) {
                   19951:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   19952:                                                       \%tocreate);
                   19953:             }
1.1309    raeburn  19954:         }
1.1344    raeburn  19955:     }
                   19956:     return ($numnew,$errors);
                   19957: }
                   19958: 
                   19959: sub make_short_symbs {
                   19960:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   19961:     my ($numnew,@errors);
                   19962:     if (ref($tocreateref) eq 'HASH') {
                   19963:         my %tocreate = %{$tocreateref};
1.1309    raeburn  19964:         if (keys(%tocreate)) {
                   19965:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   19966:             my $su = Short::URL->new(no_vowels => 1);
                   19967:             my $init = '';
                   19968:             my (%newunique,%addcourse,%courseonly,%failed);
                   19969:             # get lock on tiny db
                   19970:             my $now = time;
1.1344    raeburn  19971:             if ($lockuser eq '') {
                   19972:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   19973:             }
1.1309    raeburn  19974:             my $lockhash = {
1.1344    raeburn  19975:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  19976:                             };
                   19977:             my $tries = 0;
                   19978:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19979:             my ($code,$error);
                   19980:             while (($gotlock ne 'ok') && ($tries<3)) {
                   19981:                 $tries ++;
                   19982:                 sleep 1;
1.1319    raeburn  19983:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  19984:             }
                   19985:             if ($gotlock eq 'ok') {
                   19986:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   19987:                                        \%addcourse,\%courseonly,\%failed);
                   19988:                 if (keys(%failed)) {
                   19989:                     my $numfailed = scalar(keys(%failed));
                   19990:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   19991:                 }
                   19992:                 if (keys(%newunique)) {
                   19993:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   19994:                     if ($putres eq 'ok') {
                   19995:                         $numnew = scalar(keys(%newunique));
                   19996:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   19997:                         unless ($newputres eq 'ok') {
                   19998:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   19999:                         }
                   20000:                     } else {
                   20001:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   20002:                     }
                   20003:                 }
                   20004:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   20005:                 unless ($dellockres eq 'ok') {
                   20006:                     push(@errors,&mt('error: could not release lockfile'));
                   20007:                 }
                   20008:             } else {
                   20009:                 push(@errors,&mt('error: could not obtain lockfile'));
                   20010:             }
                   20011:             if (keys(%courseonly)) {
                   20012:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   20013:                 if ($result ne 'ok') {
                   20014:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   20015:                 }
                   20016:             }
                   20017:         }
                   20018:     }
                   20019:     return ($numnew,\@errors);
                   20020: }
                   20021: 
                   20022: sub shorten_symbs {
                   20023:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   20024:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   20025:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   20026:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   20027:     my (%possibles,%collisions);
                   20028:     foreach my $key (keys(%{$tocreate})) {
                   20029:         my $num = String::CRC32::crc32($key);
                   20030:         my $tiny = $su->encode($num,$init);
                   20031:         if ($tiny) {
                   20032:             $possibles{$tiny} = $key;
                   20033:         }
                   20034:     }
                   20035:     if (!$init) {
                   20036:         $init = 1;
                   20037:     } else {
                   20038:         $init ++;
                   20039:     }
                   20040:     if (keys(%possibles)) {
                   20041:         my @posstiny = keys(%possibles);
                   20042:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   20043:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   20044:         if (keys(%currtiny)) {
                   20045:             foreach my $key (keys(%currtiny)) {
                   20046:                 next if ($currtiny{$key} eq '');
                   20047:                 if ($currtiny{$key} eq $possibles{$key}) {
                   20048:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   20049:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   20050:                         $courseonly->{$tsymb} = $key;
                   20051:                     }
                   20052:                 } else {
                   20053:                     $collisions{$possibles{$key}} = 1;
                   20054:                 }
                   20055:                 delete($possibles{$key});
                   20056:             }
                   20057:         }
                   20058:         foreach my $key (keys(%possibles)) {
                   20059:             $newunique->{$key} = $possibles{$key};
                   20060:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   20061:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   20062:                 $addcourse->{$tsymb} = $key;
                   20063:             }
                   20064:         }
                   20065:     }
                   20066:     if (keys(%collisions)) {
                   20067:         if ($init <5) {
                   20068:             if (!$init) {
                   20069:                 $init = 1;
                   20070:             } else {
                   20071:                 $init ++;
                   20072:             }
                   20073:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   20074:                                    $newunique,$addcourse,$courseonly,$failed);
                   20075:         } else {
                   20076:             foreach my $key (keys(%collisions)) {
                   20077:                 $failed->{$key} = 1;
                   20078:             }
                   20079:         }
                   20080:     }
                   20081:     return $init;
                   20082: }
                   20083: 
1.1328    raeburn  20084: sub is_nonframeable {
1.1329    raeburn  20085:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   20086:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  20087:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  20088: 
                   20089:     $remprotocol = lc($remprotocol);
                   20090:     $remhost = lc($remhost);
                   20091:     my $remport = 80;
                   20092:     if ($remprotocol eq 'https') {
                   20093:         $remport = 443;
                   20094:     }
1.1330    raeburn  20095:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  20096:     if ($cached) {
                   20097:         unless ($nocache) {
                   20098:             if ($result) {
                   20099:                 return 1;
                   20100:             } else {
                   20101:                 return 0;
                   20102:             }
                   20103:         }
                   20104:     }
1.1328    raeburn  20105:     my $uselink;
                   20106:     my $request = new HTTP::Request('HEAD',$url);
                   20107:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   20108:     if ($response->is_success()) {
                   20109:         my $secpolicy = lc($response->header('content-security-policy'));
                   20110:         my $xframeop = lc($response->header('x-frame-options'));
                   20111:         $secpolicy =~ s/^\s+|\s+$//g;
                   20112:         $xframeop =~ s/^\s+|\s+$//g;
                   20113:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  20114:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  20115:             my ($origin,$protocol,$port);
                   20116:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   20117:                 $port = $ENV{'SERVER_PORT'};
                   20118:             } else {
                   20119:                 $port = 80;
                   20120:             }
                   20121:             if ($absolute eq '') {
                   20122:                 $protocol = 'http:';
                   20123:                 if ($port == 443) {
                   20124:                     $protocol = 'https:';
                   20125:                 }
                   20126:                 $origin = $protocol.'//'.lc($hostname);
                   20127:             } else {
                   20128:                 $origin = lc($absolute);
                   20129:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   20130:             }
                   20131:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   20132:                 my $framepolicy = $1;
                   20133:                 $framepolicy =~ s/^\s+|\s+$//g;
                   20134:                 my @policies = split(/\s+/,$framepolicy);
                   20135:                 if (@policies) {
                   20136:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   20137:                         $uselink = 1;
                   20138:                     } else {
                   20139:                         $uselink = 1;
                   20140:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   20141:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   20142:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   20143:                             undef($uselink);
                   20144:                         }
                   20145:                         if ($uselink) {
                   20146:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   20147:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   20148:                                     undef($uselink);
                   20149:                                 }
                   20150:                             }
                   20151:                         }
                   20152:                         if ($uselink) {
                   20153:                             my @possok;
                   20154:                             if ($ip ne '') {
                   20155:                                 push(@possok,$ip);
                   20156:                             }
                   20157:                             my $hoststr = '';
                   20158:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   20159:                                 if ($hoststr eq '') {
                   20160:                                     $hoststr = $part;
                   20161:                                 } else {
                   20162:                                     $hoststr = "$part.$hoststr";
                   20163:                                 }
                   20164:                                 if ($hoststr eq $hostname) {
                   20165:                                     push(@possok,$hostname);
                   20166:                                 } else {
                   20167:                                     push(@possok,"*.$hoststr");
                   20168:                                 }
                   20169:                             }
                   20170:                             if (@possok) {
                   20171:                                 foreach my $poss (@possok) {
                   20172:                                     last if (!$uselink);
                   20173:                                     foreach my $policy (@policies) {
                   20174:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   20175:                                             undef($uselink);
                   20176:                                             last;
                   20177:                                         }
                   20178:                                     }
                   20179:                                 }
                   20180:                             }
                   20181:                         }
                   20182:                     }
                   20183:                 }
                   20184:             } elsif ($xframeop ne '') {
                   20185:                 $uselink = 1;
                   20186:                 my @policies = split(/\s*,\s*/,$xframeop);
                   20187:                 if (@policies) {
                   20188:                     unless (grep(/^deny$/,@policies)) {
                   20189:                         if ($origin ne '') {
                   20190:                             if (grep(/^sameorigin$/,@policies)) {
                   20191:                                 if ($remotehost eq $origin) {
                   20192:                                     undef($uselink);
                   20193:                                 }
                   20194:                             }
                   20195:                             if ($uselink) {
                   20196:                                 foreach my $policy (@policies) {
                   20197:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   20198:                                         my $allowfrom = $1;
                   20199:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   20200:                                             undef($uselink);
                   20201:                                             last;
                   20202:                                         }
                   20203:                                     }
                   20204:                                 }
                   20205:                             }
                   20206:                         }
                   20207:                     }
                   20208:                 }
                   20209:             }
                   20210:         }
                   20211:     }
1.1329    raeburn  20212:     if ($nocache) {
                   20213:         if ($cached) {
                   20214:             my $devalidate;
                   20215:             if ($uselink && !$result) {
                   20216:                 $devalidate = 1;
                   20217:             } elsif (!$uselink && $result) {
                   20218:                 $devalidate = 1;
                   20219:             }
                   20220:             if ($devalidate) {
                   20221:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   20222:             }
                   20223:         }
                   20224:     } else {
                   20225:         if ($uselink) {
                   20226:             $result = 1;
                   20227:         } else {
                   20228:             $result = 0;
                   20229:         }
                   20230:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   20231:     }
1.1328    raeburn  20232:     return $uselink;
                   20233: }
                   20234: 
1.1359    raeburn  20235: sub page_menu {
                   20236:     my ($menucolls,$menunum) = @_;
                   20237:     my %menu;
                   20238:     foreach my $item (split(/;/,$menucolls)) {
                   20239:         my ($num,$value) = split(/\%/,$item);
                   20240:         if ($num eq $menunum) {
                   20241:             my @entries = split(/\&/,$value);
                   20242:             foreach my $entry (@entries) {
                   20243:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  20244:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  20245:                     $menu{$name} = $fields;
                   20246:                 } else {
                   20247:                     my @shown;
                   20248:                     if ($fields =~ /,/) {
                   20249:                         @shown = split(/,/,$fields);
                   20250:                     } else {
                   20251:                         @shown = ($fields);
                   20252:                     }
                   20253:                     if (@shown) {
                   20254:                         foreach my $field (@shown) {
                   20255:                             next if ($field eq '');
                   20256:                             $menu{$field} = 1;
                   20257:                         }
                   20258:                     }
                   20259:                 }
                   20260:             }
                   20261:         }
                   20262:     }
                   20263:     return %menu;
                   20264: }
                   20265: 
1.112     bowersj2 20266: 1;
                   20267: __END__;
1.41      ng       20268: 

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